简体   繁体   English

Java同步调查

[英]Java synchronisation poll

Here's some code I saw once. 这是我曾经看到的一些代码。 Can you see what's wrong with it? 您能看到问题在哪里吗?

[updated] [更新]

public class ResourceManager1
{
    private final String mutex = "";
    Object resource = null;

    public Object getResource()
    {
        synchronized (mutex)
        {
            if (resource == null)
            {
                resource = new Object();
            }
        }

        return resource;
    }
}

public class ResourceManager2
{
    private final String mutex = "";
    Object resource = null;

    public Object getResource()
    {
        synchronized (mutex)
        {
            if (resource == null)
            {
                resource = new Object();
            }
        }

        return resource;
    }
}

Never synchronize on strings, particularly string literals which are interned. 切勿在字符串上进行同步,尤其是在被内联的字符串文字上。 You've basically just got a single lock. 您基本上只有一个锁。

In general, never synchronize on any reference that might be visible outside your class (including "this") unless the purpose of the external visibility is precisely for locking purposes. 通常, 除非外部可见性的目的完全是出于锁定目的, 否则切勿在类外部(包括“ this”)上可见的任何引用上进行同步。 I usually use a private final variable created solely for the purpose of locking. 我通常使用仅为锁定目的而创建的private final变量。

对于两个类,您都使用相同的String作为互斥体,因此一次只能使用一个同步块,这似乎并不是代码的目的。

mutex is not final and resource is not private. 互斥锁不是最终的,资源也不是私有的。

Besides, you need a getResource method that returns resource, but I suppose this is just a typo. 此外,您需要一个getResource方法来返回资源,但是我想这只是一个错字。

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

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