Java synchronization with multiple objects / locks

I am wondering if there is a package or model that will help me solve this scenario.

Say I have 3 threads and a bunch of objects A, B, C, D, E, F

  • T1 requires locks A, B
  • T2 requires locks B, C, D
  • T3 requires locks E, F

In this case, it would be good if T1 and T3 were executed simultaneously. In addition, T2 and T3 can work simultaneously. But T1 and T2 should never start at the same time.

Also note that

  • Threads can get an arbitrary number of locks, not just 2. (I saw an elegant solution to this problem with a fixed number of locks, but I'm not sure I can apply it here.)
  • Obviously, I would like each thread to get all the necessary locks at the same time to prevent a deadlock.

If someone can point me to a package that supports this use case, or some piece of code that allows this, let me know.

Many thanks.

+3
source share
2 answers

Step 1

Ensure the natural order of your resources. For example, if your resources were letters, it Awill be earlier B, it Bwill be earlier C, etc.

Step 2

Only your threads allow you to grab resources in order.

Now your threads cannot get stuck in any situation.

Example

  • In the stream of 1 resource block need A, B, DandE
  • Thread 2 needs resource locks BandE

B D. , , B, D . B.

+4

, , .

, , , , :(

- System.identityHashCode( A/B/C...), hashcode. 100% , -, , Deadlock. . , - . , .

+2

All Articles