-1

I am trying to fix double checked locking with Bloch's effective java recommendation. But a small variation in my code is that the field type is static and the method to create the field type is instance method. Will the below variation for creating a static field work?

private static volatile FieldType field4;

// NOTE: The code for this method in the first printing had a serious error (see errata for details)!
public FieldType getField4() {
    FieldType result = field4;
    if (result != null)    // First check (no locking)
        return result;
    
    synchronized(Initialization.class) {
        if (field4 == null) // Second check (with locking)
            field4 = computeFieldValue();
        return field4;
    }
}

I cannot make the method static method to // Lazy initialization holder class idiom for static fields - Page 334.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
sai prasad
  • 11
  • 4

1 Answers1

0

Assuming you are using Java 5 or later1, the above code is thread-safe2.

It doesn't matter that either the method or field is static provided that:

  1. field being initialized is volatile and,
  2. the code doing the DCL initialization is using the same mutex object for any given field.

The former is obviously true. The latter is true because all calls to getField4() are locking the same Class object.

1 - Prior to Java 5, the specified semantics of volatile are not sufficient to guarantee that the code is thread-safe.
2 - Thread-safe but ugly. It is better to avoid the DCL idiom and use one of the other alternatives.


I cannot make the method static method ...

I don't see why not. It is private so you should not be constrained as to whether it is a static or instance method. It should only affect the current class.

But as noted above, it doesn't make any difference to the idiom.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Agree -- it's ugly, but it's technically thread-safe (unless the type is a long- I think in that case, it's not guaranteed to be thread-safe). If the calculation method will always resolve to the same value and is relatively trivial in terms of performance, you could also just ditch the synchronisation and accept the race condition that two threads might simultaneously initialise the field to its computed value. – Neil Coffey Jan 20 '21 at 23:56
  • Thank you. My method is public not private, I mistakenly posted as private. – sai prasad Jan 21 '21 at 00:09