Java Keyword Synchronized

The reserved keyword synchronized is used in the declaration of a method or code block to acquire the mutex (mutual exclusion) lock for an object while the current thread executes the code. The mutex lock is automatically released when program execution exits the synchronized code block. The synchronized method or synchronized code block only allows one thread to execute it at a time.

Keep in mind that the synchronized keyword can’t be applied to variables, classes, or interfaces in Java.

Let’s take a look at what a synchronized instance method looks like.

//JavaCodeDepot Sample 

public synchronized void addCounter(int ctr){
      
     this.counter += ctr;
}


You can synchronize a block of code within a method without having to synchronize the entire method.

//JavaCodeDepot Sample 

public void addCounter(int ctr){

    synchronized(this) {

       this.counter += ctr;   
    }
}


While a thread has the lock on either a method or code block, no other threads can acquire that lock, kind of the whole premise of thread safe. As soon as the current thread that has the synchronized code block completes, that thread will release the lock for another thread.

The complete list of Java reserved keywords contains a total of 50 keywords and 3 literal words that are unable to be used as variable names.

Add a Comment

Your email address will not be published. Required fields are marked *