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

VNA02-J

public void setValues(int a, int b) { this.a = a;

this.b = b;

}

}

The getSum() method contains a race condition. For example, if a and b currently have the values 0 and Integer.MAX_VALUE, respectively, and one thread calls getSum() while another calls setValues(Integer.MAX_VALUE, 0), the getSum() method might return 0 or

Integer.MAX_VALUE, or it might overflow and wrap. Overflow will occur when the first thread reads a and b after the second thread has set the value of a to Integer.MAX_VALUE, but before it has set the value of b to 0.

Note that declaring the variables volatile does not resolve the issue because these compound operations involve reads and writes of multiple variables.

2.3.9Noncompliant Code Example (Addition of Atomic Integers)

In this noncompliant code example, a and b are replaced with atomic integers.

final class Adder {

private final AtomicInteger a = new AtomicInteger(); private final AtomicInteger b = new AtomicInteger();

public int getSum() { return a.get() + b.get();

}

public void setValues(int a, int b) { this.a.set(a);

this.b.set(b);

}

}

The simple replacement of the two int fields with atomic integers in this example does not eliminate the race condition because the compound operation a.get() + b.get() is still nonatomic.

2.3.10 Compliant Solution (Addition)

This compliant solution synchronizes the setValues() and getSum() methods to ensure atomicity.

final class Adder { private int a; private int b;

public synchronized int getSum() { return a + b;

CMU/SEI-2010-TR-015 | 21

VNA02-J

}

public synchronized void setValues(int a, int b) { this.a = a;

this.b = b;

}

}

Any operations within the synchronized methods are now atomic with respect to other synchronized methods that lock on that object’s monitor (intrinsic lock). It is now possible, for example, to add overflow checking to the synchronized getSum() method without introducing the possibility of a race condition.

2.3.11 Risk Assessment

If operations on shared variables are non-atomic, unexpected results can be produced. For example, information can be disclosed inadvertently because one user can receive information about other users.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

 

 

 

 

 

 

VNA02-J

medium

probable

medium

P8

L2

2.3.12 References

[Bloch 2008] Item 66: Synchronize access to shared mutable data

[Goetz 2006] Section 2.3, “Locking”

[Gosling 2005] Chapter 17, “Threads and Locks”

Section 17.4.5, “Happens-Before Order”

Section 17.4.3, “Programs and Program Order”

Section 17.4.8, “Executions and Causality Requirements”

[Lea 2000a] Section 2.2.7, The Java Memory Model

Section 2.1.1.1, Objects and Locks

[MITRE 2010] CWE ID 667, “Insufficient Locking”

CWE ID 413, “Insufficient Resource Locking” CWE ID 366, “Race Condition within a Thread”

CWE ID 567, “Unsynchronized Access to Shared Data”

[Sun 2009b] Class AtomicInteger

[Sun 2008a] Java Concurrency Tutorial

CMU/SEI-2010-TR-015 | 22

VNA03-J

2.4VNA03-J. Do not assume that a group of calls to independently atomic methods is atomic

A consistent locking policy guarantees that multiple threads cannot simultaneously access or modify shared data. If two or more operations need to be performed as a single atomic operation, a consistent locking policy must be implemented using either intrinsic synchronization or java.util.concurrent utilities. In the absence of such a policy, the code is susceptible to race conditions.

Given an invariant involving multiple objects, a programmer may incorrectly assume that individually atomic operations require no additional locking. Similarly, programmers may incorrectly assume that using a thread-safe Collection does not require explicit synchronization to preserve an invariant that involves the collection’s elements. A thread-safe class can only guarantee atomicity of its individual methods. A grouping of calls to such methods requires additional synchronization.

Consider, for example, a scenario where the standard thread-safe API does not provide a single method to both find a particular person’s record in a Hashtable and update the corresponding payroll information. In such cases, the two method invocations must be performed atomically.

Enumerations and iterators also require explicit synchronization on the collection object (clientside locking) or a private final lock object.

Compound operations on shared variables are also non-atomic. For more information, see guideline “VNA02-J. Ensure that compound operations on shared variables are atomic” on page 16.

Guideline “VNA04-J. Ensure that calls to chained methods are atomic” on page 29 describes a specialized case of this guideline.

2.4.1Noncompliant Code Example (AtomicReference)

This noncompliant code example wraps BigInteger objects within thread-safe

AtomicReference objects.

final class Adder {

private final AtomicReference<BigInteger> first; private final AtomicReference<BigInteger> second;

public Adder(BigInteger f, BigInteger s) { first = new AtomicReference<BigInteger>(f); second = new AtomicReference<BigInteger>(s);

}

public void update(BigInteger f, BigInteger s) { // Unsafe first.set(f);

second.set(s);

}

public BigInteger add() { // Unsafe

CMU/SEI-2010-TR-015 | 23

VNA03-J

return first.get().add(second.get());

}

}

AtomicReference is an object reference that can be updated atomically. However, operations that combine more than one atomic reference are non-atomic. In this noncompliant code example, one thread may call update() while a second thread may call add(). This might cause the add() method to add the new value of first to the old value of second, yielding an erroneous result.

2.4.2Compliant Solution (Method Synchronization)

This compliant solution declares the update() and add() methods synchronized to guarantee atomicity.

final class Adder {

// ...

public synchronized void update(BigInteger f, BigInteger s){ first.set(f);

second.set(s);

}

public synchronized BigInteger add() { return first.get().add(second.get());

}

}

2.4.3Noncompliant Code Example (synchronizedList)

This noncompliant code example uses a java.util.ArrayList<E> collection, which is not thread-safe. However, Collections.synchronizedList is used as a synchronization wrapper for ArrayList. An array, rather than an iterator, is used to iterate over ArrayList to avoid a ConcurrentModificationException.

final class IPHolder {

private final List<InetAddress> ips = Collections.synchronizedList(new ArrayList<InetAddress>());

public void addAndPrintIPAddresses(InetAddress address) { ips.add(address);

InetAddress[] addressCopy = (InetAddress[]) ips.toArray(new InetAddress[0]); // Iterate through array addressCopy ...

}

}

Individually, the add() and toArray() collection methods are atomic. However, when they are called in succession (for example, in the addAndPrintIPAddresses() method), there are no guarantees that the combined operation is atomic. A race condition exists in the

CMU/SEI-2010-TR-015 | 24

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