Oversynchronization Low

Oversynchronization with ConcurrentHashMap or ConcurrentLinkedQueue can reduce program performance. An oversynchronization happens when unnecessary synchronization is used that prevents parallel execution.

Detector ID
java/concurrency-over-synchronization@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

1public String putIfAbsentNoncompliant(ConcurrentHashMap<String, String> concurrentMap, String key) {
2    String sampleValue = "sampleString";
3    // Noncompliant: this is less efficient and more error-prone than using putIfAbsent.
4    synchronized(this) {
5        String value = concurrentMap.get(key);
6        if (value == null) {
7            concurrentMap.put(key, sampleValue);
8        }
9        return key;
10    }
11}

Compliant example

1public String putIfAbsentCompliant(ConcurrentHashMap<String, String> concurrentMap, String key) {
2    String sampleValue = "sampleString";
3    // Compliant: uses putIfAbsent instead of manual synchronization.
4    concurrentMap.putIfAbsent(key, sampleValue);
5    return key;
6}