[JAVA concurrent programming practice] 9. Lock segmentation and java practice
Package cn. study. concurrency. ch11;/*** lock segmentation * @ author xiaof **/public class StripedMap {// synchronization policy: locks the array in segments, n nodes use the n % LOCKS lock to protect 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 (Str Ing 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]; // create the lock for the corresponding hash S = new Object [N_LOCKS]; for (int I = 0; I <N_LOCKS; ++ I) {locks [I] = new Object ();}} private final int hash (Object key) {// return Math from the absolute value. abs (key. hashCode () % buckets. length);} // get and clear public Object get (Object key) {int hash = hash (key); synchronized (locks [hash % N_LOCKS]) {// segment lock for (Node m = buckets [hash]; m! = Null; m = m. next) {if (m. key. equals (key) return m. value ;}} return null;}/*** clears all data, but it does not require that all locks be obtained at the same time, you can perform this release operation */public void clear () {for (int I = 0; I <buckets. length; ++ I) {synchronized (locks [I % N_LOCKS]) {buckets [I] = null ;}}}}