File: StaticGuardedByInstance.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 (42 lines) | stat: -rw-r--r-- 1,134 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
Protecting writes to a static field by synchronizing on an instance lock is not
thread-safe.

In the following example, two difference instances of `Test` can each acquire
their own instance lock and call `initialize()` at the same time.

```java
class Test {
  private final Object lock = new Object();
  static initialized = false;
  static void initialize() { /* ... */ }

  Test() {
    synchronized (lock) {
      if (!initialized) {
        initialize();
        // error: modification of static variable guarded by instance variable 'lock'
        initialized = true;
      }
      // ...
    }
  }
}
```

Static fields should generally be guarded by static locks, and instance fields
guarded by instance locks.

The example above could be made thread-safe by locking on the enclosing `Class`:

```java
synchronized (Test.class) {
  if (!initialized) {
    initialize();
    initialized = true;
  }
}
```

To update a static counter from an instance method, consider using
[`AtomicInteger`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html)
instead of incrementing a static `int` field.