Code snippet - 1
class RequestObject implements Runnable
{
private static Integer nRequests = 0;
@Override
public void run()
{
synchronized (nRequests)
{
nRequests++;
}
}
}
Code snippet - 2
public class Racer implements Runnable
{
public static Boolean won = false;
@Override
public void run()
{
synchronized (won)
{
if (!won)
won = true;
}
}
}
I was having a race condition with the first code snippet. I understood that this was because I was obtaining a lock on an immutable object(of type Integer).
I have written a second code snippet which is again impervious to 'Boolean' being immutable. But this works(no race condition is displayed in an output run). If I have understood the solution to my previous question properly the below is is one possible way in which things can go wrong
- Thread 1 gets a lock on an object(say A) pointed by
won
- Thread 2 tries to now get a lock on the object pointed to by
won
and gets in the wait queue for A
- Thread 1 goes into the synchronized block, verifies that A is false and creates a new object(say B) by saying
won = true
(A thinks it won the race).
- 'won' now points to B. Thread 1 releases the lock on object A(no longer pointed to by
won
)
- Now, thread-2 which was in the wait queue of object A gets woken up and gets a lock on object A which is still
false
(immutably so). It now goes into the synchronized block and assumes that it has also won, which is not correct.
Why is the second code snippet working fine all the time??
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…