I want an object that can be created by any thread, but the moment a thread calls myObject.use()
it can only be used by that thread until myObject.release()
is called.
I don't want to force the developers to have to wrap all method calls for this object/class in synchronized blocks (which I know could be used to approximate this functionality) as that's likely to lead to misuse of the object if they forget to wrap all calls from myObject.use()
to myObject.release()
in the same synchronized block.
Is this possible?
Could it be done with a ReentrantLock
?
Sure it can be done. The
use()
method should be synchronized, so it can be called by only one thread at a time, and store the calling thread as the locking thread in a private volatile variable. All calls - includinguse()
- should first check if there is a stored locking thread and immediately return - or throw an exception if you prefer - if there is such a thread and it doesn't match the calling thread.release()
should also be synchronized and can remove the stored locking thread, allowing the next call touse()
to store a new locking thread.