-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathOptimizedUsage.java
More file actions
41 lines (36 loc) · 1.23 KB
/
Copy pathOptimizedUsage.java
File metadata and controls
41 lines (36 loc) · 1.23 KB
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
package org.alxkm.antipatterns.usingthreadsafecollectionsincorrectly;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
/**
* Another approach is to use a ConcurrentHashMap to achieve atomic check-and-add operations.
* The ConcurrentHashMap provides thread-safe methods, simplifying the code.
*
* In this case, ConcurrentHashMap.newKeySet() creates a thread-safe set backed by a ConcurrentHashMap.
* The add method of this set is atomic, ensuring that the element is added only if it is not already present.
*/
public class OptimizedUsage implements BaseListUsage<String> {
private final Collection<String> set = ConcurrentHashMap.newKeySet();
/**
* Adds a new element to the set if it's not already present.
* This method uses ConcurrentHashMap to ensure thread-safety.
*
* @param element the element to add to the set.
*/
@Override
public void addIfAbsent(String element) {
set.add(element);
}
/**
* Returns the size of the set.
*
* @return the number of elements in the set.
*/
@Override
public int size() {
return set.size();
}
@Override
public Collection<String> getCollection() {
return set;
}
}