Skip to content

Commit 38d09af

Browse files
committed
chore: Replace synchronized method with locks in SynchronizedCache.
1 parent 9978ddd commit 38d09af

File tree

1 file changed

+45
-12
lines changed

1 file changed

+45
-12
lines changed

src/main/java/io/github/nstdio/http/ext/SynchronizedCache.java

Lines changed: 45 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,38 +19,66 @@
1919
import java.io.IOException;
2020
import java.net.http.HttpRequest;
2121
import java.net.http.HttpResponse;
22+
import java.util.concurrent.locks.Lock;
23+
import java.util.concurrent.locks.ReentrantLock;
2224
import java.util.function.Consumer;
2325

2426
class SynchronizedCache implements Cache {
2527
private final Cache delegate;
28+
private final Lock lock = new ReentrantLock();
2629

2730
SynchronizedCache(Cache delegate) {
2831
this.delegate = delegate;
2932
}
3033

3134
@Override
32-
public synchronized CacheEntry get(HttpRequest request) {
33-
return delegate.get(request);
35+
public CacheEntry get(HttpRequest request) {
36+
lock.lock();
37+
try {
38+
return delegate.get(request);
39+
} finally {
40+
lock.unlock();
41+
}
3442
}
3543

3644
@Override
37-
public synchronized void put(HttpRequest request, CacheEntry entry) {
38-
delegate.put(request, entry);
45+
public void put(HttpRequest request, CacheEntry entry) {
46+
lock.lock();
47+
try {
48+
delegate.put(request, entry);
49+
} finally {
50+
lock.unlock();
51+
}
3952
}
4053

4154
@Override
42-
public synchronized void evict(HttpRequest request) {
43-
delegate.evict(request);
55+
public void evict(HttpRequest request) {
56+
lock.lock();
57+
try {
58+
delegate.evict(request);
59+
} finally {
60+
lock.unlock();
61+
}
4462
}
4563

4664
@Override
47-
public synchronized void evictAll(HttpRequest request) {
48-
delegate.evictAll(request);
65+
public void evictAll(HttpRequest request) {
66+
lock.lock();
67+
try {
68+
delegate.evictAll(request);
69+
} finally {
70+
lock.unlock();
71+
}
4972
}
5073

5174
@Override
52-
public synchronized void evictAll() {
53-
delegate.evictAll();
75+
public void evictAll() {
76+
lock.lock();
77+
try {
78+
delegate.evictAll();
79+
} finally {
80+
lock.unlock();
81+
}
5482
}
5583

5684
@Override
@@ -79,8 +107,13 @@ public Consumer<T> finisher() {
79107
}
80108

81109
@Override
82-
public synchronized void close() throws IOException {
83-
delegate.close();
110+
public void close() throws IOException {
111+
lock.lock();
112+
try {
113+
delegate.close();
114+
} finally {
115+
lock.unlock();
116+
}
84117
}
85118

86119
Cache delegate() {

0 commit comments

Comments
 (0)