[JAVA concurrent programming practice] 9. Lock segmentation and java practice

Source: Internet
Author: User

[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 ;}}}}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.