...
Code Block | ||
---|---|---|
| ||
class DateHandler { private 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 (dateStringstr.equals(strdateString)) { // ... } lock.unlock(); } } |
However, because the doSomething()
method does not check whether str
is null
, a runtime exception in this component may prevent the lock from being released.It is important that releasing dynamic locks always be executed within an finally
clause in order to work correctly with unexpected or unchecked exceptions.
Compliant Solution
This compliant solution adds a finally
clause block and moves the unlock()
call into it.
Code Block | ||
---|---|---|
| ||
class DateHandler { private 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) { try { lock.lock(); String dateString = date.toString(); if (dateStringstr.equals(strdateString)) { // ... } } finally { lock.unlock(); } } } |
...