posted 15 years ago
Of those two code examples, I think you're much better off with the second one, synchronizing the whole getEnabled() method. Imagine what happens if two threads call getEnabled() just past 10 minutes since the last DB refresh.
With the first code (using synchronized(this)): Thread A will check the time, see it's past 10 minutes, enter the synchronized(this) block, and do a DB update. Thread B will check the time, try to enter the synch block, block until thread A completes its update, and then... thread B will do another DB update, even though thread A just completed such an update.
With the second code (using a synchronized method): Thread A will enter the sync method, check the time, see it's past 10 minutes, and do a DB update. Thread B will try to enter the sync method, block until thread A completes its work, then enter, check the time, and skip the DB update because it can easily use the value of enabled set by thread A much less than 10 minutes ago.
The DB update is by far the slowest thing in all this code, and repeating it is silly. Thus, I recommend the second code over the first, definitely.
However, a better solution might be to just create a ScheduledExecutorService (or a java.util.Timer) to, in a separate thread from everything else, update the enabled field every 10 minutes. And make enabled volatile. That way the other threads will never have to wait for a DB update. It will just be done automatically every 10 minutes. A thread that checks enabled just before a refresh will see the old value, and one that checks after that will see the new value.