Reputation: 143
I have a singleton class like below
class A{
private volatile static A a;
//declaration of LinkedHashMap
private A(){
//lot of code that puts values in the map
}
public static A getInstance() {
if (a== null) {
synchronized (A.class) {
if (a== null) {
a = new A();
}
}
}
return a;
}
}
I want to refresh the instance of A at some particular condition. How can I refresh the object without using reflection. If not a good practice,what else I can use to ensure that my map gets refreshed only in my particular condition. In short,I want to refreshed my cached map in particular condition without using reflection or without restarting my server.
Upvotes: 1
Views: 3396
Reputation: 102998
you're much better off writing your singleton as simply: 'private static A a = new A();' – this doesn't cost you anything (it's not invoked unless somebody somewhere refers to A in their code, and then it'll be invoked at that point in time), and fixes the problems with how your snippet here attempts to (incorrectly) try to make a singleton.
For refreshing, well, just.. write a method for that. Don't lock on publicly visible things (A.class is addressable by all code), that's like having public fields. Make a private object that you lock on. Then, have a method called 'getMap' which synchronizes on this private lock, as well as a method called 'refreshMap' which also does this. Now any code that calls getMap, whilst the refresh op is running, will wait until the refresh op is done and then return the newly made map. Call refresh yourself if the map is null. So, something like:
public class A {
private static final A INSTANCE = new A();
private LinkedHashMap<Integer, String> map;
private final Object locker = new Object();
private A() {}
public static A getInstance() {
return INSTANCE; // Look how simple this got!
}
public Map<Integer, String> getMap() {
synchronized (locker) {
if (map == null) refresh();
return map;
}
}
public void refresh() {
synchronized (locker) {
// refresh map here...
map = ....;
}
}
}
Upvotes: 2