Is there a way to make an object usable only by the first thread that accesses a specific method?

随声附和 提交于 2019-12-10 19:53:41

问题


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:


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.



来源:https://stackoverflow.com/questions/37040380/is-there-a-way-to-make-an-object-usable-only-by-the-first-thread-that-accesses-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!