Skip to content

Commit

Permalink
chore: Replace synchronized method with locks in SynchronizedCache.
Browse files Browse the repository at this point in the history
  • Loading branch information
nstdio committed Jan 26, 2025
1 parent 9978ddd commit 38d09af
Showing 1 changed file with 45 additions and 12 deletions.
57 changes: 45 additions & 12 deletions src/main/java/io/github/nstdio/http/ext/SynchronizedCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,38 +19,66 @@
import java.io.IOException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;

class SynchronizedCache implements Cache {
private final Cache delegate;
private final Lock lock = new ReentrantLock();

SynchronizedCache(Cache delegate) {
this.delegate = delegate;
}

@Override
public synchronized CacheEntry get(HttpRequest request) {
return delegate.get(request);
public CacheEntry get(HttpRequest request) {
lock.lock();
try {
return delegate.get(request);
} finally {
lock.unlock();
}
}

@Override
public synchronized void put(HttpRequest request, CacheEntry entry) {
delegate.put(request, entry);
public void put(HttpRequest request, CacheEntry entry) {
lock.lock();
try {
delegate.put(request, entry);
} finally {
lock.unlock();
}
}

@Override
public synchronized void evict(HttpRequest request) {
delegate.evict(request);
public void evict(HttpRequest request) {
lock.lock();
try {
delegate.evict(request);
} finally {
lock.unlock();
}
}

@Override
public synchronized void evictAll(HttpRequest request) {
delegate.evictAll(request);
public void evictAll(HttpRequest request) {
lock.lock();
try {
delegate.evictAll(request);
} finally {
lock.unlock();
}
}

@Override
public synchronized void evictAll() {
delegate.evictAll();
public void evictAll() {
lock.lock();
try {
delegate.evictAll();
} finally {
lock.unlock();
}
}

@Override
Expand Down Expand Up @@ -79,8 +107,13 @@ public Consumer<T> finisher() {
}

@Override
public synchronized void close() throws IOException {
delegate.close();
public void close() throws IOException {
lock.lock();
try {
delegate.close();
} finally {
lock.unlock();
}
}

Cache delegate() {
Expand Down

0 comments on commit 38d09af

Please sign in to comment.