Is there a way to make an object usable only by th

2019-07-03 23:33发布

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?

1条回答
祖国的老花朵
2楼-- · 2019-07-04 00:09

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 - including use() - 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 to use() to store a new locking thread.

查看更多
登录 后发表回答