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 r开发者_JAVA百科eference 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!
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.
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.
精彩评论