Skip to main content

Posts

Showing posts with the label concurrency

synchronized, wait() and notify() in java

synchronized keyword in java used to make sure that the code block would be executed by one and only one thread at a time. Using the keyword one can write a code block which would be side effects free from other concurrently running thread. There are two way we can use the keyword: 1) synchronized block and 2) synchronized method. synchronized (lockingObject) {     // code which must be executed by single thread at a time. } public synchronized void doWork () {     // code which must be executed by single thread at a time. } The synchronized block locks on lockingObject whereas synchronized method locks on object of that method ( this ). Good example of this is to achieve singleton pattern. public class Singleton {     private static Singleton s;     public static Singleton getInstance () {         if ( s == null ) {             synchronized (Singleton.class) {    ...