+ 1

Any program example to create a deadlock situation in Java? Solving ideas?

Can anyone give an example of a deadlock situation in java. Write a small java program as an example. Thank You!

3rd Apr 2018, 6:13 AM
SatyaJit Pradhan
SatyaJit Pradhan - avatar
10 Answers
+ 14
If you need to use multiple locks, do it in a well defined order. Simple as that to be said, often very hard to do/find the mistake/test. Generally spoken: be careful, be sure you know what you're doing if you need multi threading. The snychonized keyword should only be used after you double-checked that you need it and you are sure it works as expected.
3rd Apr 2018, 6:48 AM
Tashi N
Tashi N - avatar
+ 13
You can really simply create a deadlock if you use the synchronized keyword carelessly. Example and more on concurrency can be found in the Oracle tutorials: https://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html
3rd Apr 2018, 6:25 AM
Tashi N
Tashi N - avatar
3rd Apr 2018, 6:23 AM
***
*** - avatar
+ 2
So in https://www.javatpoint.com/deadlock-in-java to prevent the deadlock we should alter the resources in thread 2.....So, if thread 1 acquires lock on resource 1 , thread 2 will not proceed until thread 1 releases resource 1 lock, same way thread 1 will not be blocked even if thread 2 holds resource 2 lock because now thread 2 will not expect thread 1 to release resource 1 lock to proceed further. Am i right? Thank You all. 🙂
3rd Apr 2018, 6:51 AM
SatyaJit Pradhan
SatyaJit Pradhan - avatar
+ 1
@Tashi N How to fix such situations?
3rd Apr 2018, 6:36 AM
SatyaJit Pradhan
SatyaJit Pradhan - avatar
+ 1
And the best way to solve it is just by preventing a deadlock to occur..
3rd Apr 2018, 6:42 AM
***
*** - avatar
+ 1
@Tashi N Thank You â˜ș
3rd Apr 2018, 6:56 AM
SatyaJit Pradhan
SatyaJit Pradhan - avatar
+ 1
@Jan sorry , am little weak in English.
3rd Apr 2018, 3:18 PM
SatyaJit Pradhan
SatyaJit Pradhan - avatar
0
@Boem how can you fix that? Changing sleep? Or by changing the order of resource?
3rd Apr 2018, 6:32 AM
SatyaJit Pradhan
SatyaJit Pradhan - avatar
3rd Apr 2018, 6:41 AM
***
*** - avatar