background image
<< Synchronization Errors | Inconsistent synchronization >>

Race Condition

<< Synchronization Errors | Inconsistent synchronization >>
2.3.1
Deadlock
(rare, catastrophic)
It is a situation in which one or more threads mutually lock each other. The most frequent
reason for the cause of deadlocks is inconsistent locking sequence. The threads in deadlock wait for
resources which are in turn locked by some other thread. The general way to detect deadlocks is to
construct a lock graph and analyze if it has a loop. Loop in the lock graph represents the presence
of a deadlock. Deadlock detection and avoidance are other possible strategies followed in general by
operating systems [14].
The following is a small JAVA code fragment which can give rise to a deadlock.
T h r e a d 1:
s y n c h r o n i z e d ( A ){
s y n c h r o n i z e d ( B ){
}
}
T h r e a d 2:
s y n c h r o n i z e d ( B ){
s y n c h r o n i z e d ( C ){
}
}
T h r e a d 3:
s y n c h r o n i z e d ( C ){
s y n c h r o n i z e d ( A ){
}
}
2.3.2
Race Condition
(frequent, major)
This is an error which results when two threads try to access the same resource and the result
depends on the order of the execution of the threads. Consider the following example which illustrates
this error.
c l a s s r e s e r v a t i o n
{
int s e a t s _ r e m a i n i n g ;
p u b l i c int r e s e r v e ( int x )
{
if ( x <= s e a t s _ r e m a i n i n g ) {
s e a t s _ r e m a i n i n g -= x ;
r e t u r n 1;
}
r e t u r n 0;
}
}
If two threads simultaneously invoke reserve(x), then even though numbers of seats remaining
are not enough for both of them , they may both be returned `1'. Here, the function reserve should
be executed by one thread at a time and forms a critical section where the object of reservation is
shared resource.
Whenever some shared data has to be accessed by threads, the conditions of critical section
have to be satisfied (mutual exclusion, bounded waiting, progress)[25]. To ensure this, use the
synchronization constructs like monitor, semaphores etc.
5