Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: still need to review exception CON26-EX1

...

During

...

initialization

...

of

...

a

...

shared

...

object,

...

the

...

object

...

must

...

only

...

be

...

accessible

...

to

...

the

...

thread

...

constructing

...

it.

...

However,

...

the

...

object

...

can

...

be

...

safely

...

published

...

(that

...

is,

...

made

...

visible

...

to

...

other

...

threads)

...

once

...

it

...

is

...

initialized.

...

The

...

Java

...

Memory

...

Model

...

(JMM)

...

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

...

initialized

...

object

...

is

...

not

...

published.

...

This

...

guideline

...

differs

...

from

...

other

...

guidelines

...

in

...

that

...

it

...

prohibits

...

publishing

...

a

...

reference

...

to

...

a

...

partially

...

initialized

...

member

...

object

...

instance

...

before

...

initialization

...

completes

...

while

...

CON14-J.

...

Do

...

not

...

let

...

the

...

"this"

...

reference

...

escape

...

during

...

object

...

construction

...

refers

...

to

...

the

...

this

...

reference

...

of

...

the

...

current

...

object.

...

Noncompliant

...

Code

...

Example

...

This

...

noncompliant

...

code

...

example

...

constructs

...

a

...

Helper

...

object

...

in

...

the

...

initialize()

...

method

...

of

...

class

...

Foo

...

.

...

The

...

helper

...

field

...

is

...

initialized

...

by

...

Helper

...

's

...

constructor.

{:=
Code Block
bgColor
#FFCCCC
}
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;
  }
  // ...
}
{code}

If

...

a

...

thread

...

accesses

...

helper

...

using

...

the

...

getHelper()

...

method

...

before

...

initialize()

...

has

...

been

...

called,

...

the

...

thread

...

will

...

observe

...

an

...

uninitialized

...

helper

...

field.

...

Later,

...

if

...

one

...

thread

...

calls

...

initialize()

...

,

...

and

...

another

...

calls

...

getHelper()

...

,

...

the

...

second

...

thread

...

might

...

observe the helper reference as null, or it might observe a fully-initialized Helper object with the n field set to 42, or it might observe a partially-initialized Helper object with an uninitialized n which contains the default value 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. In other words, the compiler can reorder the write to the helper instance field with the write that initializes the Helper object (that is, this.n = n) such that the former occurs first. This exposes a race window during which other threads may observe a partially-initialized Helper object instance.

There is a separate issue in that, if two threads call initialize(), then two Helper objects are created. This is a performance issue and not a correctness issue because n will be properly initialized and the unused Helper objects will be garbage-collected.

Compliant Solution (Synchronization)

Publishing partially-constructed object reference can be prevented by using method synchronization, as shown by this compliant solution.

Code Block
bgColor#CCCCFF
 the {{helper}} reference as {{null}}, or it might observe a fully-initialized {{Helper}} object with the {{n}} field set to 42, or it might observe a partially-initialized {{Helper}} object with an uninitialized  {{n}} which contains the default value {{0}}.

