posted 17 years ago
There's a problem with that though - it's still possible for another thread to think that o == null after setO() has been called. That's the sort of weird thing that happens with threads if they're not properly synchronized. And in this case the synchronization only occurs after o has been accessed, which is to late to ensure that o is accessed correctly. You could fix this by making o transient, though that's bit unusual for something that isn't supposed to change. Or you could declare both setO() and x() to be synchronized - that is, synchronized on the current instance of the X class, not the o variable. In that way, you would synchronize before accessing o, and ensure that you got the correct o. For that matter, if you synchronize on the X instance, do you still need to sync on o at all? You may not need to anymore.
All in all, making o final is probably the simplest for you to do, if that's possible. We can't guess what these methods are really doing, so it's hard to offer good suggestions about what sort of redesign would make the most sense here.
"I'm not back." - Bill Harding, Twister