您好,登錄后才能下訂單哦!
以下是代碼:
package cn.study.concurrency.ch21; /** * 鎖分段 * @author xiaof * */ public class StripedMap { //同步策略:就是對(duì)數(shù)組進(jìn)行分段上鎖,n個(gè)節(jié)點(diǎn)用n%LOCKS鎖保護(hù) private static final int N_LOCKS = 16; private final Node[] buckets; private final Object[] locks; private static class Node { private String name; private Node next; private String key; private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } } public StripedMap(int numBuckets) { buckets = new Node[numBuckets]; //創(chuàng)建對(duì)應(yīng)hash的鎖 locks = new Object[N_LOCKS]; for(int i = 0; i < N_LOCKS; ++ i) { locks[i] = new Object(); } } private final int hash(Object key) { //取絕對(duì)值 return Math.abs(key.hashCode() % buckets.length); } //get和clear public Object get(Object key) { int hash = hash(key); synchronized(locks[hash % N_LOCKS]) { //分段上鎖 for(Node m = buckets[hash]; m != null; m = m.next) { if(m.key.equals(key)) return m.value; } } return null; } /** * 清除所有的數(shù)據(jù),但是沒有要求說要同時(shí)獲取全部的鎖的話,可以進(jìn)行這樣的釋放操作 */ public void clear() { for(int i = 0; i < buckets.length; ++i) { synchronized(locks[i % N_LOCKS]) { buckets[i] = null; } } } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。