educative.io

Synchronization keyword in method definition

Hi. I don’t get why getName method is equivalent to a method with synchronized keyword. If it locked on “this”, it would be the same but this one has monitor lock on “lock” field.

class Employee {

    // shared variable
    private String name;
    private Object lock = new Object();

    // method is synchronize on 'this' object
    public synchronized void setName(String name) {
        this.name = name;
    }

    // also synchronized on the same object
    public synchronized void resetName() {

        this.name = "";
    }

    // equivalent of adding synchronized in method
    // definition
    public String getName() {
        // Using a different object to synchronize on
        synchronized (lock) {
            return this.name;
        }
    }
}

Hi @SUEWOON_RYU, Thanks for reaching out to us.
Java synchronized keyword marks a block or method in a critical section. A critical section is where one and only one thread is executing at a time, and the thread holds the lock for the synchronized section.Synchronized keyword helps in writing concurrent parts of the applications, to protect shared resources within this block. The synchronized keyword is all about different threads reading and writing to the same variables, objects, and resources.
The getName() method is synchronized on the “this” object. getName would be synchronized independently of the other two methods and can be executed alongside one of them.

Hope you will understand :slight_smile:

1 Like