简体   繁体   English

同步方法是否对此锁定

[英]Does a synchronized method hold a lock on this

I am working through a Java book and found the following question. 我正在阅读一本Java书,发现了以下问题。

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. 但是,官方的回答是“否”,并且解释是变量int x是公共的,可以由一个线程修改,而另一个线程在其中一个同步方法中。 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. synchronized关键字所做的全部工作就是自动阻止在单个对象实例上多次调用synchronized方法。 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. 但是,直接字段访问永远不会受到Java中任何形式的锁定的影响,因此公共字段使此类非常不安全。

You are right lock is kept on object , however it means that only one thread can be inside any of syncronised method. 您是正确地将锁锁定在object上,但这意味着任何同步方法中都只能有一个线程。 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); 假设在时间T1,通过调用queenInstance.setX(10);进入setX()内部的一个线程;

Howwver, at same instance other thread is trying to set value for this variable :- queenInstance.x = 12; 但是,在同一实例中,其他线程正在尝试为此变量设置值:-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. 使setter和getter同步的唯一目的是防止访问时出现竞争状况。 But since x is public any code can directly access it without using setter OR access it without using getter. 但是由于x是公共的,所以任何代码都可以不使用setter来直接访问它,也可以不使用getter来访问它。 Making x public will negate all the security provided by Synchronized methods. 将x设为公开将取消同步方法提供的所有安全性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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