Created
November 18, 2018 17:05
-
-
Save Shtaba09/703e1abe44184a775f9fcc1bfe175eab to your computer and use it in GitHub Desktop.
Конструкция распределения локов между обьектами . Тема про то как работает HashMap
This file contains 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
package com.javarush.task.task26.task2609; | |
/* | |
Распределение элементов по корзинам с собственным локом | |
*/ | |
public class Solution { | |
private static final int NUMBER_LOCKS = 12; | |
private final Node[] buckets; | |
private final Object[] locks; | |
static class Node { | |
public Node next; | |
public Object key; | |
public Object value; | |
} | |
public Solution(int numberBuckets) { | |
buckets = new Node[numberBuckets]; | |
locks = new Object[NUMBER_LOCKS]; | |
for (int i = 0; i < NUMBER_LOCKS; i++) { | |
locks[i] = new Object(); | |
} | |
} | |
private final int hash(Object key) { | |
return Math.abs(key.hashCode() % buckets.length); | |
} | |
public Object get(Object key) { | |
int hash = hash(key); | |
synchronized (locks[hash%NUMBER_LOCKS]) { | |
for (Node m = buckets[hash]; m != null; m = m.next) { | |
if (m.key.equals(key)) return m.value; | |
} | |
} | |
return null; | |
} | |
public void clear() { | |
for (int i = 0; i < buckets.length; i++) { | |
synchronized (locks[i%NUMBER_LOCKS]) { | |
buckets[i] = null; | |
} | |
} | |
} | |
public static void main(String[] args) { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment