Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class StorageClass {
- public static void main(String[] args) {
- Storage storage = new Storage();
- storage.store(1, 4);
- storage.store(2, 4);
- storage.store(3, 2);
- storage.store(4, 2);
- storage.store(4, 3);
- Integer[] matched = storage.getUpdate(3, 2);
- System.out.println(Arrays.toString(matched));
- }
- private static class Storage {
- private ReadWriteLock lock = new ReentrantReadWriteLock();
- private List<Long> storage = new ArrayList<>(1);
- public void store(int ts, int uid) {
- Preconditions.checkArgument(uid > 0);
- Lock lock = this.lock.readLock();
- try {
- lock.lock();
- storage.add(createKey(ts, uid));
- } finally {
- lock.unlock();
- }
- }
- private long createKey(long ts, int uid) {
- return (ts << 32) + uid;
- }
- public Integer[] getUpdate(int ts, int count) {
- final int offset = 2;
- long higher = createKey(ts, Integer.MAX_VALUE);
- long lower = createKey(ts - offset, 0);
- Lock lock = this.lock.writeLock();
- try {
- lock.lock();
- Long[] diff = getDiff(lower, higher);
- Map<Integer, Integer> counters = new ConcurrentHashMap<>();
- List<Integer> res = new ArrayList<>();
- for (long d : diff) {
- counters.compute((int) d, (k, v) -> {
- if (v == null) {
- return 1;
- } else {
- v++;
- }
- if (v == count) {
- res.add(k);
- }
- return ++v;
- });
- }
- return res.toArray(new Integer[]{});
- } finally {
- lock.unlock();
- }
- }
- private Long[] getDiff(long lower, long higher) {
- Long[] arr = storage.toArray(new Long[]{});
- int lowIndex = -Arrays.binarySearch(arr, lower);
- int highIndex = -Arrays.binarySearch(arr, higher);
- int newLength = highIndex - lowIndex;
- Long[] copy = new Long[newLength];
- System.arraycopy(arr, lowIndex, copy, 0, newLength);
- return copy;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement