You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 29 Next »

Sometimes an object is required to be shared amongst multiple threads. During initialization, the object must remain exclusive to the thread constructing it. However, once the object is initialized, it can be safely published. That is, it can be made visible to other threads. The [Java Memory Model] allows multiple threads to observe the object after its initialization has begun, but before it has concluded. Consequently, it is important to ensure that a partially constructed object is not published.

This guideline is similar to [CON14-J. Do not let the "this" reference escape during object construction]. The difference is that in this guideline, a reference to a partially constructed member object instance is published instead of the this reference of the current object, before initialization is over.

Noncompliant Code Example

This noncompliant code example initializes a Helper object inside class Foo.

class Foo {
  private Helper helper;

  public Helper getHelper() {
    return helper;
  }

  public void initialize() {
    helper = new Helper(42);
  }
}

public class Helper {
  private int n;

  public Helper(int n) {
    this.n = n;
  }

  // ...
}

Suppose two or more threads have access to the same Foo object through the use of the getHelper() method, and initialize() has not been called yet. All threads will see the helper field as uninitialized. Subsequently, if one thread calls initialize(), and the other calls getHelper(), the second thread may either see the helper reference as null, observe a fully-initialized Helper object with the n field set to 42, or observe a partially-initialized Helper object with an n that has not yet been initialized, still containing the default value 0.

In particular, the [Java Memory Model (JMM)] permits compilers to allocate memory for the new Helper object and assign it to the helper field before initializing it. This introduces a race window during which other threads may see a partially-initialized Helper object instance.

There is another consideration in that if two threads both call initialize(), then two Helper objects will be created, with one eventually being garbage-collected. This is a performance issue, not a correctness issue.

Compliant Solution (synchronized)

The reference of a partially-constructed object can be prevented from being made visible by using method synchronization.

class Foo {
  private Helper helper;

  public synchronized Helper getHelper() {
    return helper;
  }

  public synchronized void initialize() {
    if (helper == NULL {
      helper = new Helper(42);
    }
  }
}

Synchronizing both methods guarantees that they will never run simultaneously in different threads. If one thread were to call initialize() just before another thread calls getHelper(), the synchronized initialize() method will always finish first, fully initializing the Helper object on its way. This forbids getHelper() from retrieving a Helper object that is partially initialized. This approach guarantees proper publication for both immutable and mutable members.

This code also adds a check in initialize() in order to prevent helper from getting initialized twice.

Compliant Solution (final field)

If the helper field is declared as final, it is guaranteed to be fully constructed before its reference is made visible.

class Foo {
  private final Helper helper;

  public Helper getHelper() {
    return helper;
  }

  public Foo() {
    helper = new Helper(42);
  }
}

However, the compiler now disallows setting the helper field to a new object using the initialize() method. Instead, a constructor must be used to initialize helper.

According to the Java Language Specification [[JLS 05]], section 17.5.2 "Reading Final Fields During Construction":

A read of a final field of an object within the thread that constructs that object is ordered with respect to the initialization of that field within the constructor by the usual happens-before rules. If the read occurs after the field is set in the constructor, it sees the value the final field is assigned, otherwise it sees the default value.

Consequently, the reference to the helper field should not be published before class Foo's constructor has finished its initialization.

Compliant Solution (immutable + volatile)

While an object may be published partially constructed, the memory model guarantees that any final fields of the object will be fully initialized before a published object becomes visible [[Goetz 06]] . By making n final, we can render the Helper class [immutable]. Furthermore, if the helper field is declared volatile, it is guaranteed to be visible to any thread that calls getHelper() after it has been fully initialized.

class Foo {
  private volatile Helper helper;

  public Helper getHelper() {
    return helper;
  }

  public void initialize() {
    helper = new Helper(42);
  }
}

// Immutable Helper
public class Helper {
  private final int n;

  public Helper(int n) {
    this.n = n;
  }
  // ...
}

Note that if the state of the Helper object could be changed after its construction, additional locking would be necessary to ensure all threads see the most recent state. See [CON11-J. Do not assume that declaring an object volatile guarantees visibility of its members] for more information. This is typically the case when a mutable, but thread-safe member object is expected to continually publish its most recent state when its reference is declared volatile. The use of volatile guarantees the visibility of only the initial publication and not of subsequent state changes. Consequently, the use of volatile to publish thread-safe objects is often not very useful, whereas immutable objects can safely use this solution.

Primitive types can also be safely published by publishing an atomic reference to the corresponding boxed type. For instance, an int field can be safely published by publishing an atomic reference to the equivalent Integer using java.util.concurrent.atomic.AtomicReference<Integer>.

Compliant Solution (thread-safe composition)

Some collection classes provide thread-safety of accesses to contained elements. If the helper field is contained in such a collection, the Helper object is guaranteed to be fully initialized before its reference is made visible. This compliant solution encases the helper field in a Vector. It synchronizes the initialization to prevent two Helper objects from being created and added to the vector.

class Foo {
  private Vector<Helper> helper;

  public Helper getHelper() {
    return helper.elementAt(0);
  }

  public synchronized void initialize() {
    if (helper == null) {
      helper = new Vector<Helper>();
      helper.add(new Helper(42));
    }
  }
}

If the Foo object were mutable, additional locking may be required to ensure that this ability does not lead to data races.

Compliant Solution (static initialization)

In this compliant solution, the helper field is initialized in a static block. When initialized statically, any object is guaranteed to be fully initialized before its reference is made visible.

Unknown macro: {mc}

cite JLS section here

class Foo {
  private static final Helper helper = new Helper(42);

  public static Helper getHelper() {
    return helper;
  } 
}

This requires the helper field to be declared static. It is recommended that the field be declared final as well to sufficiently document the class's immutability property.

According to JSR-133 [[JSR-133 04]], 9.2.3 Static Final Fields:

The rules for class initialization ensure that any thread that reads a static field will be synchronized with the static initialization of that class, which is the only place where static final fields can be set. Thus, no special rules in the JMM are needed for static final fields.

Risk Assessment

Failing to synchronize access to shared mutable data can cause different threads to observe different states of the object or a partially initialized object.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CON26-J

medium

probable

medium

P8

L2

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

[[API 06]]
[[Bloch 01]] Item 48: "Synchronize access to shared mutable data"
[[Goetz 06]] Section 3.5.3 "Safe Publication Idioms"
[[Goetz 07]] Pattern #2: "one-time safe publication"
[[JPL 06]], 14.10.2. Final Fields and Security:
[[Pugh 04]]


[!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_left.png!]      [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_up.png!]      [!The CERT Sun Microsystems Secure Coding Standard for Java^button_arrow_right.png!]

  • No labels