Java Con Currency Look2

download Java Con Currency Look2

of 66

Transcript of Java Con Currency Look2

  • 8/8/2019 Java Con Currency Look2

    1/66

    Java Concurrency

    Java Team

  • 8/8/2019 Java Con Currency Look2

    2/66

    Concurrency

    New in Java 5: java.util.concurrent

    Thread Pools, Task Scheduling

    Concurrent Collections

    Atomic variables

    Locks, Conditions, Synchronizers

    Enhance scalability, performance,

    readability and

    thread safety of Java applications

    Provide richer set of concurrency

  • 8/8/2019 Java Con Currency Look2

    3/66

    Threads

    Threads are expensive to create, can require500K of memory during creation

    Your threads spend a lot of time context-switching, even if you have 10 processors

    Whenever you want to start a thread, dont useThreads:

    use Executor

  • 8/8/2019 Java Con Currency Look2

    4/66

    Disadvantage of usingThreadsCreating a new thread causes someperformance overhead .

    Too many threads can lead to reducedperformance, as the CPU needs to switchbetween these threads.

    You cannot easily control the number of

    threads, therefore you may run into out ofmemory errors due to too many threads.

  • 8/8/2019 Java Con Currency Look2

    5/66

    Why Concurrency?

    wait(), notify(), and synchronize are

    hard to use, specified at a low level,

    can lead to poor performance

    Lots of wheel reinventing

    Reduced programming effort

    Increased performance

    Increased reliability

    > Eliminate threading hazards such

    as deadlock, starvation,

    race conditions, or excessive

  • 8/8/2019 Java Con Currency Look2

    6/66

    Goal of Concurrency

    Do what Collections did for data structures

    Allow development of thread-safe classes, such

    as servlets, built on concurrent building blocks(like ConcurrentHashMap)

    Make some solved things easier for

    masses

    Make very hard things solvable by

    experts

  • 8/8/2019 Java Con Currency Look2

    7/66

    Concurrency Utilities

    Task Scheduling Framework

    Callable's and Future's

    Synchronizers

    Concurrent Collections

    Atomic Variables

    Locks

    Nanosecond-granularity timing

  • 8/8/2019 Java Con Currency Look2

    8/66

    Concurrency:

    Task Scheduling

    Framework

  • 8/8/2019 Java Con Currency Look2

    9/66

    Task SchedulingFrameworkExecutor/ExercuteService/Executorsframework supports

    > standardizing invocation> scheduling

    > execution

    > control of asynchronous tasks according toa set of execution Policies

    Executor is an interface

    ExecutorService extends Executor

  • 8/8/2019 Java Con Currency Look2

    10/66

    Why Prefer Executor?Executor framework allows for a variety ofexecution policies

    Provides cancellation and shutdown support

    Created via factory

    Can customize shutdown hooks

    Simpler interface

    provides a way of de-coupling task

    submission from the execution

    Many Executor implementations impose some

    sort of

  • 8/8/2019 Java Con Currency Look2

    11/66

    Task Scheduling(Executor)Use anExecutor.execute(aRunnable)

    Do NOT use new Thread(aRunnable).start()

    Executor executor = anExecutor;

    executor.execute(new RunnableTask1());

    executor.execute(new RunnableTask2());

    try

    http://opt/scribd/conversion/workspace/ConcurrentEXamples/src/executor/executer.javahttp://opt/scribd/conversion/workspace/ConcurrentEXamples/src/executor/executer.java
  • 8/8/2019 Java Con Currency Look2

    12/66

    Executer interface

    Executor, a simple interface that supportslaunching new tasks.

    ExecutorService, a subinterface of Executor,which adds features that help manage thelifecycle, both of the individual tasks and of theexecutor itself.

    ScheduledExecutorService, a subinterface ofExecutorService, supports future and/or periodicexecution of tasks.

  • 8/8/2019 Java Con Currency Look2

    13/66

    Executor Interface

    functionsexecute(Runnable command)

    Executes the given command at some time in

    the future.

    http://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Executor.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/lang/Runnable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Executor.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/lang/Runnable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/lang/Runnable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Executor.html
  • 8/8/2019 Java Con Currency Look2

    14/66

  • 8/8/2019 Java Con Currency Look2

    15/66

    Executor Service

    ExecutorService supports graceful andimmediate shutdown

    Has a lifecycleHas many useful utility methods

    Can get a single threaded executor

    Bad Example: Webserver in a while() looplistens forever and starts a new thread

    for each request.

  • 8/8/2019 Java Con Currency Look2

    16/66

    Executor Service

    Methodssubmit(Callable task)Submits a value-returning task for executionand returns a Future representing the pending

    results of the task.

    submit(Runnable task)

    Submits a Runnable task for execution and

    returns a Future representing that task.

    submit(Runnable task, T result)

    Submits a Runnable task for execution and

    returns a Future representing that task that willu on com letion return the iven result.

    http://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/ExecutorService.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Callable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/ExecutorService.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Callable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/ExecutorService.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/lang/Runnable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/ExecutorService.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/lang/Runnable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/lang/Runnable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/ExecutorService.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/lang/Runnable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/ExecutorService.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Callable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/ExecutorService.html
  • 8/8/2019 Java Con Currency Look2

    17/66

    Creating ExecutorService From

    Executorspublic class Executors

    {

    static ExecutorService newSingleThreadedExecutor();

    static ExecutorService newFixedThreadPool(int n);

    static ExecutorService newCachedThreadPool(int n);

    static ScheduledExecutorService

    newScheduledThreadPool(int n);

    // additional versions specifying ThreadFactory

    // additional utility methods

    }

  • 8/8/2019 Java Con Currency Look2

    18/66

    Using Executor

    Executor pool =

    Executor.newFixedThreadPool(7);

    socket.accept(); Runnable r = new Runnable() {

    //handle request

    }

    pool.execute();

  • 8/8/2019 Java Con Currency Look2

    19/66

    pre-J2SE 5.0 CodeWeb Serverpoor resource managementclass WebServer

    {

    public static void main(String[] args)

    {

    ServerSocket socket = newServerSocket(80);

    while (true) {

    final Socket connection =socket.accept();

    Runnable r = new Runnable() {

  • 8/8/2019 Java Con Currency Look2

    20/66

    Executors ExampleWeb Serverbetter resource managementclass WebServer

    {

    Executor pool

    =Executors.newFixedThreadPool(7);

    public static void main(String[] args)

    {

    ServerSocket socket = newServerSocket(80);

    while (true) {

    final Socket connection =

  • 8/8/2019 Java Con Currency Look2

    21/66

    ScheduledExecutorService

    SES is a drop-in replacement forTimer Supports pooling

    final ScheduledFuturebeeperHandle =

    scheduler.scheduleAtFixedRate(beeper,10, 10, SECONDS);

    scheduler.schedule(new Runnable()

  • 8/8/2019 Java Con Currency Look2

    22/66

    Functions

    schedule(Callable callable, long delay,TimeUnit unit)

    Creates and executes a ScheduledFuture thatbecomes enabled after the given delay.

    scheduleAtFixedRate(Runnable command,long initialDelay, long period,TimeUnit unit)

    Creates and executes a periodic action thatbecomes enabled first after the given initialdelay, and subsequently with the given period;

    scheduleWithFixedDelay(Runnablecommand lon initialDela lon dela

    http://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/ScheduledExecutorService.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Callable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/TimeUnit.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/ScheduledExecutorService.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/lang/Runnable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/TimeUnit.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/ScheduledExecutorService.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/lang/Runnable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/lang/Runnable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/ScheduledExecutorService.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/TimeUnit.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/lang/Runnable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/ScheduledExecutorService.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/TimeUnit.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Callable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/ScheduledExecutorService.html
  • 8/8/2019 Java Con Currency Look2

    23/66

    Concurrency:Callablesand Futures

  • 8/8/2019 Java Con Currency Look2

    24/66

    Callable's and

    Future's:Problem (pre-J2SE

    5.0)

    If a new thread (callable thread) is started in an

    application, there is currently no way to return

    a result from that thread to the thread (callingthread) that started it without the use of ashared variable and appropriate synchronization

    > This is complex and makes code harder to

    understand and maintain

  • 8/8/2019 Java Con Currency Look2

    25/66

    Interface Callable

    Functional analog ofRunnable.

    It is similar to Runnable, in that both are

    designed for classes whose instances are

    potentially executed by another thread. A

    Runnable, however, does not return a result

    and cannot throw a checked exception.

    public interface Callable

    {

    V call() throws Exception;

    }

    http://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/lang/Runnable.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/lang/Runnable.html
  • 8/8/2019 Java Con Currency Look2

    26/66

    Callables and Futures

    Callable thread (Callee) implements Callableinterface

    > Implement call() method rather than run()Calling thread (Caller) submits Callable object toExecutor and then moves on

    > Through submit() not execute()

    > The submit() returns a Future object

    Calling thread (Caller) then retrieves the resultusing get() method of Future object

    > If result is read it is returned

  • 8/8/2019 Java Con Currency Look2

    27/66

    Runnable vs Callable

    Runnable Callable

    class c1 implementsRunnable

    {

    public void run()

    {

    //

    }

    }

    class c1 implementsCallable

    {

    public String call() throwsException

    {

    //

    return null;

    }

  • 8/8/2019 Java Con Currency Look2

    28/66

    Future

    Holds result of asynchronous call, normally aCallable. Can find out if this task is

    complete, cancelled, etc.

    Implementing caches is tricky--often were

    just moving the bottleneck from computation

    to serialization most of the time.

  • 8/8/2019 Java Con Currency Look2

    29/66

    Future functions

    cancel(boolean mayInterruptIfRunning)

    Attempts to cancel execution of this task.

    get()

    Waits if necessary for the computation tocomplete, and then retrieves its result.

    get(long timeout,TimeUnit unit)Waits if necessary for at most the given time forthe computation to complete, and thenretrieves its result, if available.

    isCancelled()

    http://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Future.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Future.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Future.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/TimeUnit.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Future.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Future.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/TimeUnit.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Future.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Future.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/Future.html
  • 8/8/2019 Java Con Currency Look2

    30/66

    Build CallableExample

    (This is Callee)class CallableExample implementsCallable

    {

    public String call() {

    String result = The work is ended;

    /* Do some work and create a result */

    return result;

    }

  • 8/8/2019 Java Con Currency Look2

    31/66

    Future Example

    (Caller)class FutureDemo{

    public static void main(String[] args){

    ExecutorService es=Executors.newSingleThreadExecutor();

    Future f =es.submit(newCallableExample());

    /* Do some work in parallel */

    try {

  • 8/8/2019 Java Con Currency Look2

    32/66

    Concurrency:Synchronizers

  • 8/8/2019 Java Con Currency Look2

    33/66

    Semaphores

    Typically used to restrict access to fixed sizepool of

    resourcesNew Semaphore object is created with samecount

    as number of resources

    Thread trying to access resource calls aquire()

    > Returns immediately if semaphore count> 0

    > Blocks if count is zero until release is

  • 8/8/2019 Java Con Currency Look2

    34/66

    Semaphore

    A counting semaphore. Conceptually, asemaphore maintains a set of permits. Eachacquire() blocks if necessary until a permit is

    available, and then takes it. Each release() addsa permit, potentially releasing a blockingacquirer.

    A Semaphore is a thread synchronizationconstruct that can be used either to sendsignals between threads to avoid missed signals

    , or to guard a critical section like you would

    http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Semaphore.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Semaphore.htmlhttp://tutorials.jenkov.com/java-concurrency/thread-signaling.htmlhttp://tutorials.jenkov.com/java-concurrency/race-conditions-and-critical-sections.htmlhttp://tutorials.jenkov.com/java-concurrency/locks.htmlhttp://tutorials.jenkov.com/java-concurrency/race-conditions-and-critical-sections.htmlhttp://tutorials.jenkov.com/java-concurrency/thread-signaling.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Semaphore.htmlhttp://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Semaphore.html
  • 8/8/2019 Java Con Currency Look2

    35/66

    Semaphore Exampleprivate Semaphore available;

    private Resource[] resources;

    private boolean[] used;

    public Resource(int poolSize) {

    available = new Semaphore(poolSize);

    /* Initialise resource pool */

    }

    public Resource getResource() {

    try { available.aquire() } catch (IE) {}

    /* Acquire resource */

    }

    public void returnResource(Resource r) {

    /* Return resource to pool */

    available.release();

    }

  • 8/8/2019 Java Con Currency Look2

    36/66

    Synchronizers

    Utility classes

    Low level

  • 8/8/2019 Java Con Currency Look2

    37/66

    Latches

    A latch is a synchronizer that can delay the progress ofthreads until it reaches its terminal state. A latch acts asa gate: until the latch reaches the terminal state thegate is closed and no thread can pass, and in theterminal state the gate opens, allowing all threads topass. Once the latch reaches the terminal state, itcannot change state again, so it remains open forever.

    Latches can be used to ensure that certain activities do

    not proceed until other one-time activities complete,such as:

  • 8/8/2019 Java Con Currency Look2

    38/66

    Latches (Cont.)

    Ensuring that a computation does not proceed untilresources it needs have been initialized. A simplebinary (two-state) latch could be used to indicate

    "Resource R has been initialized", and any activitythat requires R would wait first on this latch.

    Ensuring that a service does not start until otherservices on which it depends have started. Each

    service would have an associated binary latch;starting service S would involve first waiting on thelatches for other services on which S depends, andthen releasing the S latch after startup completesso any services that depend on S can then proceed.

  • 8/8/2019 Java Con Currency Look2

    39/66

    New Synchronizers:

    Semaphor: Represents a permit manager

    CountdownLatch: Gate with one or more

    padlocks -- allows 1 or more threads to wait fora set of threads to complete action

    Exchanger: Allows two threads to rendezvousand exchange data, then go their separate

    ways.

  • 8/8/2019 Java Con Currency Look2

    40/66

    CountDownLatch

    CountDownLatch is a flexible latch

    implementation that can be used in any ofthese situations; it allows one or more threadsto wait for a set of events to occur. The latchstate consists of a counter initialized to apositive number, representing the number ofevents to wait for. The countDown methoddecrements the counter, indicating that anevent has occurred, and the await methods waitfor the counter to reach zero, which happens

    when all the events have occurred. If the

  • 8/8/2019 Java Con Currency Look2

    41/66

    Barriers

    This is a synchronization aid that allows a set ofthreads to all wait for each other to reach acommon barrier point. The interface to the

    barrier is the CyclicBarrier class, called cyclicbecause it can be re-used after the waitingthreads are released. This is useful for parallelprogramming.

    Barriers are similar to latches in that they blocka group of threads until some event has

    occurred. The key difference is that with a

  • 8/8/2019 Java Con Currency Look2

    42/66

    CyclicBarrier

    CyclicBarrier allows a fixed number of parties torendezvous repeatedly at a barrier point and is useful inparallel iterative algorithms that break down a probleminto a fixed number of independent subproblems.

    Threads call await when they reach the barrier point, andawait blocks until all the threads have reached thebarrier point. If all threads meet at the barrier point, thebarrier has been successfully passed, in which case allthreads are released and the barrier is reset so it can beused again.

  • 8/8/2019 Java Con Currency Look2

    43/66

    CyclicBarrier (Cont.)

    If a call to await times out or a thread blocked inawait is interrupted, then the barrier is consideredbroken and all outstanding calls to await terminate

    with BrokenBarrierException. If the barrier issuccessfully passed, await returns a unique arrivalindex for each thread, which can be used to "elect"a leader that takes some special action in the nextiteration. CyclicBar rier also lets you pass a barrier

    action to the constructor; this is a Runnable that isexecuted (in one of the subtask threads) when thebarrier is successfully passed but before the blockedthreads are released.

  • 8/8/2019 Java Con Currency Look2

    44/66

    Difference Between

    Latch and BarrierBarrier: This is a synchronization aid thatallows a set of threads to all wait for each otherto reach a common barrier point. The interface

    to the barrier is the CyclicBarrier class, calledcyclic because it can be re-used after thewaiting threads are released. This is useful forparallel programming.

    CountDown Latch: A latch is a conditionstarting out false, but once set true remainstrue forever. The

    java.util.concurrent.CountDownLatch class

  • 8/8/2019 Java Con Currency Look2

    45/66

    Exchanger

    Allows two threads to exchange objects at a rendezvouspoint, and can be useful in pipeline designs. Each threadpresents some object on entry to the exchange() methodand receives the object presented by the other thread onreturn. As an example, consider the classical consumer-producer problem (two entities share a channel);

  • 8/8/2019 Java Con Currency Look2

    46/66

    Concurrency: Concurrent

    Collections

  • 8/8/2019 Java Con Currency Look2

    47/66

    Concurrent Collections

    Pre Java 5 was thread-safe but not concurrent.

    Every method was synchronized. This was okay becausewe werent on multi-core machines.

    Azul has a 384-way box now--running Java on that would

    have been problematic.

    Old collections required locking during iteration.

  • 8/8/2019 Java Con Currency Look2

    48/66

    New:

    ConcurrentHashMapDrop-in replacement for HashtableNo iterator throws

    ConcurrentModificationException

    Allows read/write overlaps.

    It is therefore weakly concurrent

  • 8/8/2019 Java Con Currency Look2

    49/66

    New:

    CopyOnWriteArrayListLocking during iteration hurts scalability.Changes made by other threads may or maynot be noticed by reads

  • 8/8/2019 Java Con Currency Look2

    50/66

    New: BlockingQueue

    A blocking queue is a queue that blocks whenyou try to dequeue from it and the queue isempty, or if you try to enqueue items to it and

    the queue is already full.

    Extends Queue to provide two operations:

    take(): wait for queue to be non-empty

    put(): wait for queue to have room

  • 8/8/2019 Java Con Currency Look2

    51/66

    BlockingQueue

    InterfaceProvides thread safe way for multiple threads tomanipulate collection

    ArrayBlockingQueue is simplest concreteimplementation

    Full set of methods

    > put()> offer() [non-blocking]

    > peek()

    > take()

  • 8/8/2019 Java Con Currency Look2

    52/66

    Blocking Queue

    Example 1private BlockingQueue msgQueue;public Logger(BlockingQueue mq)

    { msgQueue = mq; }

    public void run()

    {

    try {

    while (true) {

    String message = msgQueue.take();

    /* Lo messa e */

    Bl ki Q

  • 8/8/2019 Java Con Currency Look2

    53/66

    Blocking Queue

    Example 2private ArrayBlockingQueue messageQueue =newArrayBlockingQueue(10);Logger logger = new Logger(messageQueue);

    public void run()

    {

    String someMessage;

    try {

    while (true) {

    /* Do some processing */

    * Blocks if no s ace available *

  • 8/8/2019 Java Con Currency Look2

    54/66

    Concurrency: Locks

  • 8/8/2019 Java Con Currency Look2

    55/66

    Use of monitor

    synchronization is finefor most apps BUT:Single wait-set per lock

    No way to interrupt a thread waiting for a lock

    No way to time out when waiting for a lock

    Locking must be block-structured

    Inconvenient to acquire a variable number of

    locks at once.Advanced techniques not possible

    Lock objects address these concerns

  • 8/8/2019 Java Con Currency Look2

    56/66

    Locks

    Lock interface

    > More extensive locking operations than synchronizedblock

    > No automatic unlocking use try/finally to unlock

    > Non-blocking access using tryLock()

    ReentrantLock

    > Concrete implementation of Lock

    > Holding thread can call lock() multiple times and notblock

    > Useful for recursive code

  • 8/8/2019 Java Con Currency Look2

    57/66

    Lock Objects

    Address synchronization monitor issues

    Provide a high-level interface:

    lock

    tryLock (tells you if you got it)

    unlock

    newCondition (every object cant provideconditions)

  • 8/8/2019 Java Con Currency Look2

    58/66

    ReentrantLock

    High-Performance

    Re-entrant, mutual exclusion lock offers samesemantics as synchronized but with extrafeatures

    Can interrupt a thread waiting to acquire a lock

    Can specify a timeout while waiting

    Can poll for lock availability

    Downside: have to manually unlock (in finally{})

  • 8/8/2019 Java Con Currency Look2

    59/66

    Re-entrant Lock Example

    Lock lock = new ReentrantLock();

    lock.lock();

    try {

    //do work

    } catch {

    //resolve invariants and rethrow }

    finally {

    lock.unlock(); }

    ReadWriteLock

  • 8/8/2019 Java Con Currency Look2

    60/66

    ReadWriteLockHas two locks controlling read and write access

    > Multiple threads can acquire the read lock if no threads

    have a write lock

    > If a thread has a read lock, others can acquire read lock

    but nobody can acquire write lock

    > If a thread has a write lock, nobody can have read/write lock

    > Methods to access locks

    rwl.readLock().lock();

    rwl.writeLock().lock();

  • 8/8/2019 Java Con Currency Look2

    61/66

    ReadWriteLock

    Multiple reader, single writer exclusion lock

    ReadWriteLock class defines a pair of locks:

    interface ReadWriteLock {

    Lock readLock();

    Lock writeLock();

    }

    Use for frequent, long reads w/ few writes.

    Various implementation policies

  • 8/8/2019 Java Con Currency Look2

    62/66

    ReadWrite Lock

    Exampleclass ReadWriteMap{

    final Map m = newTreeMap();

    final ReentrantReadWriteLock rwl =newReentrantReadWriteLock();

    final Lock r = rwl.readLock();

    final Lock w = rwl.writeLock();

    public Data get(String key)

  • 8/8/2019 Java Con Currency Look2

    63/66

    Condition Interface

    Conditions (also known as condition queues orcondition variables) provide a means for onethread to suspend execution (to "wait") until

    notified by another thread that some statecondition may now be true. Because access tothis shared state information occurs in differentthreads, it must be protected, so a lock of some

    form is associated with the condition. The keyproperty that waiting for a condition provides isthat it atomicallyreleases the associated lockand suspends the current thread, just like

    Object.wait.

  • 8/8/2019 Java Con Currency Look2

    64/66

    Atomic Variables

    Until JDK 5.0, it was not possible to write wait-free, lock-free algorithms in the Java languagewithout using native code. With the addition of

    the atomic variables classes in thejava.util.concurrent.atomic package, that haschanged. The atomic variable classes all exposea compare-and-set primitive (similar to

    compare-and-swap), which is implementedusing the fastest native construct available onthe platform (compare-and-swap, loadlinked/store conditional, or, in the worst case,

    spin locks).

  • 8/8/2019 Java Con Currency Look2

    65/66

    Few Classes in Atomic

    AtomicBooleanAtomicIntegerAtomicIntegerArray

    AtomicIntegerFieldUpdaterAtomicLongAtomicLongArray

    http://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/atomic/AtomicBoolean.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/atomic/AtomicInteger.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/atomic/AtomicIntegerArray.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/atomic/AtomicLong.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/atomic/AtomicLongArray.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/atomic/AtomicLongArray.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/atomic/AtomicLong.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/atomic/AtomicIntegerFieldUpdater.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/atomic/AtomicIntegerArray.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/atomic/AtomicInteger.htmlhttp://g/2.Training/Java/JavaMaterials/Java/Java%20v5.0%20API%20Docs/api/java/util/concurrent/atomic/AtomicBoolean.html
  • 8/8/2019 Java Con Currency Look2

    66/66

    Thank You.