Java sync polling

Here is the code I saw once. Can you see what's wrong with him?

[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;
    }
}

      

0


source to share


3 answers


Never sync strings, in particular string literals that are interned. You basically only have one lock.



In general, never sync on any reference that might be visible outside of your class (including "this"), unless the target of external visibility is for blocking purposes. I usually use a variable private final

created exclusively for blocking.

+12


source


You are using the same string as the mutex for both classes, and therefore only one of the synchronized blocks can be used at the same time, which does not seem to be the intent of the code.



+1


source


The mutex is not final and the resource is not private.

Also, you need a getResource method that returns a resource, but I suppose this is just a typo.

0


source







All Articles