Java synchronized references

主宰稳场 提交于 2019-12-19 04:58:28

问题


I have a class A and B.

public class A() { 
    private static List<int> list = new ArrayList<int>(); 
    public static List<int> getList() {
        return list;
    }
}

public class B() { 
    public void foo() {
        synchronized(A.getList()) {
            // DO Stuff
        }
    }
}

In class B where I synchronize. Does this synchronize on A's list, or on B's reference to A's list. I think it is the latter but could use some help.

If so then how do I accomplish a similar thing to this that will actually work?

Thanks!


回答1:


The OP followed up with this comment:

What's weird is the behavior that I am seeing is that if I lock from within A I can actually lock it at the same time in B. Which pretty much means the synchronized has no effect. Which is why I surmised that maybe locking a reference won't work.

That can't happen with the code in the question.

But it could happen if there was a setList method in A that updated the list variable. You could then end up in a situation where the two threads were locking on different objects.

Another possibility is that you actually only have one thread that is taking a lock on the same object twice. That's normal behavior. Java primitive mutexes are reentrant; i.e. they only prevent two different threads from holding the same mutex at the same time.




回答2:


It synchronizes on A's list. What do you mean by B's reference to A's list? It doesn't matter if you're in A using list or B using A.getList(), they both reference the same object. When you synchronize on it you'll block other threads from synchronizing on that same object, regardless of where it's referenced from.



来源:https://stackoverflow.com/questions/5827679/java-synchronized-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!