Thread safety violation High

A thread safety violation might indicate a data race which can put the system into an inconsistent state. A data race occurs when different threads read and write the same field without lock synchronization. Consider synchronizing access to the field through a lock.

Detector ID
java/thread-safety-violation@v1.0
Category

Noncompliant example

1class PropertiesNoncompliant {
2
3    private int parameter = 0;
4
5    public int getParameter() {
6        return parameter;
7    }
8
9    public void setParameter(int number) {
10        parameter = number;
11    }
12}
13
14@ThreadSafe
15class ThreadSafetyViolationNoncompliant {
16    private final PropertiesNoncompliant properties = new PropertiesNoncompliant();
17    private final ReentrantLock lock = new ReentrantLock();
18
19    public void syncReadCallOutsideNoncompliant(int i) {
20        // Noncompliant: violates thread safety by indirectly reading without synchronization.
21        if (properties.getParameter() > i) {
22            lock.lock();
23            properties.setParameter(i);
24            lock.unlock();
25        }
26    }
27}

Compliant example

1class PropertiesCompliant {
2    private int parameter = 0;
3
4    public int getParameter() {
5        return parameter;
6    }
7
8    public void setParameter(int number) {
9        parameter = number;
10    }
11}
12
13@ThreadSafe
14class ThreadSafetyViolationCompliant {
15    private final PropertiesCompliant properties = new PropertiesCompliant();
16    private final ReentrantLock lock = new ReentrantLock();
17
18    public void syncReadCallOutsideCompliant(int i) {
19        // Compliant: follows thread safety by indirectly reading with synchronization.
20        lock.lock();
21        if (properties.getParameter() > i) {
22            properties.setParameter(i);
23        }
24        lock.unlock();
25    }
26}