溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

java并發(fā)分段鎖實(shí)踐代碼

發(fā)布時(shí)間:2020-09-22 01:50:17 來源:腳本之家 閱讀:110 作者:cutter_point 欄目:編程語言

以下是代碼:

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í)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(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)容。

AI