package com.mac.tarchan.misc;

import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * simple hashset class(hashset synchronized)
 * 
 * @author nori090
 * @param <E> key
 */
public class SimpleConcurrentHashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable {
    private transient ConcurrentHashMap<E, Object> map;

    private static final Object PRESENT = new Object();

    public SimpleConcurrentHashSet() {
        map = new ConcurrentHashMap<E, Object>( 16, .75f );
    }

    @Override
    public Iterator<E> iterator() {
        return map.keySet().iterator();
    }

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public boolean contains( Object o ) {
        return map.contains( o );
    }

    @Override
    public boolean add( E e ) {
        return map.put( e, PRESENT ) == null;
    }

    @Override
    public boolean remove( Object o ) {
        return map.remove( o ) == PRESENT;
    }

    @Override
    public void clear() {
        map.clear();
    }

    /**
     * not support keyset clone();
     */
    @Override
    @SuppressWarnings( "unchecked" )
    protected Object clone()
        throws CloneNotSupportedException {
        SimpleConcurrentHashSet<E> newset = (SimpleConcurrentHashSet<E>) super.clone();
        newset.map = null;
        return newset;
    }
}
