...
This noncompliant code example protects a resource, an open file, by using a a ReentrantLock.
However, the method fails to release the lock when an exception occurs while performing operations on the open file. When an exception is thrown, control transfers to the the catch
block block and the call to to unlock()
never never executes.
Code Block |
---|
|
public final class Client {
public void doSomething(File file) {
final Lock lock = new ReentrantLock();
InputStream in = null;
try {
lock.lock();
in = new FileInputStream(file);
// Perform operations on the open file
lock.unlock();
} catch (FileNotFoundException x) {
// Handle exception
} finally {
if (in != null) {
try {
in.close();
} catch (IOException x) {
// Handle exception
}
}
}
}
} |
Noncompliant Code Example (finally
Block)
This noncompliant code example attempts to rectify the problem of the lock not being released, by invoking Lock.unlock()
in the finally
block. This ensures that the lock is released regardless of whether or not an exception occurs. However, it does not acquire the lock until after trying to open the file. If the file cannot be opened, the lock may be unlocked without ever being locked in the first place.
Code Block |
---|
|
public final class Client {
public void doSomething(File file) {
final Lock lock = new ReentrantLock();
InputStream in = null;
try {
in = new FileInputStream(file);
lock.lock();
// 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
}
}
}
}
}
|
Compliant Solution (finally
Block)
This compliant solution encapsulates operations that could throw an exception in a try
block immediately after acquiring the lock (which cannot throw). The lock is acquired just before the try
block, which guarantees that it is held when the finally
block executes. Invoking Lock.unlock()
in the finally
block ensures that the lock is released regardless of whether or not an exception occurs.
Code Block |
---|
|
public final class Client {
public void doSomething(File file) {
final Lock lock = new ReentrantLock();
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
}
}
}
}
}
|
...