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

LCK07-J

Consequently, while one thread is calculating the average bandwidth or response time, another thread cannot interfere or induce deadlock. That is because the other thread first needs to synchronize on the first web request, which cannot happen before the first calculation completes.

There is no need to lock on the last element of the vector in addWebRequest() for two reasons:

(1) because locks are acquired in increasing order in all the methods and (2) because updates to the vector are reflected in the results of the computations.

3.8.7Risk Assessment

Acquiring and releasing locks in the wrong order can result in deadlock.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

LCK07- J

low

likely

high

P3

L3

3.8.8References

[Gosling 2005]

Chapter 17, “Threads and Locks”

[Halloway 2000]

 

[MITRE 2010]

CWE ID 412, “Unrestricted Lock on Critical Resource”

CMU/SEI-2010-TR-015 | 72

LCK08-J

3.9LCK08-J. Ensure actively held locks are released on exceptional conditions

An exceptional condition can circumvent the release of a lock, leading to deadlock. According to the Java API [Sun 2009b]

A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread.

Consequently, an unreleased lock in any thread will stop other threads from acquiring the same lock. Intrinsic locks of class objects used for method and block synchronization are automatically released on exceptional conditions (such as abnormal thread termination).

3.9.1Noncompliant Code Example (Checked Exception)

This noncompliant code example protects a resource using a ReentrantLock but fails to release the lock if an exception occurs while performing operations on the open file. If an exception is thrown, control transfers to the catch block, and the call to unlock() is not executed.

public final class Client {

public void doSomething(File file) { final Lock lock = new ReentrantLock(); try {

lock.lock();

InputStream in = new FileInputStream(file);

//Perform operations on the open file lock.unlock();

}catch (FileNotFoundException fnf) {

//Handle the exception

}

}

}

Note that the lock is not released, even when the doSomething() method returns.

This noncompliant code example does not close the input stream and, consequently, also violates guideline “FIO06-J. Ensure all resources are properly closed when they are no longer needed.”5

3.9.2Compliant Solution (finally Block)

This compliant solution encapsulates operations that may throw an exception in a try block immediately after acquiring the lock. The lock is acquired just before the try block, which guarantees that the lock is held when the finally block executes. Invoking Lock.unlock() in the finally block ensures that the lock is released, regardless of whether an exception occurred.

public final class Client {

public void doSomething(File file) { final Lock lock = new ReentrantLock();

5

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

 

CMU/SEI-2010-TR-015 | 73

LCK08-J

InputStream in = null; lock.lock();

try {

in = new FileInputStream(file);

//Perform operations on the open file

}catch(FileNotFoundException fnf) {

//Forward to handler

}finally { lock.unlock();

if(in != null) { try {

in.close();

}catch (IOException e) { // Forward to handler

}

}

}

}

}

3.9.3Compliant Solution (Execute-Around Idiom)

The execute-around idiom provides a generic mechanism for performing resource allocation and clean-up operations so that the client can focus on specifying only the required functionality. This idiom reduces clutter in client code and provides a secure mechanism for resource management.

In this compliant solution, the client’s doSomething() method provides only the required functionality by implementing the doSomethingWithFile() method of the LockAction interface, without having to manage the acquisition and release of locks or the open and close operations of files. The ReentrantLockAction class encapsulates all resource management actions.

public interface LockAction {

void doSomethingWithFile(InputStream in);

}

public final class ReentrantLockAction {

public static void doSomething(File file, LockAction action) { Lock lock = new ReentrantLock();

InputStream in = null; lock.lock();

try {

in = new FileInputStream(file); action.doSomethingWithFile(in);

}catch (FileNotFoundException fnf) { // Forward to handler

}finally { lock.unlock();

CMU/SEI-2010-TR-015 | 74

LCK08-J

if (in != null) { try {

in.close();

}catch (IOException e) {

//Forward to handler

}

}

}

}

public final class Client {

public void doSomething(File file) { ReentrantLockAction.doSomething(file, new LockAction() {

public void doSomethingWithFile(InputStream in) { // Perform operations on the open file

}

});

}

}

3.9.4Noncompliant Code Example (Unchecked Exception)

This noncompliant code example uses a ReentrantLock to protect a java.util.Date instance, which is not thread-safe by design. The doSomethingSafely() method must catch Throwable to comply with guideline “EXC06-J. Do not allow exceptions to transmit sensitive information.”6

final class DateHandler {

private final Date date = new Date(); final Lock lock = new ReentrantLock(); public void doSomethingSafely(String str) {

try { doSomething(str);

}catch(Throwable t) {

//Forward to handler

}

public void doSomething(String str) { lock.lock();

String dateString = date.toString(); if (str.equals(dateString)) {

// ...

}

lock.unlock();

}

}

6

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

 

CMU/SEI-2010-TR-015 | 75

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