Docstoc

java concurrency

Document Sample
java concurrency Powered By Docstoc
					Java Concurrency Control
Contents

   Overview of Java synchronisation
   Instance methods              Wait/notify overview
   Class methods                 Wait()
   Synchronized blocks           Notify()
   Additional Notes              General concurrency
   Deadlock                       control
                                  Timed wait




   Book: Wellings 3.1, 1.1 (deadlock);
    Wellings 3.2



                                                          2
Synchronisation Overview

   Every Java object has an
    associated lock
                                      Lock
       Every class is also an
        object and has its own lock
   At most one thread can            Object
    hold a lock at any time
   The lock is manipulated           Method
    implicitly using the
    synchronized
    keyword…




                                               3
Synchronized methods

   If a method is declared                Object
    synchronized                    Lock
     The calling thread
       obtains the lock on entry      Sync.
       and releases the lock on       Method
       exit (return or exception)     Sync.
     => at most one thread           Method
       can be active in a sync.
       method per object
     = “monitor”
   Other methods are always          Unsync.
    open                              Method


                                                    4
Block Synchronization
   A mechanism where a block can be labeled as
    synchronized
   The synchronized keyword takes as a parameter an object
    whose lock the system needs to obtain before it can
    continue
   Synchronized methods are effectively implementable as

    public int read() {
       synchronized(this) {
         return theData;
       }
    }
   this is the Java mechanism for obtaining the current
    object
Example 1a: instance method
   public class MethodNoSyncTest {
        // account balance
        int balance;
        // method
        public void   deposit()
        {
            balance   = balance + 100;
        }
        // method
        public void   withdraw()
        {
            balance   = balance - 100;
        }
        …
    }                   Critical sections because:
                        Modify shared state (shared memory)


                                                              6
                                                            Watch for this
Example 1a (cont.)
     class UpdateTask implements Runnable {
         public void run() {
                 for (long i = 0; i < 1000000; i++) {
                        deposit();
                        withdraw();
                 }
         }
     }
     …
     balance = 100;
     Thread t1 = new Thread(new UpdateTask());
     t1.start();
     Thread t2 = new Thread(new UpdateTask());
     t2.start();
     t1.join();
     t2.join();

     final balance not 100: Interleaving of shared state reads/write 
     RW/WW conflicts  error



                                                                             7
Example 1b
    public class MethodSyncTest {
         // account balance
         int balance;
         // method
         public synchronized void deposit()
         {
             balance = balance + 100;
         }
         // method
         public synchronized void withdraw()
         {
             balance = balance - 100;
         }
         …
     }
     Final balance 100 – each method obtains instance lock and so
     runs to completion without interleaving



                                                                      8
Example 1b
      Provided balance is
       only manipulated from                Object
       synchronized methods          - balance
       all updates will be
       serialised                    Lock
         i.e. “mutual exclusion”,
          “critical sections”
                                         withdraw
      N.B. each instance is
       independent
         own balance, own lock          deposit
      What effect does
       locking have on speed
       of execution?                     Unsync.
         Considerably slower            Method
          (time to acquire and
          release lock)
                                                     9
Example 2a: class method
   public class ClassMethodNoSyncTest {
        // account balance
        static int balance;
        // method
        public static   void deposit()
        {
            balance =   balance + 100;
        }
        // method
        public static   void withdraw()
        {
            balance =   balance - 100;
        }
        …
    }




                                           10
Example 2a (cont.)
     static class UpdateTask implements Runnable {
         public void run() {
                for (long i = 0; i < 1000000; i++) {
                      deposit();
                      withdraw();
                }
         }
     }
     …
     balance = 100;
     Thread t1 = new Thread(new UpdateTask());
     t1.start();
     Thread t2 = new Thread(new UpdateTask());
     t2.start();
     t1.join();
     t2.join();

     same as in case of shared instance variable (still shared state)


                                                                          11
Static Data
     Static data is shared between all objects created
      from the class
     In Java, classes themselves are also objects and
      there is a lock associated with the class
     This lock may be accessed by either labeling a
      static method with the synchronized modifier or by
      identifying the class's object in a synchronized
      block statement
     The latter can be obtained from the Object class
      associated with the object
     Note that this class-wide lock is not obtained when
      synchronizing on the object
