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

Compare with Current View Page History

« Previous Version 8 Next »

Sometimes you must share an object among multiple threads. During initialization, the object must remain exclusive to the thread constructing it, However, once the object is initialized, it can be published, that is, made visible to other threads.

The Java Memory Model permits a compiler to modify the order of execution instructions in such a way that a seemingly innocuous publication results in multiple threads observing the object after initialization has begun, but before it is fully initialized.

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 threads have access to the same Foo object through the use of the getHelper() method, and initialize() has not been called yet. Both 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 uninitialized n (default value of n being 0).

In particular, the 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.

Compliant Solution (volatile)

If the helper field is declared as volatile, it is guaranteed to be fully constructed (properly initialized) before the reference is made visible.

class Foo {
  private volatile Helper helper;

  public Helper getHelper() {
    return helper;
  }

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

Compliant Solution (final)

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

class Foo {
  private final Helper helper;

  public Helper getHelper() {
    return helper;
  }

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

However, this disallows setting the helper field to a new object.

Compliant Solution (immutable)

If the Helper class is [immutable], it is guaranteed to be fully constructed before its reference is made visible. The Helper object must be truly immutable; it is not sufficient for the program to refrain from modifying the object.

public class Helper {
  private final int n;

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

  // ...
}

Note that if the Helper object was mutable, in addition to the problem of visibility of a reference to a partially-constructed object, another problem would ensue. The state of the object may be modified after its construction and publication, causing subtle thread-safety issues. For more information see [CON11-J. Do not assume that declaring an object volatile guarantees visibility of its members].

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() {
    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.

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 constructed before its reference is made visible. This compliant solution encases the helper field in a Vector.

class Foo {
  private Vector<Helper> helper;

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

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

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 constructed before its reference is made visible.

Unknown macro: {mc}

cite JLS section here

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

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

This requires the helper field to be declared static.

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"
[[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