Guest User

Untitled

a guest
Nov 18th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. package com.javarush.task.task26.task2609;
  2.  
  3. /*
  4. Распределение элементов по корзинам с собственным локом
  5. */
  6. public class Solution {
  7. private static final int NUMBER_LOCKS = 12;
  8. private final Node[] buckets;
  9. private final Object[] locks;
  10.  
  11. static class Node {
  12. public Node next;
  13. public Object key;
  14. public Object value;
  15. }
  16.  
  17. public Solution(int numberBuckets) {
  18. buckets = new Node[numberBuckets];
  19. locks = new Object[NUMBER_LOCKS];
  20. for (int i = 0; i < NUMBER_LOCKS; i++) {
  21. locks[i] = new Object();
  22. }
  23. }
  24.  
  25. private final int hash(Object key) {
  26. return Math.abs(key.hashCode() % buckets.length);
  27. }
  28.  
  29. public Object get(Object key) {
  30. int hash = hash(key);
  31. synchronized (locks[hash%NUMBER_LOCKS]) {
  32. for (Node m = buckets[hash]; m != null; m = m.next) {
  33. if (m.key.equals(key)) return m.value;
  34. }
  35. }
  36. return null;
  37. }
  38.  
  39. public void clear() {
  40. for (int i = 0; i < buckets.length; i++) {
  41. synchronized (locks[i%NUMBER_LOCKS]) {
  42. buckets[i] = null;
  43. }
  44. }
  45. }
  46.  
  47. public static void main(String[] args) {
  48.  
  49. }
  50. }
Add Comment
Please, Sign In to add comment