Skip to main content

Posts

Showing posts with the label Thread Synchronization

Wait/Notify Idiom

Some times threads need some condition to be realized by other threads to continue execution. Until this condition is realized a thread should make continues wait and check. But this means waste of resources and since thread probably owns lock that is needed by other threads to realize this condition, may lead to deadlocks. Java has a better alternative.  Java Object class has wait/notify/notifyAll methods to deal with such situations.  A complete example of wait/notify idiom is given below. class ProducerConsumer {     List dataList = new ArrayList ();     boolean empty = true ;     synchronized void produce () {         dataList . add ( new Object ());         empty = false ;         notifyAll ();// notify waiting threads     }     synchronized void consume ...

Thread Synchronization

    In Java, thread synchronization is achieved through two constructs: synhcronized methods and synhcronized statements. int a = 7 ; void synchronized commonMethod (){     a += 5 ; // additional processing of data not shared among threads       // but unnecessarilly synchronized } An example of synchronized methods can be seen above. int a = 7 ; void commonMethod (){     synchronized ( this ){         a += 5 ;     }         // additional processing of data not shared among threads.         // Unnecessary synchronization is avoided. } Code fragment above is an example of synchronized statements. Note that synchronized methods may lead to unnecessary synchronization of code segments, while synchronized statements has the flexibility to avoid those situat...