-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy pathUsingSynchronizedCollections.java
72 lines (65 loc) · 2.09 KB
/
UsingSynchronizedCollections.java
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package br.com.leonardoz.features.collections;
import java.util.Vector;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Synchronized collections synchronizes every public method to encapsulate
* their state.
*
* They're thread-safe, but if you use compound actions like size+add, they'rent
* anymore, because these operations needs to be atomic.
*
* It's required to use client side locking for compound actions.
*
* Synchronized collections doesn't support concurrent iteration+modification.
* They'll throw ConcurrentModificationException
*
*/
public class UsingSynchronizedCollections {
/**
* Use client-side locking to guard compound actions; contains and add are
* synchronized, but this doesn't help when you need to use both in a compounded
* manner.
*
* It's just an easy example to explain the problem, sets are better for this
* than a vector/list.
*/
public static void insertIfAbsent(Vector<Long> list, Long value) {
synchronized (list) {
var contains = list.contains(value);
if (!contains) {
list.add(value);
System.out.println("Value added: " + value);
}
}
}
/**
* You can have duplicates. Try to run multiple times and see the diff in
* results
*/
public static void insertIfAbsentUnsafe(Vector<Long> list, Long value) {
var contains = list.contains(value);
if (!contains) {
list.add(value);
System.out.println("Value added: " + value);
}
}
public static void main(String[] args) throws InterruptedException {
var executor = Executors.newCachedThreadPool();
// Synchronized - Vector
var vector = new Vector<Long>();
Runnable insertIfAbsent = () -> {
long millis = System.currentTimeMillis() / 1000;
insertIfAbsent(vector, millis);
};
for (int i = 0; i < 10001; i++) {
executor.execute(insertIfAbsent);
}
executor.shutdown();
executor.awaitTermination(4000, TimeUnit.SECONDS);
// Using the wrappers for not sync collections
// List<String> synchronizedList = Collections.synchronizedList(abcList);
// Collections.synchronizedMap(m)
// Collections.synchronizedXXX
}
}