Tuesday, November 30, 2010

5 things you didn't know about ... java.util.concurrent

http://www.ibm.com/developerworks/java/library/j-5things4.html


    CopyOnWriteArrayList is a thread-safe variant of ArrayList with all mutative operations (add, set, and so on) implemented to make a fresh copy of the array - ideal for the read-often, write-rarely scenario such as Listeners of a JavaBean event.






    BlockingQueue is a first in, first out (FIFO) Queue which blocks the thread if it tries to get from an empty queue until an item is added by another thread; and for the bounded variety will block the thread on any attempt to insert an item into a full queue until space becomes available in the queue's storage.






    ArrayBlockingQueue can give reader and writer threads first in, first out access (it would be a more efficient to allow readers to run while other readers held the lock, but you'd risk a constant stream of reader threads keeping the writer from ever doing its job.)






    BlockingQueue neatly solves the problem of how to "hand off" items from one thread to another thread without explicitly synchronizing.






    Doing (if Map.get() == null) Map.put() is a race condition; ConcurrentMap supports putIfAbsent() that does the test first then does a put only if the key isn't already stored in the Map.






    SynchronousQueue is a BlockingQueue in which each insert operation must wait for a corresponding remove operation by another thread and vice versa - i.e. the threads always operate synchronously across this queue





No comments: