Concurrent hash set that allows the lock array to be resized. : HashSet « Collections Data Structure « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JavaFX
25.JDK 6
26.JDK 7
27.JNDI LDAP
28.JPA
29.JSP
30.JSTL
31.Language Basics
32.Network Protocol
33.PDF RTF
34.Reflection
35.Regular Expressions
36.Scripting
37.Security
38.Servlets
39.Spring
40.Swing Components
41.Swing JFC
42.SWT JFace Eclipse
43.Threads
44.Tiny Application
45.Velocity
46.Web Services SOA
47.XML
Java » Collections Data Structure » HashSet 




Concurrent hash set that allows the lock array to be resized.
     
/*
 * RefinableHashSet.java
 *
 * Created on November 15, 2006, 3:59 PM
 *
 * From "The Art of Multiprocessor Programming",
 * by Maurice Herlihy and Nir Shavit.
 *
 * This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.
 * http://i.creativecommons.org/l/by-sa/3.0/us/88x31.png
 */
//package xbird.util.concurrent.set;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicMarkableReference;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Concurrent hash set that allows the lock array to be resized.
 @param <T> type
 @author Maurice Herlihy
 */
public class RefinableHashSet<T> extends BaseHashSet<T> {
    AtomicMarkableReference<Thread> owner;
    volatile ReentrantLock[] locks;

    /**
     * Concurrent Cuckoo hash set. Resizes lock array.
     @param capacity Initial number of buckets.
     */
    public RefinableHashSet(int capacity) {
        super(capacity);
        locks = new ReentrantLock[capacity];
        for(int j = 0; j < capacity; j++) {
            locks[jnew ReentrantLock();
        }
        owner = new AtomicMarkableReference<Thread>(null, false);
    }

    /**
     * Synchronize before adding, removing, or testing for item
     @param x item involved
     */
    @Override
    public void acquire(T x) {
        boolean[] mark = true };
        Thread me = Thread.currentThread();
        Thread who;
        while(true) {
            do // wait until not resizing
                who = owner.get(mark);
            while(mark[0&& who != me);
            ReentrantLock[] oldLocks = this.locks;
            int myBucket = Math.abs(x.hashCode() % oldLocks.length);
            ReentrantLock oldLock = oldLocks[myBucket];
            oldLock.lock()// acquire lock
            who = owner.get(mark);
            if((!mark[0|| who == me&& this.locks == oldLocks) { // recheck
                return;
            else //  unlock & try again
                oldLock.unlock();
            }
        }
    }

    /**
     * synchronize after adding, removing, or testing for item
     @param x item involved
     */
    @Override
    public void release(T x) {
        int myBucket = Math.abs(x.hashCode() % locks.length);
        locks[myBucket].unlock();
    }

    /**
     * Ensure that no thread is currently locking the set.
     */
    protected void quiesce() {
        for(ReentrantLock lock : locks) {
            while(lock.isLocked()) {
            // spin
        }
    }

    /**
     * double the set size
     */
    @Override
    public void resize() {
        int oldCapacity = table.length;
        int newCapacity = * oldCapacity;
        Thread me = Thread.currentThread();
        if(owner.compareAndSet(null, me, false, true)) {
            try {
                if(table.length != oldCapacity) { // someone else resized first
                    return;
                }
                quiesce();
                List<T>[] oldTable = table;
                table = (List<T>[]) new List[newCapacity];
                for(int i = 0; i < newCapacity; i++)
                    table[inew ArrayList<T>();
                locks = new ReentrantLock[newCapacity];
                for(int j = 0; j < locks.length; j++) {
                    locks[jnew ReentrantLock();
                }
                initializeFrom(oldTable);
            finally {
                owner.set(null, false)// restore prior state
            }
        }
    }

    @Override
    public boolean policy() {
        return size / table.length > 4;
    }

    private void initializeFrom(List<T>[] oldTable) {
        for(List<T> bucket : oldTable) {
            for(T x : bucket) {
                int myBucket = Math.abs(x.hashCode() % table.length);
                table[myBucket].add(x);
            }
        }
    }
}


/**
 * Simple fine-grained hash map.
 @param <T> type
 @author Maurice Herlihy
 */
 abstract class BaseHashSet<T> {
    protected List<T>[] table;
    protected int size;

    public BaseHashSet(int capacity) {
        size = 0;
        table = (List<T>[]) new List[capacity];
        for(int i = 0; i < capacity; i++) {
            table[inew ArrayList<T>();
        }
    }

    /**
     * Is item in set?
     @param x item to test
     @return <code>true</code> iff item present
     */
    public boolean contains(T x) {
        acquire(x);
        try {
            int myBucket = Math.abs(x.hashCode() % table.length);
            return table[myBucket].contains(x);
        finally {
            release(x);
        }
    }

    /**
     * Add item to set
     @param x item to add
     @return <code>true</code> iff set changed
     */
    public boolean add(T x) {
        boolean result = false;
        acquire(x);
        try {
            int myBucket = Math.abs(x.hashCode() % table.length);
            result = table[myBucket].add(x);
            size = result ? size + : size;
        finally {
            release(x)// always unlock
        }
        if(policy())
            resize();
        return result;
    }

    /**
     * Remove item from set
     @param x item to remove
     @return <code>true</code> iff set changed
     */
    public boolean remove(T x) {
        acquire(x);
        try {
            int myBucket = Math.abs(x.hashCode() % table.length);
            boolean result = table[myBucket].remove(x);
            size = result ? size - : size;
            return result;
        finally {
            release(x)// always unlock
        }
    }

    /**
     * Synchronize before adding, removing, or testing for item
     @param x item involved
     */
    public abstract void acquire(T x);

    /**
     * synchronize after adding, removing, or testing for item
     @param x item involved
     */
    public abstract void release(T x);

    /**
     * double the set size
     */
    public abstract void resize();

    /**
     * decide whether to resize
     @return whether to resize
     */
    public abstract boolean policy();

}

   
    
    
    
    
  














Related examples in the same category
1.Add values to HashSet
2.HashSet implementation of setHashSet implementation of set
3.Generic collection conversion: HashSet and ArrayList
4.Remove one set from another set
5.Remove element from HashSet
6.Find maximum element of Java HashSet
7.Find Minimum element of Java HashSet
8.Get Enumeration over Java HashSet
9.Get Synchronized Set from Java HashSet
10.Check if a particular element exists in Java HashSet
11.Copy all elements of Java HashSet to an Object Array
12.Get Size of Java HashSet
13.Iterate through elements of Java HashSet
14.Integer value set
15.Listing the Elements of a Collection(iterate over the elements of set or list)
16.Remove specified element from Java HashSet
17.Remove all elements from Java HashSet
18.Convert array to Set
19.Implements a HashSet where the objects given are stored in weak references
20.Convert an ArrayList to HashSet
21.Create an array containing the elements in a set
22.Duplicate elements are discarded
23.Convert Set into array
24.A memory-efficient hash set.
25.Compact HashSet
26.Coarse-grained hash set.
27.A CompactHashSet implements the set interface more tightly in memory and more efficiently than Java's java.util.HashSet.
28.Concurrent HashSet
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.