Unlocking lock owned by another thread java

前端 未结 5 926
借酒劲吻你
借酒劲吻你 2020-12-30 01:40

I have a LockManager that manages the locks of several threads. Sometimes the threads are bad boys, and I have to kill them and ask the LockManager to release all their lock

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-30 02:08

    You've discovered a major reason why common wisdom says: Don't kill threads!

    Locks are only one of the potential resource leaks that can happen if you forcibly kill a thread. Consider open files and sockets, etc.

    Also consider that if you did manage to unlock the lock, there was a reason the lock was locked in the first place. For example, the thread may have partially updated a data structure, and allowing access to that structure from another thread is likely to cause strange and wondrous program failures that are difficult if not impossible to debug.

    The best way to handle this situation is to ask the thread to go away. Add a "stop()" method to the object associated with the thread (you do have an object for each thread, don't you?) that sets a flag, and have the thread check this flag regularly and exit if it is set.

    If your threads are misbehaving in a way that prevents them from checking the stop flag, then the correct approach is to fix the code so that it does not misbehave.

提交回复
热议问题