File: LockNotBeforeTry.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (43 lines) | stat: -rw-r--r-- 1,029 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
Wherever possible, calls to Lock#lock should be immediately followed by a `try`
block with a `finally` clause which releases the lock,

```java
lock.lock();
try {
  frobnicate();
} finally {
  lock.unlock();
}
```

Placing the call to `lock` *inside* the `try` block is suboptimal. The
documentation for `Lock` allows for `Lock#lock` to throw an unchecked exception
if, for example, it determines that the program will deadlock. In this
situation, `#unlock` will be called even if `#lock` throws,

```java
try {
  lock.lock();
  frobnicate();
} finally {
  lock.unlock();
}
```

Doing work between the `lock` invocation and the start of the `try` block is
potentially very bad, as the lock will go unreleased if the intermediate work
throws,

```java
lock.lock();
checkState(frobnicator.ready());
try {
  frobnicator.frobnicate();
} finally {
  lock.unlock();
}
```

`frobnicator.ready()` should either be moved before the `#lock` call or inside
the `try` block, depending on whether the lock must be acquired before calling
it.