Advertisement
Guest User

Untitled

a guest
Nov 12th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. public class StorageClass {
  2.  
  3. public static void main(String[] args) {
  4. Storage storage = new Storage();
  5. storage.store(1, 4);
  6. storage.store(2, 4);
  7. storage.store(3, 2);
  8. storage.store(4, 2);
  9. storage.store(4, 3);
  10.  
  11. Integer[] matched = storage.getUpdate(3, 2);
  12. System.out.println(Arrays.toString(matched));
  13. }
  14.  
  15. private static class Storage {
  16.  
  17. private ReadWriteLock lock = new ReentrantReadWriteLock();
  18. private List<Long> storage = new ArrayList<>(1);
  19.  
  20. public void store(int ts, int uid) {
  21. Preconditions.checkArgument(uid > 0);
  22. Lock lock = this.lock.readLock();
  23. try {
  24. lock.lock();
  25. storage.add(createKey(ts, uid));
  26. } finally {
  27. lock.unlock();
  28. }
  29. }
  30.  
  31. private long createKey(long ts, int uid) {
  32. return (ts << 32) + uid;
  33. }
  34.  
  35. public Integer[] getUpdate(int ts, int count) {
  36. final int offset = 2;
  37.  
  38. long higher = createKey(ts, Integer.MAX_VALUE);
  39. long lower = createKey(ts - offset, 0);
  40. Lock lock = this.lock.writeLock();
  41. try {
  42. lock.lock();
  43. Long[] diff = getDiff(lower, higher);
  44. Map<Integer, Integer> counters = new ConcurrentHashMap<>();
  45. List<Integer> res = new ArrayList<>();
  46. for (long d : diff) {
  47. counters.compute((int) d, (k, v) -> {
  48. if (v == null) {
  49. return 1;
  50. } else {
  51. v++;
  52. }
  53.  
  54. if (v == count) {
  55. res.add(k);
  56. }
  57.  
  58. return ++v;
  59. });
  60. }
  61.  
  62. return res.toArray(new Integer[]{});
  63. } finally {
  64. lock.unlock();
  65. }
  66. }
  67.  
  68. private Long[] getDiff(long lower, long higher) {
  69. Long[] arr = storage.toArray(new Long[]{});
  70. int lowIndex = -Arrays.binarySearch(arr, lower);
  71. int highIndex = -Arrays.binarySearch(arr, higher);
  72. int newLength = highIndex - lowIndex;
  73. Long[] copy = new Long[newLength];
  74. System.arraycopy(arr, lowIndex, copy, 0, newLength);
  75. return copy;
  76. }
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement