Java concurrency helps developers to work with multi-threaded programs using features like Thread, synchronized and volatile. Threads communicate by calling a method of another thread. Some thread coordination methods are start, join and interrupt. A deadlock occurs when there is more than one thread, each waiting for the resource held by another. Starvation occurs when a thread holds a lock when some other starve without any progress. Wait/notify methods are used when one thread needs to signal when other thread waits till the condition is met.
A race condition occurs when more than one thread is performing actions on shared resources and several outcomes can exist with the order of the actions from each thread. Therefore, locking establishes the guarantee of the orderings. The monitor in every object provide mutual exclusion access to critical sections of code. Critical section is specified by marking as synchronized in a method or code block. Only one thread is allowed to enter the critical section for a particular monitor. Other threads have to wait for the monitor to be released.
java.util.concurrent.locks packages has a standard Lock interface. ReentrantLock implementation dublicated the functionality of the synchronized keyword with functionlity to obtain information about the state of lock. ReadWriteLock interface and ReentrantReadWrite Lock implementation define pair of locks for reading and writing. volatile modifier marked in a field indicate that the changes to that field must be seen by all subsequent reads by other threads.
java.util.concurrent package inculdes data structures designed for concurrent use. Use of these data structures gives better performances than using a synchoronized wrapper around an unsynchronized collection. As an example, CopyOnWriteArrayList is a thread-safe ArrayList where each modification of the data structure results in a new internal copy of the data. Queue acts as a "first in first out(FIFO)" adding elements in one end and removing from other end. BlockingQueue interface extends Queue and provide additional functionality how to handle the scenario where a queue may be full. Deque supports adding and removing from both ends, not adding from one end and removing from other end.
There are several classes for multi-thread communication such as CyclicBarrier, CountDownLatch, Semaphore and Exchanger. In task execution using a pool of workers, Executor and more ExecutorService interfaces define the contract for a component that can execute tasks.
No comments:
Post a Comment