I think you need something like a factory to have objects with various parameters instantiated and reused. It could be implemented by using a synchronized HashMap
or ConcurrentHashMap
map a parameter (an Integer
for an example) to your 'singleton' parameterizable class.
Although you might get to the point where you should use regular, non-singleton classes instead (for example needing 10.000 differently parametrized singleton).
Here is an example for such store:
public final class UsefulObjFactory {
private static Map<Integer, UsefulObj> store =
new HashMap<Integer, UsefulObj>();
public static final class UsefulObj {
private UsefulObj(int parameter) {
// init
}
public void someUsefulMethod() {
// some useful operation
}
}
public static UsefulObj get(int parameter) {
synchronized (store) {
UsefulObj result = store.get(parameter);
if (result == null) {
result = new UsefulObj(parameter);
store.put(parameter, result);
}
return result;
}
}
}
To push it even further, the Java enum
s can be also considered (or used as) parametrized singletons, although allowing only a fixed number static variants.
However, if you need a distributed1 solution, consider some lateral caching solution. For example: EHCache, Terracotta, etc.
1 in the sense of spanning multiple VMs on probably multiple computers.