File: UnsynchronizedOverridesSynchronized.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 (45 lines) | stat: -rw-r--r-- 1,292 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
44
45
Thread-safe methods should never be overridden by methods that are not
thread-safe. Doing so violates behavioural subtyping, and can result in bugs if
the subtype is used in contexts that rely on the thread-safety of the supertype.

Overriding a `synchronized` method with a method that is not `synchronized` can
be a sign that the thread-safety of the supertype is not being preserved.

```java
class Counter {
  private int count = 0;

  synchronized void increment() {
    count++;
  }
}
```

```java
// MyCounter is not thread safe!
class MyCounter extends Counter {
  private int count = 0;

  void increment() {
    count++;
  }
}
```

Note that there are many ways to implement a thread-safe method without using
the `synchronized` modifier (e.g. `synchronized` statements using explicit
locks, or other locking constructs). When overriding a `synchronized` method
with a method that is thread-safe but does not have the `synchronized` modifier,
consider adding `@SuppressWarnings("UnsynchronizedOverridesSynchronized")` and
an explanation.

```java
class MyCounter extends Counter {
  private AtomicInteger count = AtomicInteger();

  @SuppressWarnings("UnsynchronizedOverridesSynchronized") // AtomicInteger is thread-safe
  void increment() {
    count.getAndIncrement();
  }
}
```