Professor Abdul-Quader
Concurrency
Take a look at the Increment.java
program.
NUM_THREADS * NUM_INCREMENTS
.Not just one instruction! Actually:
someRunnableObject.run()
class C extends Thread
and override run
Runnable
Earlier: created Threads directly. Don’t ever do that. Creating a thread involves:
Some tradeoffs should be thought about:
Thread pools: re-use threads that were already created.
There is a framework for this in Java: Executor and ExecutorService objects:
This is very flexible – many possible “execution” policies. See Java Concurrency in Practice.
A deadlock is when several processes / threads are all waiting for each other to finish working before they can do their work.
A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code. — Java Concurrency In Practice
In general, what is most worrisome is state.
synchronized
keyword.A Vector
is like an ArrayList
, with all of its methods synchronized. Is the following code thread-safe?
See ListRaceCondition. What happens when we run the code? Play around with the type of “Executor” we use (single vs multithreaded).
Question: why do we see a NullPointerException
? What is the race condition here?
add
calls the following:
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}