简体   繁体   中英

Does a synchronized method hold a lock on this

I am working through a Java book and found the following question.

In the code below, is the class threadsafe?

public class Queen   
{
    public int x;
    public synchronized int getX()
    {
        return x;
    }
    public synchronized void setX(int x)
    {
        this.x = x;
    }
    public static void main(String args[]) 
    {
    }
}

My answer would be yes, since there are only two methods, both synchronized, so while one of them is running, it holds the lock on the object, and the other cannot run.

However, the official answer is NO, and the explanation is that the variable int x is public and can be modified by a thread while the other thread is inside one of the synchronized methods. Is that possible?? Doesn't the synchronized method hold the thread on this, meaning everything in that object including public variables?

All that the synchronized keyword does is automatically prevent multiple calls to synchronized methods on a single instance of an object. That means that whenever a synchronized method is called, it must be exited before any other synchronized methods can execute on the same instance.

However, direct field access is never affected by any form of locking in Java, so the public field makes this class quite unsafe.

You are right lock is kept on object , however it means that only one thread can be inside any of syncronised method. But the field is public so other threads need not to inside sycronized block.

Let say at time T1 , one thread in inside the setX() by calling queenInstance.setX(10);

Howwver, at same instance other thread is trying to set value for this variable :- queenInstance.x = 12;

It is unpredicatable what will be output.

The sole purpose of making the setter and getter synchronized is to prevent a race condition while accessing it. But since x is public any code can directly access it without using setter OR access it without using getter. Making x public will negate all the security provided by Synchronized methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM