I have a long-lived server application that is designed to run with minimal downtime (e.g. 24/7 operation stopping only for maintenance). The application has to be able to handle thousands of requests a second, so performance is a concern.
To service each request. part of the application needs to know what the current date is (although not the time) and it must be stored in a java.util.Date object because of a 3rd party API.
However,Date objects are expensive to construct so creating a new one for each request doesn’t sound sensible.
Sharing a Date object between requests and updating it once a day would mean only a single object would need to be created (per server worker thread) at startup, but then how can you update it in a safe manner?
For example, using a ScheduledExecutorService that runs just after midnight could increment the Date, but introduces Thread synchronisation into the mix: the Date object is now shared between the main thread and the thread that the ScheduledExecutorService spawns to run the update task.
Synchronising the 2 threads introduces another performance headache, due to the likelihood of contention on the shared resource between the thousands of requests being serviced (the single execution of the update thread per day is less of a concern because it only happens once per day, unlike the millions of requests we will service daily).
So, my question is What is the most efficient way to ensure the application always knows what the current date is, even when running continuously for weeks on end?
@chrisbunney, a couple of the answers on this thread have suggested using special-purpose concurrency classes, but if you really did need to cache a date as you originally asked, there’s only one thing you need: the
volatilekeyword.AtomicReferenceis good if you need an atomic check-and-swap operation, but in this case, you’re not checking anything. You’re just setting a reference to a new value, and you want that value to be visible to all threads. That’s whatvolatiledoes.If you were modifying the internal state of an existing object, then you might need locks. Or if you were going to read the value of the existing
Date, do some calculations based on that, and generate a newDateobject as a result, again some type of locking (or something likeAtomicReference) would be necessary. But you’re not doing that; again, you’re only replacing a reference, with no regard to its previous value.In general, if you have only one thread which ever replaces a value, and other threads only read the value,
volatileis enough. No other concurrency control is needed. Or if you have multiple threads which can replace a value, but they only replace, not modify in-place, and they replace it with no regard for its previous value, then again,volatileis enough. Nothing else is needed.