Example 2b
    public class ClassMethodSyncTest {
         // account balance
         static int balance;
         // method
         public static      synchronized void deposit()
         {
             balance =      balance + 100;
         }
         // method
         public static      synchronized void withdraw()
         {
             balance =      balance - 100;
         }
         …
     }

     Correct execution – methods obtain class lock


                                                           13
Example 2b

                                       Class object
   Class has its own lock
       N.B. independent of all   - balance (static)
        instance locks
                                   Class lock
       => class synchronized
        methods do NOT block           static
        instance synchronized          withdraw
        methods or vice versa
                                       Static
                                       deposit
                                       Unsync.
                                       Method


                                                       14
Example 3a: synchronized block
      public class BlockSyncTest { // like NoSyncTest
           // account balance
           int balance;
           // method
           public void   deposit()
           {
               balance   = balance + 100;
           }
           // method
           public void   withdraw()
           {
               balance   = balance - 100;
           }
           …
       }




                                                         15
Example 3a (cont.)
    class UpdateTask implements Runnable {
         UpdateTask(BlockSyncTest instance) {
               this.instance = instance;
         }
         BlockSyncTest instance;
         public void run() {
               for (long i = 0; i < 1000000; i++) {
                        synchronized(instance) {
                             instance.deposit();
                             instance.withdraw();
                      }
               }
         }
     }




                                                      16
Example 3a (cont.)
      BlockSyncTest instance = new BlockSyncTest();
       instance.balance = 100
       Thread t1 = new Thread
         (new UpdateTask(instance));           instance
       t1.start();                      - balance
       Thread t2 = new Thread
         (new UpdateTask(instance));        Lock
       t2.start();
       t1.join();
       t2.join();
                                            withdraw

                                             deposit
       critical sections
       execute with lock on shared instance

                                                          17
Additional notes

   Object locks are re-entrant
     i.e.a sychronized method or block can call other
      synchronized methods on the same object (lock)
      without blocking/deadlock
   Locks are implicitly released when block or
    method is left
         By return, end of method, thrown exception or stop()
     Avoids problems with explicit lock/unlock of
      missing an unlock  deadlock

                                                                 18
Additional notes: deadlock

   A synchronized method can call both
    synchronized and unsynchronized methods
    in other classes
     The   lock is still held
   This can result in deadlock…




                                              19
Example of deadlock
     thread A has lock on       O1
      O1 and calls sync A
                                 Lock
      method on O2 while
      thread B has lock on            m1
      O2 and calls sync
      method on O1

                                           O2
                                   Lock
                             x
                                        m2
                         B
                                                20
Requirements for deadlock

   Mutual exclusion
       Only one thread can use each resource (lock)
   Hold and wait
       Blocked threads hold onto locks
   No pre-emption
       The system will not take away a lock from a blocked thread
   Circular wait
       A cycle of threads requiring resources held by the next




                                                                     21
Summary 1

   Mutual exclusion is supported on Java by per-object
    locks
       A class is also an object (MyClass.class)
   Locks are re-entrant
   Locks are implicitly manipulated by the JVM
   Acquired by synchronized methods
       Instance method  instance lock;
        class method  class lock
   Or synchronized(…) {…} blocks
   Released automatically on leaving method/block


                                                          22
Wait/notify Overview
                                   Object
   Every Java object has a wait
    queue as well as a lock
                                    Lock
   Only a thread holding the
    lock can manipulate the wait     Wait queue
    queue
   The queue is manipulated
    using the                       wait
    java.lang.Object
    methods wait(…) and             notify
    notify()/ notifyAll()…
       All classes extend
        java.lang.Object            Method…


                                                  23
wait()

   A thread calling wait is added to the wait
    queue
     (not   necessarily the end)
 It releases the object lock while waiting
 It re-obtains the object lock before returning

 Why use wait?
              task cooperation (avoids polling and
     Efficient
     avoids race conditions or lock-out with sleep)


                                                      24
