Skip to content

Commit be4bc7e

Browse files
authored
hated me without a cause
But this happened so that the word may be fulfilled which was written in their law, 'They hated me without a cause.' (John 15:25)
1 parent 5281b66 commit be4bc7e

1 file changed

Lines changed: 70 additions & 0 deletions

File tree

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
2+
//But this happened so that the word may be fulfilled which was written in their law, 'They hated me without a cause.' (John 15:25)
3+
4+
package com.javarush.task.task29.task2908;
5+
6+
import java.util.concurrent.*;
7+
8+
/* Argument and Value are generic types*/
9+
public class CacheComputeManager<Argument, Value> implements Computable<Argument, Value> {
10+
private final ConcurrentHashMap<Argument, Future<Value>> cache = new ConcurrentHashMap<>();
11+
private final Computable<Argument, Value> computable;
12+
13+
public CacheComputeManager(Computable<Argument, Value> computable) {
14+
this.computable = computable;
15+
}
16+
17+
@Override
18+
public Value compute(final Argument arg) throws InterruptedException {
19+
Future<Value> f = cache.get(arg);
20+
if (f == null) {
21+
FutureTask<Value> ft = createFutureTaskForNewArgumentThatHaveToComputeValue(arg);
22+
cache.putIfAbsent(arg, ft);
23+
f = ft;
24+
ft.run();
25+
System.out.print(arg + " will be cached ");
26+
} else {
27+
System.out.print(arg + " taken from cache ");
28+
}
29+
try {
30+
return f.get();
31+
} catch (CancellationException e) {
32+
cache.remove(arg, f);
33+
} catch (ExecutionException e) {
34+
throw new RuntimeException(e.getCause());
35+
}
36+
return null;
37+
}
38+
39+
public FutureTask<Value> createFutureTaskForNewArgumentThatHaveToComputeValue(final Argument arg) {
40+
41+
return new FutureTask<Value>(new Callable<Value>() {
42+
@Override
43+
public Value call() throws Exception {
44+
return computable.compute(arg);
45+
}
46+
});
47+
}
48+
}
49+
50+
/*
51+
Кеширование
52+
53+
В CacheComputeManager реализуй логику пустого метода.
54+
55+
Догадайся, что он должен делать по названию метода и по логике класса.
56+
57+
58+
59+
60+
61+
Требования:
62+
63+
1. Метод createFutureTaskForNewArgumentThatHaveToComputeValue должен создавать и возвращать объект типа FutureTask.
64+
65+
2. В методе createFutureTaskForNewArgumentThatHaveToComputeValue должен создаваться объект анонимного класса, реализующего интерфейс Callable.
66+
67+
3. Внутри метода createFutureTaskForNewArgumentThatHaveToComputeValue должна встречаться строка "return computable.compute(arg);".
68+
69+
4. Программа должна выводить текст указанный в комментариях в классе Solution.
70+
*/

0 commit comments

Comments
 (0)