Improper use of classes that aren't thread-safe Medium

Improper use of classes that are not thread-safe in multi-threaded programs can make the programs unstable. Unsafe thread violations cause race conditions that can cause systems to crash or produce unpredictable results.

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

Noncompliant example

1@ThreadSafe
2public class ThreadSafetyClassViolationsNoncompliant {
3
4    private HashMap<String, FileInfo> fileInfoMap = new HashMap<String, FileInfo>();
5
6    public synchronized void reset() {
7        fileInfoMap.clear();
8    }
9
10    public synchronized void addFileInfo(String fileName, long fileSize) {
11        FileInfo fileInfo = new FileInfo(fileName, fileSize);
12        fileInfoMap.put(fileName, fileInfo);
13    }
14
15    // Noncompliant: the method doesn't protect the parallel use of map.
16    public FileInfo getFileInfo(String fileName) {
17        return fileInfoMap.get(fileName);
18    }
19
20    public synchronized FileInfo getFileInfoSync(String fileName) {
21        return fileInfoMap.get(fileName);
22    }
23}

Compliant example

1@ThreadSafe
2public class ThreadSafetyClassViolationsCompliant {
3
4    private HashMap<String, FileInfo> fileInfoMap = new HashMap<String, FileInfo>();
5
6    // Compliant: all methods are thread-safe.
7
8    public synchronized void reset() {
9        fileInfoMap.clear();
10    }
11
12    public synchronized void addFileInfo(String fileName, long fileSize) {
13        FileInfo fileInfo = new FileInfo(fileName, fileSize);
14        fileInfoMap.put(fileName, fileInfo);
15    }
16
17    public synchronized FileInfo getFileInfoSync(String fileName) {
18        return fileInfoMap.get(fileName);
19    }
20}