Wait detail
                                                  Thread
   …
    synchronized (this) {           Gains lock on ‘this’    has
      try {                                                 lock
                                Releases lock on ‘this’
          this.wait();          Added to wait queue
                                 (time passes)
                                Woken from wait queue
        }                        (time passes)
        catch (InterruptedException ie) lock on ‘this’
                                Re-gains {
        }                                                   has
    }                                                       lock
                                  Releases lock on ‘this’


                                                              25
notify()
      A thread calling notify() wakes
       one thread(s) from the wait queue
      A thread calling notifyAll() wakes all
       thread(s) from the wait queue
      If there are no threads waiting then the calls
       have no effect
          Notifies are not “queued” or “persistent”
      Waiting threads are not subdivided or classified
          Notify cannot wake a certain kind of thread or method
          => less efficient than some alternative


                                                                   26
Infinite buffer
  Class Buffer<T> {           …
   Vector<T> data =            public synchronized
       new Vector<T>();          T get()
   synchronized void           {
      put(T item) {     has     while (data.size()==0) {
    data.add(item);    lock      try {
    notify(); wakes               wait();
   }                             } catch(InterruptedException ie) {}
   …                            }
                        has     T item = data.get(0);
                       lock     data.remove(0);
                                return item;
                               }
                              }

                                                                 27
General concurrency control

   Thread 1                        Thread 2
       …                               …
       Entry protocol                  Entry protocol
                                        Critical section
       Critical section
                                        Exit protocol
       Exit protocol
                                        …
       …

                                    Exit:
   Entry:
                                        (update state) Wake any
       Block until safe to              blocked threads now able
        proceed (update state)           to proceed


                                                                    28
Infinite buffer revisited
  Class Buffer<T> {             …
   Vector<T> data =              public synchronized
       new Vector<T>();            T get()
   synchronized void    entry    {
      put(T item) {               while (data.size==0) {
    data.add(item);                try {
    notify();        Critical       wait();
   }                  section      } catch(InterruptedException ie) {}
   …                              }
                                  T item = data.get(0);
                                  data.remove(0);
                                  return item;
                                 }
                         exit   }

                                                                         29
Infinite buffer notes

   Object lock is held during critical section
     So   at most one thread can be in critical section
   If more than one thread should be in critical
    section then lock must be released and
    regained
     E.g.   separate into two synchronized blocks




                                                           30
Synchronized method implementation

This:                        Equals:
…                            …
synchronized void method()   void method()
{                            {
                               synchronized
                                 (this) {
        …                         …
                               }
}                            }
…                            …
static synchronized          static void method() {
  void method() {              synchronized
                                 (ThisClass.class) {
    …                             …
                               }
}                            }




                                                       31
Bounded Buffer
  public class BoundedBuffer {
    private int buffer[];
    private int first;
    private int last;
    private int numberInBuffer = 0;
    private int size;

   public BoundedBuffer(int length) {
     size = length;
     buffer = new int[size];
     last = 0;
     first = 0;
   };
Bounded Buffer
     public synchronized void put(int item)
            throws InterruptedException {
         while (numberInBuffer == size) wait();
         last = (last + 1) % size ; // % is modulus
         numberInBuffer++;
         buffer[last] = item;
         notifyAll();
     };
     public synchronized int get()
            throws InterruptedException {
         while (numberInBuffer == 0) wait();
         first = (first + 1) % size ; // % is modulus
         numberInBuffer--;
         notifyAll();
         return buffer[first];
     };
 }
Timed wait()

   wait() waits indefinitely
     Or   until interrupted
   wait(long millis) waits at most
    millis ms before attempted to regain lock
    & continue
     Butwait(0) waits indefinitely
     Cannot tell if timed out or notified!

   Allows time-out
     E.g.   error or deadlock detection


                                                34
Summary 2

   Each object has a wait queue as well as a
    lock
    =   “monitor”
 wait() blocks a thread and releases the
  lock until notify()/notifyAll()
 Supports general concurrency control
     Can   be used to avoid busy waiting or polling
   Additional variable(s) are required to track
    concurrency requirements

                                                       35

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:4
posted:8/5/2012
language:
pages:35