Title: Capital District JavaDevelopers Network
1Capital DistrictJavaDevelopers Network
- java.util.concurrent
- presented by Rod Sprattling
- 11 January 2006
2java.util.concurrent
- New in Java 5.0
- Provides concurrent programming utilities
- Three categories
- Asynchronous execution framework
- Thread synchronization classes (synchronizers)
- Thread-safe Collections classes
3Asynchronous ExecutionFramework
- Existing Thread models
- Subclass Thread
- class Worker extends Thread private List
worklist - private int status private int doTheWork()
public Worker(List worklist) this.worklist
worklist public void run() status
doTheWork() -
- Thread happyCog new Worker(todaysWorkList)
- happyCog.start()
- Implement a Runnable
- Thread workerThread new Thread( new Runnable()
public void run() -
w new Worker(todaysWorklist) -
status w.doTheWork() -
-
)) - workerThread.start()
4Asynchronous ExecutionFramework
- Java 5 lets you add handler for uncaught thread
exceptions - Thread workerThread new Thread( new Runnable()
public void run() -
w new Worker(todaysWorklist) -
status w.doTheWork() -
if (status WorkStatus.INCOMPLETE)
throw new WorkIncompleteException() -
-
) - workerThread.setUncaughtException(new
WorkThread.WorkIncompleteException() - public void uncaughtException(Thread t,
Throwable e) - System.err.printf(...)
-
- )
5Asynchronous ExecutionFramework
- Callable interface
- Defines methods for a task
- Like Runnable, but
- Uses call() instead of run() method
- Unlike run(), call() can return a result and can
throw exceptions - Executable by ExecutorService andScheduled
ExecutorService
6Asynchronous ExecutionFramework
- Executor interface
- Defines methods for executing Runnable object
- import java.util.concurrent
- class ThreadExecutor implements Executor
- public void execute(Runnable r) ( r.run() )
-
- // Or, to run it in a new thread
- class ThreadExecutor implements Executor
- public void execute(Runnable r) ( new
Thread(r).start() ) -
7Asynchronous ExecutionFramework
- ExecutorService interface
- Defines methods for executing Runnable and
Callable objects - import java.util.concurrent
- public class KeywordSearch implements
CallableltMatchListgt - InputStream is
- ListltStringgt wordList
- public KeywordSearch(InputStream intercept,
ListltStringgt keywords) - is intercept wordList keywords
-
- private MatchList searchForMatches(InputStream
is, ListltStringgt wordList) - public MatchList call() return(searchForMatche
s(is, wordList) -
- ExecutorService threadPool Executors.newFixedThr
eadPool(3) - ListltStringgt keywords loadKeywords()
- ListltInputStreamgt streams openInputStreams()
8Asynchronous ExecutionFramework
- ExecutorService interface
- That Future object returned by submit() is your
Callable task chit. With it you can - cancel() execution
- check if execution was cancelled using
isCancelled() - call isDone() to see if it's completed
- call get() to get the results (careful get()
blocks until call() has completed.)
9Asynchronous ExecutionFramework
- ScheduledExecutorService interface
- Extends ExecutorService
- Use to schedule a
- Runnable or Callable to be executed once after a
specified delay, or - A Runnable for repeated execution
10Asynchronous ExecutionFramework
- ThreadPoolExecutor implementation
- ThreadPoolExecutor implements ExecutorService to
execute tasks using a thread pool - Maintains caller-specified work queue
- Manages thread pool size and use depending upon
queue type and contents, and keepAlive parameter - Easy instantiation through Executors factory
class - Work queue is implementation of BlockingQueue
interface LinkedBlockingQueue,
PriorityBlockingQueue, ArrayBlockingQueue,
SynchronousQueue are provided by lib.
11Asynchronous ExecutionFramework
- ScheduledThreadPoolExecutor implementation
- Extends ThreadPoolExecutor to let tasks be
submitted for future execution - Adds three schedule methods
- Adds shutdown() method
- Introduces set/get methods for after-shutdown
policies - Easy instantiation through Executors factory class
12Synchronizers
- Classes used to synchronize multiple threads
- Semaphore
- maintains one or more permits
- acquire() method blocks until a permit is
available, then decrements permits count and
returns - release() method increments permits count
13Synchronizers
- Semaphore example
- class Pool
- private static final MAX_AVAILABLE 100
- private final Semaphore available new
Semaphore(MAX_AVAILABLE, true) - public Object getItem() throws
InterruptedException - available.acquire()
- return getNextAvailableItem()
-
- public void putItem(Object x)
- if (markAsUnused(x))
- available.release()
-
- // Not a particularly efficient data
structure just for demo - protected Object items ... whatever kinds
of items being managed - protected boolean used new
booleanMAX_AVAILABLE
14Synchronizers
- ExchangerltVgt
- Lets two threads exchange data
- Each thread calls exchange() with value of type V
that it wants to exchange - exchange() returns value V to each thread
- Timed version of exchange() throws
TimeoutException if exchange isn't performed
within timeout period
15Synchronizers
- ExchangerltVgt example
- try // Consumer thread
- while (currentBuffer ! null)
- takeFromBuffer(currentBuffer)
- if (currentBuffer.empty())
- currentBuffer exchanger.exchange(currentBuff
er) -
- catch (InterruptedException ex)
- // ... handle ...
-
- try // Producer thread
- while (currentBuffer ! null)
- addToBuffer(currentBuffer)
- if (currentBuffer.full())
- currentBuffer exchanger.exchange(currentBuff
er) -
- catch (InterruptedException ex)
16Synchronizers
- CountDownLatch
- Synchronizes two or more threads
- Each thread calls await() and blocks until
countDown() method is called n times, with n
specified at CountDownLatch object creation - getCount() returns remaining count
- CountDownLatch is single-use
17Synchronizers
- CountDownLatch example
-
- class Driver // ...
- void main() throws InterruptedException
- CountDownLatch startSignal new
CountDownLatch(1) - CountDownLatch doneSignal new
CountDownLatch(N) - for (int i 0 i lt N i) // create and
start threads - new Thread(new Worker(startSignal,
doneSignal)).start() - doSomethingElse() // don't let
run yet - startSignal.countDown() // let all
threads proceed - doSomethingElse()
- doneSignal.await() // wait for
all to finish -
-
- class Worker implements Runnable
- private final CountDownLatch startSignal
18Synchronizersh
- CyclicBarrier
- Synchronizes n threads, with n specified when
CyclicBarrier is created - Each thread calls await() and blocks until n
threads are waiting, with n specified at
CountDownLatch object creation - Can optionally pass Runnable barrier action to
CyclicBarrier constructor, which is executed in
last thread calling await() - Return value of await() is integer order of that
thread's call to await()
19Synchronizers
- CyclicBarrier
- All threads blocked on await() are unblocked with
a BrokenBarrierException if - Any blocked thread times out or is interrupted
- The CyclicBarrier is reset using reset()
- isBroken() confirms broken state
- reset() restores for reuse
- getNumberWaiting() tells number of threads
waiting at barrier - getParties() tells number of parties needed to
trip barrier
20Synchronizers
- CyclicBarrier example
- class Worker implements Runnable
- int myRow
- Worker(int row) myRow row
- public void run()
- while (!done())
- processRow(myRow)
- try
- barrier.await()
- catch (InterruptedException ex)
- return
- catch (BrokenBarrierException ex)
- return
-
-
-
-
21Thread-Safe Collections Classes
- ConcurrentLinkedQueue
- Implementation of java.util.Queue interface
- No synchronized methods used
- non-blocking
- Unbounded FIFO
- No nulls allowed
22Thread-Safe Collections Classes
- CopyOnWriteArrayList, CopyOnWriteArraySet
- Implementation of java.util.List and
java.util.Set interfaces. - All update methods are synchronized
- CopyOnWriteArrayList iterator doesn't see updates
that occur after call to iterator().
23Thread-Safe Collections Classes
- ConcurrentMapltK,Vgt
- Extends java.util.Map interface to add four
atomic methods putIfAbsent(), remove() and two
replace() methods
24Thread-Safe Collections Classes
- ConcurrentHashMapltK,Vgt
- Implements ConcurrentMap interface
- No synchronized methods used
- No locking required for reads
- Only segment of internal data structure being
updated is locked on write, not entire data
structure. Can specify number of segments at
construction. - Intended as replacement for java.util.Hashtable
25System.exit()