Consider following class that I have wrote for testing the locking of non-primitive variable (myObject). My question is:
(Consider all threads are working on same object instance of SynchronizationTest)
I understand that if thread1 is executing set(...) method then any other thread (lets say thread2) is okay to execute either of the anotherSetWithSynchronized(...) or anotherSetWithoutSynchronized(...).
Question a : If thread1 has locked the object of SynchronizationTest while executing set(...), does it mean it has acquired lock on all member object variable ? like in this case myObject. If not then,
Question b: If thread1 is executing set(...) can thread2 execute anotherSetWithSynchronized(...) concurrently ?
Ouestion C: None of the two methods can execute simultaneously by thread?
Ouestion D: Design is wrong, I need to explicitly lock myObject in synchronized set(...) method. Like this:
public synchronized void set(MyValue myValue)
{
synchronized (myObject)
{
myObject.put(myValue);
}
}
======================SynchronizationTest class======================
public class SynchronizationTest
{
private MyObject myObject = new MyObject();
public synchronized void set(MyValue myValue)
{
myObject.put(myValue);
}
public void anotherSetWithSynchronized(MyValue myValue)
{
synchronized (myObject)
{
myObject.put(myValue);
}
}
public void anotherSetWithoutSynchronized(MyValue myValue)
{
myObject.put(myValue);
}
}
No comments:
Post a Comment