Created
October 5, 2017 13:59
-
-
Save esafirm/43ca4f6d28a3133aca93324ee503afa3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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