M
Mike Smith
How do you handle this paradox?
1. Object myObject = new Object();
2.
3. // Threads started here which
4. // may set myObject to null
5.
6. if (myObject != null) {
7. synchronized (myObject) {
8. // Ref to myObject here
9. }
10. }
How can you be sure another thread will not swoop in and set myObject
to null in between lines 6 and 7 before you have a chance to get a
lock on it? You cannot synchronize on myObject if it is set to null
without throwing an exception. Do you just move the synchronized
block to before the IF statement and catch the exception if myObject
is null or is there a more elegant approach?
Mike
1. Object myObject = new Object();
2.
3. // Threads started here which
4. // may set myObject to null
5.
6. if (myObject != null) {
7. synchronized (myObject) {
8. // Ref to myObject here
9. }
10. }
How can you be sure another thread will not swoop in and set myObject
to null in between lines 6 and 7 before you have a chance to get a
lock on it? You cannot synchronize on myObject if it is set to null
without throwing an exception. Do you just move the synchronized
block to before the IF statement and catch the exception if myObject
is null or is there a more elegant approach?
Mike