In Java Concurrency in practice book ,I came across a code in chapter 4
public Class PrivateLock{private final Object myLock=new Object();Widget widget;void someMethod(){ synchronized(myLock){// Access or modify the state of widget}}}
The book says there are advantages to using a private lock object. Making the lock object private encapsulates the lock so that client code cannot acquire it, whereas a publicly accessible lock allows client code to participate in its synchronisation policy-correctly or incorrectly.
My doubt is
If I have my own Runnable method and I call instantiate this class and call
someMethod()
, will it fail to acquire the lock?If so, how can the owner of the code make use of this lock and call
someMethod()
? Because he also have to instantiate an object of this class and callsomeMethod()
, the same I, the client is doing.
I suspect this is a duplicate, but I have not found my answers in those threads.
Best Answer
1)If I have my own Runnable method and I call instantiate this class and call someMethod() , Will it fail to acquire the lock?
No, unless the lock is already acquired elsewhere by another thread, like if there was another thread with your PrivateLock object reference which called someMethod before you, and is still executing that portion of the method that uses the lock.
When the book says clients cannot acquire it, it probably means the clients cannot obtain a reference to the lock to lock things in their own client code, it doesn't mean that client callees are not able to execute the synchronized block.
Having the lock private prevents this:
PrivateLock myPrivateLock = new PrivateLock();// MyPrivateLockThread is a custom Thread class that calls myMethodThread thread = new MyPrivateLockThread(myPrivateLock);thread.start();// Now the following would be possible if the lock wasn't privatesynchronized(myPrivateLock.myLock) { while (true) { } }
You want to prevent this so you don't need to worry about client code that you don't own causing threading issues for the code you do own.
I believe I can see where your confusion comes from: the idea is to have an instance of PrivateLock
and a few different threads working with that instance, invoking instance.someMethod()
simultaneously.
1)If I have my own Runnable method and I call instantiate this classand call someMethod() , Will it fail to acquire the lock?
Answer: if there's only one thread calling this method on an instance it shouldn't fail
2) If so , How can the owner of the code make use of this lock andcall someMethod()? Because he also have to instantiate an object ofthis class and call someMethod(), the same I ,the client is doing.
Answer: I believe that now you can answer it by yourself :)