Reputation: 42100
This is a follow-up of my previous question.
Suppose I have a server application, which uses some read-only file. Sometimes (e.g. once a few hours) we update this file and the application starts working with the updated data.
How to implement it? I believe the application should check for an update periodically and update the file if an update is available. Once the file is updated the application should perform all necessary initialization (e.g. invalidate internal caches, etc.) while still working with the "old" data. Once the initialization completes it discards the "old" data and works only with the "new" one.
Does it make sense? This problem looks very generic. Is there any off-the-shelf Java infrastructure, which solves this problem?
Upvotes: 0
Views: 93
Reputation: 49095
Sounds like cache. Two flexible thread safe cache implementations are Guava's cache, EhCache or Hazelcast. All three will expire and reload in a thread safe manner. Hazelcast and EhCache can be distributed over a network. Guava is not distributed but is much simpler.
If you decide you don't want to use cache the other common use case for some long held in memory object like a singleton is double checked locking. Guava makes it much more elegantly with its Suppliers memoize function.
I recommend you use immutable objects with caches or @MarkoTopolnik suggestion of volatile
.
Upvotes: 3
Reputation: 200236
You should have a single object that represents all the data, and services derived from it, read from the file. Maintain a volatile
reference to that object, which will ensure thread-safe publication.
Upvotes: 1