Preventing race and deadlock conditions in threads
There are two common problems that can cause problems with threaded code. The first is the race condition. This is what can happen when two or more threads work with a block of code that changes a variable shared by all the threads.
The second is the deadlock condition. To resolve race conditions, you lock a block of code. If multiple threads use the same lock object, then you could have a situation where these threads are waiting for each other to finish with the lock but none finish. Let us look more closely at these two conditions.
Race condition
Imagine a scenario where you share a reference to an object among multiple threads. Calling upon methods in this shared class that only use local variables is thread-safe. Thread-safe, in this case, occurs because each thread maintains its own private stack for local variables. There can be no conflict between threads.
It is a different story if the shared object’s methods...