In particular, the [JMM|BB. Definitions#memory model] permits compilers to allocate memory for the new {{Helper}} object and assign it to the {{helper}} field before initializing it. In other words, the compiler can reorder the write to the {{helper}} instance field with the write that initializes the {{Helper}} object (that is, {{this.n = n}}) such that the former occurs first. This exposes a race window during which other threads may observe a partially-initialized {{Helper}} object instance.

There is a separate issue in that, if two threads call {{initialize()}}, then two {{Helper}} objects are created. This is a performance issue and not a correctness issue because {{n}} will be properly initialized and the unused {{Helper}} objects will be garbage-collected. 

h2. Compliant Solution (Synchronization)

Publishing partially-constructed object reference can be prevented by using method synchronization, as shown by this compliant solution.

{code:bgColor=#CCCCFF}
class Foo {
  private Helper helper;

  public synchronized Helper getHelper() {
    return helper;
  }

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

Synchronizing

...

both

...

methods

...

guarantees

...

that

...

they

...

will

...

not

...

execute

...

concurrently.

...

If

...

one

...

thread

...

calls

...

initialize()

...

just

...

before

...

another

...

thread

...

calls

...

getHelper()

...

,

...

the

...

synchronized

...

initialize()

...

method

...

will

...

always

...

finish

...

first.

...

The

...

synchronized

...

keywords

...

establish

...

a

...

happens-before relationship between the two threads. This guarantees that the thread calling getHelper() sees the fully initialized Helper object or none at all (that is, helper contains a null reference). This approach guarantees proper publication for both immutable and mutable members.

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.

Code Block
bgColor#CCCCFF
 relationship|BB. Definitions#happens-before order] between the two threads. This guarantees that the thread calling {{getHelper()}} sees the fully initialized {{Helper}} object or none at all (that is, {{helper}} contains a {{null}} reference). This approach guarantees proper publication for both immutable and mutable members.


h2. 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. 

{code:bgColor=#CCCCFF}
class Foo {
  private final Helper helper;

  public Helper getHelper() {
    return helper;
  }

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

Wiki Markup
However, this solution requires that the {{helper}} field is assigned to a new object during construction. According to the Java Language Specification, Section 17.5.2, "Reading Final Fields During Construction" \[[JLS 05|AA. Java References#JLS 05]\]:

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 (see CON14-J. Do not let the "this" reference escape during object construction).

Compliant Solution (Final Field and Thread-safe Composition)

Some collection classes provide thread-safe access to contained elements. If the Helper object is inserted into such a collection, it is guaranteed to be fully initialized before its reference is made visible. This compliant solution encapsulates the helper field in a Vector<Helper>.

Code Block
bgColor#CCCCFF


{quote}
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.
{quote}

Consequently, the reference to the {{helper}} field should not be published before class {{Foo}}'s constructor has finished its initialization (see [CON14-J. Do not let the "this" reference escape during object construction]). 


h2. Compliant Solution (Final Field and Thread-safe Composition)

Some collection classes provide thread-safe access to contained elements. If the {{Helper}} object is inserted into such a collection, it is guaranteed to be fully initialized before its reference is made visible. This compliant solution encapsulates the {{helper}} field in a {{Vector<Helper>}}. 

{code:bgColor=#CCCCFF}
class Foo {
  private final Vector<Helper> helper;

  public Foo() {
    helper = new Vector<Helper>();  
  }

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

  public synchronized void initialize() {
    if (helper.isEmpty()) {
      helper.add(new Helper(42));
    }
  }
}
{code}

The {{helper}} field is declared as {{final}} to guarantee that the vector is created before any accesses take place. It can be safely initialized by the {{initialize()}} method, which is synchronized and checks that only one {{Helper}} object is ever added to the vector.  If {{getHelper()}} is invoked before {{initialize()}}, it calls {{initialize()}} to avoid the possibility of a null-pointer dereference by the client. The {{getHelper()}} method does not require synchronization to simply return {{Helper}}, and because the synchronized {{initialize()}} method also checks to make sure {{helper}} is empty before adding a new {{Helper}} object, there is no possibility of exploiting a race condition to add a second object to the vector. 


h2. Compliant Solution (Static Initialization)

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

{code:bgColor=#CCCCFF}

The helper field is declared as final to guarantee that the vector is created before any accesses take place. It can be safely initialized by the initialize() method, which is synchronized and checks that only one Helper object is ever added to the vector. If getHelper() is invoked before initialize(), it calls initialize() to avoid the possibility of a null-pointer dereference by the client. The getHelper() method does not require synchronization to simply return Helper, and because the synchronized initialize() method also checks to make sure helper is empty before adding a new Helper object, there is no possibility of exploiting a race condition to add a second object to the vector.

Compliant Solution (Static Initialization)

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

Code Block
bgColor#CCCCFF
// Immutable Foo
final class Foo {
  private static final Helper helper = new Helper(42);

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

This

...

requires

...

the

...

helper

...

field

...

to

...

be

...

declared

...

static

...

.

...

Although

...

not

...

a

...

requirement,

...

it

...

is

...

recommended

...

that

...

the

...

field

...

be

...

declared

...

final

...

to

...

document

...

the

...

class's

...

immutability.

...

Wiki Markup
According to JSR-133, Section 9.2.3, "Static Final Fields"  \[[JSR-133 04|AA. Java References#JSR-133 04]\]:

...

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.

Compliant Solution (Immutable object - Final fields, Volatile Reference)

Wiki Markup
The Java memory model guarantees that any final fields of an object are fully initialized before a published object becomes visible \[[Goetz 06|AA. Java References#Goetz 06]\]. By declaring {{n}} as final, the {{Helper}} class is made [immutable|BB. Definitions#immutable]. Furthermore, if the {{helper}} field is declared {{volatile}} in compliance with [CON09-J. Ensure visibility of shared references to immutable objects], {{Helper}}'s reference is guaranteed to be made visible to any thread that calls {{getHelper()}} after {{Helper}} has been fully initialized.

{:=
Code Block
bgColor
#CCCCFF
}
class Foo {
  private volatile Helper helper;

  public Helper getHelper() {
    return helper;
  }

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

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

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

This

...

compliant

...

solution

...

requires

...

that

...

helper

...

be

...

declared

...

as

...

volatile and class Helper be immutable. If it were not immutable, the code would violate CON11-J.

...

Do

...

not

...

assume

...

that

...

declaring

...

an

...

object

...

reference

...

volatile

...

guarantees

...

visibility

...

of

...

its

...

members

...

and

...

additional

...

synchronization

...

would

...

be

...

necessary

...

(see

...

the

...

next

...

compliant

...

solution).

...

And

...

if

...

the

...

helper

...

field

...

were

...

not

...

volatile

...

,

...

it

...

would

...

violate

...

CON09-J.

...

Ensure

...

visibility

...

of

...

shared

...

references

...

to

...

immutable

...

objects

...

.

...

Similarly,

...

a

...

public

...

static

...

factory

...

method

...

that

...

returns

...

a

...

new

...

instance

...

of

...

Helper

...

can

...

be

...

provided

...

in

...

class

...

Helper

...

.

...

This

...

approach

...

allows

...

the

...

Helper

...

instance

...

to

...

be

...

created

...

in

...

a

...

private

...

constructor.

...

Compliant Solution (Mutable

...

Thread-safe

...

Object,

...

Volatile

...

Reference)

...

If

...

Helper

...

is

...

mutable,

...

but

...

thread-safe,

...

it

...

can

...

be

...

safely

...

published

...

by

...

declaring

...

the

...

helper

...

field

...

in

...

class

...

Foo

...

as

...

volatile.

Code Block
bgColor#CCCCFF
}}. 

{code:bgColor=#CCCCFF}
class Foo {
  private volatile Helper helper;

  public Helper getHelper() {
    return helper;
  }

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

// Mutable but thread-safe Helper
public class Helper {
  private volatile int n;
  private final Object lock = new Object();

  public Helper(int n) {
    this.n = n;
  }
  
  public void setN(int value) {
    synchronized (lock) {
      n = value;
    }
  }
}
{code}

Because

...

the

...

Helper

...

object

...

can

...

change

...

state

...

after

...

its

...

construction,

...

synchronization

...

is

...

necessary

...

to

...

ensure

...

visibility

...

of

...

mutable

...

members

...

after

...

initial

...

publication.

...

Consequently,

...

the

...

setN()

...

method

...

is

...

synchronized

...

to

...

provide

...

visibility

...

of

...

n

...

in

...

this

...

compliant

...

solution

...

(see

...

CON11-J.

...

Do

...

not

...

assume

...

that

...

declaring

...

an

...

object

...

reference

...

volatile

...

guarantees

...

visibility

...

of

...

its

...

members

...

).

...

If

...

the

...

Helper

...

class

...

is

...

not

...

properly

...

synchronized,

...

declaring

...

helper

...

as

...

volatile

...

in

...

class

...

Foo

...

only

...

guarantees

...

the

...

visibility

...

of

...

the

...

initial

...

publication

...

of

...

Helper

...

and

...

not

...

of

...

subsequent

...

state

...

changes.

...

Consequently,

...

volatile

...

references

...

alone

...

are

...

inadequate

...

for

...

publishing

...

objects

...

that

...

are

...

not

...

thread-safe.

...

If the helper field in class Foo is not declared as volatile, the field n should be declared as volatile so that a happens-before relationship is established between the initialization of n and the write of Helper to the field helper. This is in compliance with CON11-J. Do not assume that declaring an object reference volatile guarantees visibility of its members. This is only required when the caller (class Foo) cannot be trusted to declare helper as volatile.

Because the the Helper class is declared as public, it uses a private lock to handle synchronization in conformance with CON04-J. Use private final lock objects to synchronize classes that may interact with untrusted code.

Exceptions

Wiki Markup
*CON26-EX1:* Security sensitive objects prior to Java SE 6 (but under the revised Java Memory Model under JSR-133 (JMM) \[[JSR-133 04|AA. Java References#JSR-133 04]\]) checked a {{volatile}} {{boolean}} flag in every method of the class to ensure that the object is unusable when it is in an uninitialized or partially-initialized state. The flag was always set in the last statement of the initializing code. This guideline may be violated if the code uses this technique for providing backward compatibility or if the caller is untrusted and consequently, may not declare the object reference as volatile. 

...

This

...

exception

...

uses

...

a

...

volatile

...

initialized

...

flag.

...

The

...

corresponding

...

Foo

...

class

...

is

...

the

...

same

...

as

...

the

...

noncompliant

...

code

...

example.

Code Block
bgColor#CCCCFF
 

{code:bgColor=#CCCCFF}
public class Helper {
  private int n;
  private volatile boolean initialized; // Defaults to false

  public Helper(int n) {
    this.n = n;
    this.initialized = true;
  }
  
  public void doSomething() {
    if (!initialized) {
      throw new SecurityException("Cannot use partially initialized instance");
    }
    // ... 
  }
  // ...
}
{code}

This

...

ensures

...

that

...

even

...

if

...

the

...

reference

...

to

...

the

...

Helper

...

object

...

instance

...

is

...

published

...

before

...

its

...

initialization

...

is

...

over,

...

the

...

instance

...

is

...

unusable.

...

The

...

instance

...

is

...

unusable

...

because

...

every

...

method

...

within

...

Helper

...

must

...

check

...

the

...

flag

...

to

...

determine

...

whether

...

the

...

initialization

...

has

...

finished.

...

Wiki Markup
From SE 6 onwards, this technique is superseded by a mechanism that recommends performing any checks that might leave the code uninitialized as a result of exceptions, in a call to a private constructor or a superclass constructor. An exception thrown before the completion of {{Object}}'s constructor ensures that a subclass cannot obtain a partially initialized instance \[[SCG 09|AA. Java References#SCG 09]\]. (For more information, see the guideline [OBJ04-J. Do not allow partially initialized objects to be accessed])

...

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

Wiki Markup
\[[API 06|AA. Java References#API 06]\] 
\[[Bloch 01|AA. Java References#Bloch 01]\] Item 48: "Synchronize access to shared mutable data"
\[[Goetz 06|AA. Java References#Goetz 06]\] Section 3.5.3 "Safe Publication Idioms"
\[[Goetz 07|AA. Java References#Goetz 07]\] Pattern #2: "one-time safe publication"
\[[JPL 06|AA. Java References#JPL 06]\] 14.10.2. "Final Fields

...

 and Security"
\[[Pugh 04|AA. Java References#Pugh 04]\]

...

CON25-J. Ensure atomicity when reading and writing 64-bit values      11. Concurrency (CON)      CON27-J. Do not execute classes that use ThreadLocal objects in a thread pool