Mega Code Archive

 
Categories / Java Book / 007 Thread Conncurrent
 

0405 Concurrent Collections

The java.util.concurrent package has several interfaces and classes that are concurrency-oriented extensions to the Collections Framework. BlockingDeque is a subinterface of BlockingQueue and java.util.Deque. BlockingDeque supports blocking operations. The LinkedBlockingDeque class implements BlockingDeque. BlockingQueue is a subinterface of java.util.Queue that supports blocking operations. ArrayBlockingQueue, DelayQueue, LinkedBlockingDeque, LinkedBlockingQueue, LinkedTransferQueue, PriorityBlockingQueue, and SynchronousQueue classes implements BlockingQueue. TransferQueue is a subinterface of BlockingQueue and describes a blocking queue in which producers may wait for consumers to receive elements. The LinkedTransferQueue class implements this interface. ConcurrentMap is a subinterface of java.util.Map that declares additional atomic putIfAbsent(), remove(), and replace() methods. The ConcurrentHashMap class and the ConcurrentSkipListMap class implement this interface. ConcurrentNavigableMap is a subinterface of ConcurrentMap and java.util.NavigableMap. The ConcurrentSkipListMap class implements this interface. ConcurrentLinkedDeque is an unbounded concurrent deque based on linked nodes. ConcurrentLinkedQueue is an unbounded thread-safe FIFO implementation of the Queue interface. ConcurrentSkipListSet is a scalable concurrent NavigableSet implementation. CopyOnWriteArrayList is a thread-safe java.util.ArrayList. CopyOnWriteArraySet is a java.util.Set implementation that uses an internal CopyOnWriteArrayList instance for all its operations. import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) { final BlockingQueue<Character> bq = new ArrayBlockingQueue<Character>(26); final ExecutorService executor = Executors.newFixedThreadPool(2); Runnable producer; producer = new Runnable() { public void run() { for (char ch = 'A'; ch <= 'F'; ch++) { try { bq.put(ch); System.out.println("putting:"+ch); } catch (InterruptedException ie) { assert false; } } } }; executor.execute(producer); Runnable consumer; consumer = new Runnable() { public void run() { char ch = '\0'; do { try { ch = bq.take(); System.out.println("getting:"+ch); } catch (InterruptedException ie) { } } while (ch != 'F'); executor.shutdownNow(); } }; executor.execute(consumer); } }