Why do we need to lock (this) as well? I see it that way:
The thread goes into the first method -> locks the 'lock' mutex -> then goes to the second method and tries to go into the synchronize (lock) {} block but it can't because the 'lock' mutex was already acquired in the first method -> waits until it is released (which never happens) -> deadlock
Woudn't just synchronized (lock) {} be enough?
Resolved
Comments (5)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
29 April 2021, 15:34solution
Threads can't lock themselves out. They can enter any lock that they hold the lock for (object or class). It is other threads that can not. The task is asking that you create a deadlock, but that would never occur in this scenario. The deadlock occurs when one thread holds one lock while another thread holds another lock. Then both threads need to access to an area of code already locked by the other thread before they themselves can release their lock.
So:
Thread1 -> hold an object lock
Thread2 -> holds a class lock
Thread1 -> to release the hold on the object lock it needs access to code that is locked by the class lock
Thread2 -> to release the hold on the class lock it needs access to code that is locked by the object lock
In this scenario deadlock occurs.
+3
Szymon
29 April 2021, 19:40
Thanks, everything makes sense now. I did some more research and testing on my own and all the pieces start to come together.
+1
Guadalupe Gagnon
29 April 2021, 19:49
"I did some more research and testing on my own and all the pieces start to come together."
You sound like a professional programmer already
+2
Szymon
29 April 2021, 20:34
Completed 3/4 of the course and I feel so geeky now.
+2
Szymon
29 April 2021, 20:36
But I tell you - these multithreading stuff makes me actually so so excited.
+1