Eugene To Eugene To - 11 months ago 70
Java Question

Refresh Cache concurrently

Suppose I have Java Bean called MyCache that has multiple getters and setters.
I have one instance of MyCache in my application. And it's a volatile field 'myCache' in MyCacheHolder.
When I need to refresh MyCache I create a new copy of it (it takes time) and then I just assign the reference 'myCache' to this new object.

Many threads are reading MyCacheHolder.myCache concurrently. They will definitely get the latest Reference because it's volatile. But I'm not sure if they get the object that is fully initialized. The object is initializes via setters. Is it possile that reading threads won't see all fields of 'myCache'? If yes then how can I fix it?

Answer Source

Making the field myCache volatile is not enough to make it thread safe, you need to make the class MyCache thread safe too by either synchronizing access to your getters and setters or making MyCache immutable (all its non static fields must be final and themselves immutable). For me the best solution is making the class immutable since once the instance created as its state cannot change, it can be accessed by any number of threads without the need to synchronize access to any of its fields.