I have a Static helper class implemented that helps cache and retreive some read-only, non-mutable, non-volatile data from the database.
(Stripped) Example:
public class CacheHelper
{
private static HashMap foos, bars;
public static Foo getFoo(int fooId) { /* etc etc */ }
public static Bar getBar(int barId) { /* etc etc */ }
public static void reloadAllCaches()
{
//This is where I need it to lock access to all the other static methods
}
}
The way I’ve read it for static classes, If I add the synchronized keyword to the reloadAllCaches() method, this will apply a lock on the entire class while that method executes. Is this correct? (Edit: Yep, not correct. Thanks for the responses. )
Note: I would like to remain agnostic to the thread safety of the getter methods and the objects they return as this data is never mutated and would like it to be returned as fast as possible.
If you add the
synchronizedkeyword to the reloadAllCaches() function all other static functions in the class that got thesynchronizedkeyword can’t execute while the reloadAllCaches() function is running.How ever non-static functions can execute, not matter if they got the
synchronizedkeyword or not. Also all other functions without thesynchronizedkeyword can execute.After all a function with the
synchronizedcan be looked at like:A non-static function with the
synchronizedkeyword can be looked at like this:So static and non-static functions have a different synchronization context and do not block the execution of each other with the synchronized keyword.
For your case I suggest the usage of a
ReentrantReadWriteLock. This class will allow any number of functions to get a read-lock at the same time but only one function to get a Write-Lock. The write lock is only acquired when there is no read-lock in place and no read-lock is acquired as long as a write-lock is in place.You can make your reload function fetching a write-lock and all your reading function fetching a write-lock. You have to use a static instance of the
ReentrantReadWriteLockof cause.My proposal is to implement it like this: