Skip to content

Instantly share code, notes, and snippets.

@esafirm
Created October 5, 2017 13:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save esafirm/43ca4f6d28a3133aca93324ee503afa3 to your computer and use it in GitHub Desktop.
Save esafirm/43ca4f6d28a3133aca93324ee503afa3 to your computer and use it in GitHub Desktop.
public class LruStorage extends LinkedHashMap<String, byte[]>
implements KV.Storage {
private final ExecutorService mService = Executors.newSingleThreadExecutor();
private final KV.Storage mStorage;
private final int mMaxSize;
public LruStorage(KV.Storage storage, int size) {
super(size/2, 0.75f, true);
mStorage = storage;
mMaxSize = size;
}
public void set(final String key, final byte[] value) {
if (value == null) {
this.remove(key);
} else {
this.put(key, value);
}
mService.submit(new Callable<Void>() {
public Void call() {
mStorage.set(key, value);
return null;
}
});
}
public byte[] get(final String key) {
byte[] value = super.get(key);
if (value == null) {
value = wait(new Callable<byte[]>() {
public byte[] call() {
byte[] b = mStorage.get(key);
put(key, b);
return b;
}
});
}
return value;
}
public Set<String> keys(final String mask) {
return wait(new Callable<Set<String>>() {
public Set<String> call() {
return mStorage.keys(mask);
}
});
}
public void close() {
wait(new Callable<Void>() {
public Void call() {
mStorage.close();
return null;
}
});
mService.shutdown();
}
protected boolean removeEldestEntry(Map.Entry<String, byte[]> eldest) {
return size() > mMaxSize;
}
private <T> T wait(Callable<T> c) {
try {
return mService.submit(c).get();
} catch (InterruptedException|ExecutionException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment