2

I know I can create a Java code which is VERY likely to deadlock. There are many ready examples which, when run, will provide a deadlock almost instantly.

However, I'm wondering if it's theoretically possible to write a Java code which absolutely guarantees a deadlock?

That is, by analyzing such code one can prove there will be a deadlock?

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158

1 Answers1

0

Ok, so what leads to a deadlock? Thread 1 locks resource one, Thread 2 locks resource 2, thread 1 tries to lock resource two, Thread 2 tries to lock resource 1. Here is a way to guarantee this situation:

  1. Thread 1 locks resource 1
  2. Thread 1 sets flag FLAG
  3. Thread 1 spawns Thread 2
  4. Thread 1 waits for FLAG to be reset by Thread 2 (in while loop, for example). We can't use a lock here because we can't distinguish between a lock that has not been used already and one that has been used and was released (as far as i know)
  5. Thread 2 locks resource 2
  6. Thread 2 resets FLAG
  7. Thread 2 tries to lock resource 1
  8. Thread 1 resumes, and tries to lock resource 2

=> voila, Deadlock I guess you can turn this into code yourself (FLAG should be volatile imho)

kutschkem
  • 7,826
  • 3
  • 21
  • 56