-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathCustomCache.java
43 lines (38 loc) · 1.3 KB
/
CustomCache.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
package by.andd3dfx.multithreading;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
/**
* Реализовать без использования конкурентных коллекций класс с 2 методами:
* <pre>
* public class CustomCache {
* // Его вызывает большое кол-во конкурентных потоков
* public Object read(int idx) {
* //...
* }
*
* // Его вызывает один поток
* public void write(int idx, Object object) {
* //...
* }
* }
* </pre>
* Известно, что кол-во разных объектов в кеше - небольшое, не более 1000
*/
public class CustomCache {
private final List<AtomicReference> storage = new ArrayList<>() {{
for (int i = 0; i < 1000; i++) {
add(new AtomicReference());
}
}};
public Object read(int idx) {
return storage.get(idx).get();
}
public void write(int idx, Object object) {
boolean result;
do {
Object oldValue = storage.get(idx).get();
result = storage.get(idx).compareAndSet(oldValue, object);
} while (!result);
}
}