Java Synchronization with multiple objects/locks

旧时模样 提交于 2019-12-01 08:13:41

Step 1

Provide a natural ordering for your resources. For example, if your resources were letters, A would come before B, B would come before C, and so on.

Step 2

Only allow your threads to grab resources in order.

Now your threads cannot possibly reach deadlock in any situation.

Example

  • Thread 1 needs locks on resources A, B, D, and E
  • Thread 2 needs locks on resources B and E

Our threads must fight for locks on resources B and D. Because we have enforced a natural order, the thread that obtains the lock on B first is guaranteed to get the lock on D and proceed smoothly. The losing thread will be waiting for B to be released.

To avoid deadlock in these scenarios you must need to induce an ordering on the locks and acquire them according to the induced ordering consistently though out your application.

I understand this answer has been mentioned and may be sufficient in particularly your case but natural ordering is possible only when objects are comparable :(

Best way to induce ordering on objects is to use the System.identityHashCode(A/B/C...lock object) which returns value of hashcode. But again don't feel 100% safe as you might be victim of hash collision and even the chance is rare but you might get Deadlock. In those scenarios you need additional safety in your code. Your make your threads to compete for some separate 'tie breaking' lock. Hope this information helps in getting a bit more clear picture on your problem.

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