Tuesday, September 16, 2014

Concurrency in Java

Old way before 1.5, you canuse Thread, Runnable, Synchronized and Object.wait, notify, notifyAll to control the concurrency between multiple threads.

From 1.5  on, more sophisticated framework is available for bigger scale of systems. Most frequently used concepts are Executor, Future,Lock and Condition etc.

Condition factors out the Object monitor methods (waitnotify and notifyAll) into distinct objects to give the effect of having multiple wait-sets per object, by combining them with the use of arbitrary Lock implementations. Where a Lock replaces the use of synchronized methods and statements, a Condition replaces the use of the Object monitor methods.

Understanding Lock and Condition

http://web.stanford.edu/~ouster/cgi-bin/cs140-winter13/lecture.php?topic=locks

Lock

an object that can only be owned by a single thread at any given time. Basic operations on a lock. basic operations are acquire and release. Thread exclusively own a lock.

Condition

  • Synchronization mechanisms need more than just mutual exclusion; also need a way to wait for another thread to do something (e.g., wait for a character to be added to the buffer)
  • Condition variables: used to wait for a particular condition to become true
  • basic operations: wait, signal(notify)
    • wait(condition, lock): release lock, put thread to sleep until condition is signaled; when thread wakes up again, re-acquire lock before returning.
    • signal(condition, lock): if any threads are waiting on condition, wake up one of them. Caller must hold lock, which must be the same as the lock used in the wait call.

Semaphore

Basically semaphore maintains a set of permits, basic operations are acquire and release, thread will wait if it can not acquire a permit, release will make a permit available. it's often used as a way to restrict number of threads that can access a certain resource.

CountdownLatch

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset.

CyclicBarrier

wait until required number of waits.

TransferQueue

A BlockingQueue in which producers may wait for consumers to receive elements.

No comments: