Docstoc

Java Threads A Quick Introduction to Java Concurrent Programming CS 472

Document Sample
Java Threads A Quick Introduction to Java Concurrent Programming CS 472 Powered By Docstoc
					A Quick Introduction to Java
Concurrent Programming

               CS 472 Operating Systems
    Indiana University – Purdue University Fort Wayne
                        Mark Temte




                                                        1
Java threads
 Java threads have the following states:
   -- new
   -- running
   -- ready
   -- inactive (=blocked)
   -- finished



                                           2
Java threads
A new thread is created by subclassing the
Thread class and overriding the run() method

      public class MyThread extends Thread{
        public MyThread() { }
        public void run() {
          <activity of the thread>
        }
      }



                                               3
Java threads
 A method may start a thread as follows:
    
    MyThread t = new MyThread();
    
    t.start();
    


 Method start() invokes the run() method.



                                            4
Thread methods
 Thread methods:
 -- start()
 -- sleep( milliseconds )
 -- setPriority( n )        n is in the range 1 to 10
 -- interrupt()
 Method interrupt() is applied by one thread to a
 target thread
 It sets a flag in the target thread that “requests” that
 the target thread sleep when appropriate.
 The target thread must check the flag periodically
                                                        5
Thread methods
 Every thread inherits methods …
 -- wait()
 -- notify()
 -- notifyAll()
 When a thread applies wait() to an object, the
 thread becomes inactive until another thread
 applies notify() to that object
 notify() awakens a single thread waiting on the
 object
 notifyAll() awakens all threads waiting on the object
                                                   6
Deprecated methods
 Deprecated methods are inherently unsafe and
 should no longer be used
 For threads, these include
 -- stop()              Use “t = null” instead
 -- suspend()           Prone to deadlock
 -- resume()            Prone to deadlock




                                                 7
Object locks
 Every Java object has a “lock” used in conjunction
 with a “synchronized statement”
    
    synchronized( someObj ){
      <critical section>
    }
    
 someObj represents a critical resource for which
 mutual exclusion is needed
 Critical code associated with someObj should be
 placed in a synchronized statement
                                                 8
Synchronized statement
 A thread executing a synchronized statement
 must acquire someObj’s lock
 If someObj is already locked, the thread blocks
 The object acts like a binary semaphore
 initialized to 1
 However, the thread blocked the longest is not
 guaranteed to acquire the lock next


                                                   9
Synchronized methods
 The synchronized method
     synchronized type method(  ) {
       
     }
 is an abbreviation for
     type method (  ){
        synchronized( this ) {
          
        }
     }
 In other words, the entire body of a synchronized
 method is a synchronized statement on the object
 to which the method is applied.
                                                10
Constructing a Java monitor
 Make use of the synchronized method
 Example

 class MyMonitor{
      <private instance variables>
      public MyMonitor( ){  }
      public synchronized type1 method1(  ){  }
      public synchronized type2 method2(  ){  }
      <etc.>
 }


                                                        11
Java monitor
 Using My Monitor
    
    m = new MyMonitor();
    
    m.method2()
    
 The method blocks if m is locked by another
 thread



                                               12
Implementing a semaphore
 Application: Implement a weak, counting
 semaphore in Java
 The semaphore is weak because the Java
 runtime system does not use a FIFO queue for
 threads waiting on notify()
 Recall that the thread blocked the longest is not
 guaranteed to acquire the lock next
 A Java monitor is surprisingly tricky to implement

                                                  13
Java semaphore implementation
                      First attempt
 class Semaphore{
   //                                          Recall notation:
   private int value = 0;
   //                                             p() = wait
   public Semaphore( int initial ){               v() = signal
     if ( initial > 0 ) value = initial;
   }//end Sempaphore
   //
   public synchronized void p(){
     if ( value == 0 ){   // then no resources left, so wait
       wait();
     value--;
   }//end p
   //
   public synchronized void v(){
     if ( value == 0 ){ // if not true, no need to notify
       notify();
     }
     value++;
   }//end v
   //
 }//end class Semaphore




                                                                  14
Java semaphore implementation
 This first attempt is flawed
 “Barging” is possible
 A thread calling p() might get in the monitor
 before the thread notified with v() can get back in
 from the ready state
 Both calls will succeed when only one should
 This is a “safety” violation: the number of
 successful waits exceed the number allowed

                                                   15
Java semaphore implementation
        Second attempt – solves the “barging” problem

                 Change “if” to “while” in p( )
class Semaphore{
  //
  private int value = 0;
  //
  public Semaphore( int initial ){
    if ( initial > 0 ) value = initial;
  }//end Sempaphore
  //
  public synchronized void p(){
    while( value == 0 ){   // then no resources left, so wait
       wait();
    value--;
  }//end p
  //
  public synchronized void v(){
    if( value == 0 ){ // if not true, no need to notify
      notify();
    }
    value++;
  }//end v
  //
}//end class Semaphore



                                                                16
Java semaphore implementation
 The second attempt replaces “if” by “while” in p()
 This forces p() to check the condition again after
 being scheduled
 This second attempt is also flawed due to
 another “barging” problem




                                                  17
Java semaphore implementation
 This time, assume several threads are waiting
 One thread is released by the next notify()
 Before it can act, several threads call v()
 “notify()”s are lost since value>0
 Other threads wait unnecessarily
 This is a “liveness” violation: the number of
 successful waits is fewer than allowed
 We need to keep track of the total number of
 waits and notifies
                                                 18
 Java semaphore implementation
                      Final successful attempt

// DESCRIPTION: This Java class implements a weak counting semaphore
// as described by Stephen Hartley, SIGCSE Bulletin, Vol. 31, Num. 1,
// March 1999, pp. 58 – 62. Note: A mandatory try-catch-finally block
// associated with the possibility of interruption has been omitted to
// simplify the presentation.
class Semaphore{
  //
  private int value       = 0;
  private int waitCount   = 0;   // tabulates the number of waits
  private int notifyCount = 0;   // tabulates the number of notifys
  //
  public Semaphore( int initial ){
    if ( initial > 0 ) value = initial;
  }//end Sempaphore
  //
  public synchronized void p(){
     < next page >
  }//end p
  //
  public synchronized void v(){
     < next page >
  }
  }//end v
  //
}//end class Semaphore


                                                                         19
Java semaphore implementation
                  Final successful attempt

 public synchronized void p(){
     if ( value <= waitCount ){   // then no resources left, so wait
       waitCount++;
       do{
         wait();
       }while ( notifyCount == 0 );
       waitCount--;
       notifyCount--;
     }else{
       if ( notifyCount > waitCount )   // then use up one notify
         notifyCount--;
     }
     value--;
   }//end p
   //
   public synchronized void v(){
     value++;
     if ( waitCount > notifyCount ){ // if not true, no need to notify
       notifyCount++;
       notify();
     }
   }//end v
   //




                                                                  20

				
DOCUMENT INFO
Description: java and its various features
About if any file u wil find copyright contact me it will be remove in 3 to 4 buisnees days. add me on sanjaydudeja007@gmail.com or visit http://www.ohotech.com/