Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Java concurrency guidelines.pdf
Скачиваний:
16
Добавлен:
23.05.2015
Размер:
1.35 Mб
Скачать

VNA06-J

// Validate the values before inserting if (!value.matches("[\\w]*")) {

throw new IllegalArgumentException();

}

properties.setProperty(key, value);

}

}

The volatile-read, synchronized-write technique uses synchronization to preserve the atomicity of compound operations, such as increment, and provides faster access times for atomic reads. However, it does not work with mutable objects because the visibility of volatile object references does not extend to object members. Consequently, there is no happens-before relationship between the write and a subsequent read of the property.

This technique is also discussed in guideline “VNA02-J. Ensure that compound operations on shared variables are atomic” on page 16.

2.7.6Compliant Solution (Synchronization)

This compliant solution uses method synchronization to guarantee visibility.

final class Foo {

private final Properties properties;

public Foo() {

properties = new Properties();

// Load some useful values into properties

}

public synchronized String get(String s) { return properties.getProperty(s);

}

public synchronized void put(String key, String value) { // Validate the values before inserting

if (!value.matches("[\\w]*")) {

throw new IllegalArgumentException();

}

properties.setProperty(key, value);

}

}

The properties field does not need to be volatile because the methods are synchronized. The field is declared final so that its reference is not published when it is in a partially initialized state (see guideline “TSM03-J. Do not publish partially initialized objects” on page 162 for more information).

CMU/SEI-2010-TR-015 | 38

VNA06-J

2.7.7Noncompliant Code Example (Mutable Sub-Object)

In this noncompliant code example, the volatile format field is used to store a reference to a mutable object, java.text.DateFormat.

final class DateHandler {

private static volatile DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM);

public static Date parse(String str) throws ParseException { return format.parse(str);

}

}

Because DateFormat is not thread-safe [Sun 2009c], the parse() method might return a value for Date that does not correspond to the str argument.

2.7.8Compliant Solution (Instance Per Call/Defensive Copying)

This compliant solution creates and returns a new DateFormat instance for every invocation of the parse() method [Sun 2009c].

final class DateHandler {

public static Date parse(String str) throws ParseException { return DateFormat.getDateInstance(DateFormat.MEDIUM).parse(str);

}

}

This solution does not violate guideline “OBJ11-J. Defensively copy private mutable class members before returning their references”3 because the class no longer contains internal mutable state.

2.7.9Compliant Solution (Synchronization)

This compliant solution synchronizes statements within the parse() method, making DateHandler thread-safe [Sun 2009c].

final class DateHandler {

private static DateFormat format= DateFormat.getDateInstance(DateFormat.MEDIUM);

public static Date parse(String str) throws ParseException { synchronized (format) {

return format.parse(str);

}

}

}

3

This guideline is described at https://www.securecoding.cert.org/confluence/display/java/.

 

CMU/SEI-2010-TR-015 | 39

VNA06-J

2.7.10 Compliant Solution (ThreadLocal Storage)

This compliant solution uses a ThreadLocal object to create a separate DateFormat instance per thread.

final class DateHandler {

private static final ThreadLocal<DateFormat> format = new ThreadLocal<DateFormat>() {

@Override protected DateFormat initialValue() {

return DateFormat.getDateInstance(DateFormat.MEDIUM);

}

}; // ...

}

2.7.11 Risk Assessment

Incorrectly assuming that declaring a field volatile guarantees that the visibility of a referenced object’s members can cause threads to observe stale values.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

VNA06-J

medium

probable

medium

P8

L2

 

 

 

 

 

 

2.7.12 References

[Goetz 2006c]

Pattern #2: “one-time safe publication”

[Gosling 2005]

 

[Miller 2009]

Mutable Statics

[Sun 2009c]

Class java.text.DateFormat

CMU/SEI-2010-TR-015 | 40

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]