That's how I do it (android code)
private volatile static WifiManager wm;
private static WifiManager wm(Context ctx) {
WifiManager result = wm;
if (result == null) {
synchronized (WifiMonitor.class) { // the enclosing class
result = wm;
if (result == null) {
result = wm = (WifiManager) ctx
.getSystemService(Context.WIFI_SERVICE);
if (result == null) throw new WmNotAvailableException();
}
}
}
return result;
}
Bloch in Effective Java recommends :
// Lazy initialization holder class idiom for static fields
private static class FieldHolder {
static final FieldType field = computeFieldValue();
}
static FieldType getField() {
return FieldHolder.field;
}
This has the advantages of dispensing with the synchronization and that the JVM optimizes out the field access. The problem is that I need a Context object in my case. So :
- Is there a way to adapt Bloch's pattern to my case (
computeFieldValue()
needs a param) ? - If not, is there a way to execute around ? The code is subtle and I'd rather have it in one place and pass only required behavior in
- Last but not least - is there a way to enforce access to the cache field (
wm
) only via thewm()
method ? So I can avoid NPEs and such. Other languages use properties for this