All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gs.collections.impl.set.mutable.MultiReaderUnifiedSet Maven / Gradle / Ivy

Go to download

GS Collections is a collections framework for Java. It has JDK-compatible List, Set and Map implementations with a rich API and set of utility classes that work with any JDK compatible Collections, Arrays, Maps or Strings. The iteration protocol was inspired by the Smalltalk collection framework.

There is a newer version: 7.0.3
Show newest version
/*
 * Copyright 2015 Goldman Sachs.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.gs.collections.impl.set.mutable;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Iterator;
import java.util.RandomAccess;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import com.gs.collections.api.LazyIterable;
import com.gs.collections.api.RichIterable;
import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.function.Function2;
import com.gs.collections.api.block.function.primitive.BooleanFunction;
import com.gs.collections.api.block.function.primitive.ByteFunction;
import com.gs.collections.api.block.function.primitive.CharFunction;
import com.gs.collections.api.block.function.primitive.DoubleFunction;
import com.gs.collections.api.block.function.primitive.FloatFunction;
import com.gs.collections.api.block.function.primitive.IntFunction;
import com.gs.collections.api.block.function.primitive.LongFunction;
import com.gs.collections.api.block.function.primitive.ShortFunction;
import com.gs.collections.api.block.predicate.Predicate;
import com.gs.collections.api.block.predicate.Predicate2;
import com.gs.collections.api.block.procedure.Procedure;
import com.gs.collections.api.collection.primitive.MutableBooleanCollection;
import com.gs.collections.api.collection.primitive.MutableByteCollection;
import com.gs.collections.api.collection.primitive.MutableCharCollection;
import com.gs.collections.api.collection.primitive.MutableDoubleCollection;
import com.gs.collections.api.collection.primitive.MutableFloatCollection;
import com.gs.collections.api.collection.primitive.MutableIntCollection;
import com.gs.collections.api.collection.primitive.MutableLongCollection;
import com.gs.collections.api.collection.primitive.MutableShortCollection;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.map.MutableMap;
import com.gs.collections.api.multimap.set.MutableSetMultimap;
import com.gs.collections.api.ordered.OrderedIterable;
import com.gs.collections.api.partition.set.PartitionMutableSet;
import com.gs.collections.api.set.ImmutableSet;
import com.gs.collections.api.set.MutableSet;
import com.gs.collections.api.set.ParallelUnsortedSetIterable;
import com.gs.collections.api.set.SetIterable;
import com.gs.collections.api.set.UnsortedSetIterable;
import com.gs.collections.api.set.primitive.MutableBooleanSet;
import com.gs.collections.api.set.primitive.MutableByteSet;
import com.gs.collections.api.set.primitive.MutableCharSet;
import com.gs.collections.api.set.primitive.MutableDoubleSet;
import com.gs.collections.api.set.primitive.MutableFloatSet;
import com.gs.collections.api.set.primitive.MutableIntSet;
import com.gs.collections.api.set.primitive.MutableLongSet;
import com.gs.collections.api.set.primitive.MutableShortSet;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.impl.collection.mutable.AbstractMultiReaderMutableCollection;
import com.gs.collections.impl.factory.Sets;
import com.gs.collections.impl.lazy.parallel.set.MultiReaderParallelUnsortedSetIterable;
import com.gs.collections.impl.utility.LazyIterate;

import static com.gs.collections.impl.factory.Iterables.*;

/**
 * MultiReadUnifiedSet provides a thread-safe wrapper around a UnifiedSet, using a ReentrantReadWriteLock.  In order to
 * provide true thread-safety, MultiReaderFastList does not implement iterator() as all this method requires an external
 * lock to be taken to provide thread-safe iteration.  You can use an iterator() if you use the
 * withReadLockAndDelegate() or withWriteLockAndDelegate() methods.  Both of these methods take a parameter of type
 * Procedure, and a wrapped version of the underlying Unified is returned.  This wrapper guarantees that no
 * external pointer can ever reference the underlying UnifiedSet outside of a locked procedure.  In the case of the read
 * lock method, an Unmodifiable version of the collection is offered, which will throw UnsupportedOperationExceptions on
 * any write methods like add or remove.
 */
public final class MultiReaderUnifiedSet
        extends AbstractMultiReaderMutableCollection
        implements RandomAccess, Externalizable, MutableSet
{
    private static final long serialVersionUID = 1L;

    private transient ReadWriteLock lock;
    private MutableSet delegate;

    /**
     * @deprecated Empty default constructor used for serialization.
     */
    @SuppressWarnings("UnusedDeclaration")
    @Deprecated
    public MultiReaderUnifiedSet()
    {
        // For Externalizable use only
    }

    private MultiReaderUnifiedSet(MutableSet newDelegate)
    {
        this(newDelegate, new ReentrantReadWriteLock());
    }

    private MultiReaderUnifiedSet(MutableSet newDelegate, ReadWriteLock newLock)
    {
        this.lock = newLock;
        this.delegate = newDelegate;
    }

    public static  MultiReaderUnifiedSet newSet()
    {
        return new MultiReaderUnifiedSet(UnifiedSet.newSet());
    }

    public static  MultiReaderUnifiedSet newSet(int capacity)
    {
        return new MultiReaderUnifiedSet(UnifiedSet.newSet(capacity));
    }

    public static  MultiReaderUnifiedSet newSet(Iterable iterable)
    {
        return new MultiReaderUnifiedSet(UnifiedSet.newSet(iterable));
    }

    public static  MultiReaderUnifiedSet newSetWith(T... elements)
    {
        return new MultiReaderUnifiedSet(UnifiedSet.newSetWith(elements));
    }

    @Override
    protected MutableSet getDelegate()
    {
        return this.delegate;
    }

    @Override
    protected ReadWriteLock getLock()
    {
        return this.lock;
    }

    // Exposed for testing

    UntouchableMutableSet asReadUntouchable()
    {
        return new UntouchableMutableSet(this.delegate.asUnmodifiable());
    }

    // Exposed for testing

    UntouchableMutableSet asWriteUntouchable()
    {
        return new UntouchableMutableSet(this.delegate);
    }

    public void withReadLockAndDelegate(Procedure> procedure)
    {
        this.acquireReadLock();
        try
        {
            UntouchableMutableSet untouchableSet = this.asReadUntouchable();
            procedure.value(untouchableSet);
            untouchableSet.becomeUseless();
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public void withWriteLockAndDelegate(Procedure> procedure)
    {
        this.acquireWriteLock();
        try
        {
            UntouchableMutableSet untouchableSet = this.asWriteUntouchable();
            procedure.value(untouchableSet);
            untouchableSet.becomeUseless();
        }
        finally
        {
            this.unlockWriteLock();
        }
    }

    public MutableSet asSynchronized()
    {
        this.acquireReadLock();
        try
        {
            return SynchronizedMutableSet.of(this);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public ImmutableSet toImmutable()
    {
        this.acquireReadLock();
        try
        {
            return Sets.immutable.withAll(this.delegate);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public MutableSet asUnmodifiable()
    {
        this.acquireReadLock();
        try
        {
            return UnmodifiableMutableSet.of(this);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    @Override
    public MutableSet clone()
    {
        this.acquireReadLock();
        try
        {
            return new MultiReaderUnifiedSet(this.delegate.clone());
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public  MutableSet collect(Function function)
    {
        this.acquireReadLock();
        try
        {
            return this.delegate.collect(function);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public MutableBooleanSet collectBoolean(BooleanFunction booleanFunction)
    {
        this.acquireReadLock();
        try
        {
            return this.delegate.collectBoolean(booleanFunction);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public MutableByteSet collectByte(ByteFunction byteFunction)
    {
        this.acquireReadLock();
        try
        {
            return this.delegate.collectByte(byteFunction);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public MutableCharSet collectChar(CharFunction charFunction)
    {
        this.acquireReadLock();
        try
        {
            return this.delegate.collectChar(charFunction);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public MutableDoubleSet collectDouble(DoubleFunction doubleFunction)
    {
        this.acquireReadLock();
        try
        {
            return this.delegate.collectDouble(doubleFunction);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public MutableFloatSet collectFloat(FloatFunction floatFunction)
    {
        this.acquireReadLock();
        try
        {
            return this.delegate.collectFloat(floatFunction);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public MutableIntSet collectInt(IntFunction intFunction)
    {
        this.acquireReadLock();
        try
        {
            return this.delegate.collectInt(intFunction);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public MutableLongSet collectLong(LongFunction longFunction)
    {
        this.acquireReadLock();
        try
        {
            return this.delegate.collectLong(longFunction);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public MutableShortSet collectShort(ShortFunction shortFunction)
    {
        this.acquireReadLock();
        try
        {
            return this.delegate.collectShort(shortFunction);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public  MutableSet flatCollect(Function> function)
    {
        this.acquireReadLock();
        try
        {
            return this.delegate.flatCollect(function);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public  MutableSet collectIf(
            Predicate predicate,
            Function function)
    {
        this.acquireReadLock();
        try
        {
            return this.delegate.collectIf(predicate, function);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public  MutableSet collectWith(
            Function2 function,
            P parameter)
    {
        this.acquireReadLock();
        try
        {
            return this.delegate.collectWith(function, parameter);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public MutableSet newEmpty()
    {
        return MultiReaderUnifiedSet.newSet();
    }

    public MutableSet reject(Predicate predicate)
    {
        this.acquireReadLock();
        try
        {
            return this.delegate.reject(predicate);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public 

MutableSet rejectWith( Predicate2 predicate, P parameter) { this.acquireReadLock(); try { return this.delegate.rejectWith(predicate, parameter); } finally { this.unlockReadLock(); } } public MutableSet tap(Procedure procedure) { this.acquireReadLock(); try { this.forEach(procedure); return this; } finally { this.unlockReadLock(); } } public MutableSet select(Predicate predicate) { this.acquireReadLock(); try { return this.delegate.select(predicate); } finally { this.unlockReadLock(); } } public

MutableSet selectWith( Predicate2 predicate, P parameter) { this.acquireReadLock(); try { return this.delegate.selectWith(predicate, parameter); } finally { this.unlockReadLock(); } } public PartitionMutableSet partition(Predicate predicate) { this.acquireReadLock(); try { return this.delegate.partition(predicate); } finally { this.unlockReadLock(); } } public

PartitionMutableSet partitionWith(Predicate2 predicate, P parameter) { this.acquireReadLock(); try { return this.delegate.partitionWith(predicate, parameter); } finally { this.unlockReadLock(); } } public MutableSet selectInstancesOf(Class clazz) { this.acquireReadLock(); try { return this.delegate.selectInstancesOf(clazz); } finally { this.unlockReadLock(); } } public MutableSet with(T element) { this.add(element); return this; } public MutableSet without(T element) { this.remove(element); return this; } public MutableSet withAll(Iterable elements) { this.addAllIterable(elements); return this; } public MutableSet withoutAll(Iterable elements) { this.removeAllIterable(elements); return this; } @Override public boolean equals(Object o) { this.acquireReadLock(); try { return this.delegate.equals(o); } finally { this.unlockReadLock(); } } @Override public int hashCode() { this.acquireReadLock(); try { return this.delegate.hashCode(); } finally { this.unlockReadLock(); } } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(this.delegate); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.delegate = (MutableSet) in.readObject(); this.lock = new ReentrantReadWriteLock(); } // Exposed for testing static final class UntouchableMutableSet extends UntouchableMutableCollection implements MutableSet { private final MutableList> requestedIterators = mList(); private UntouchableMutableSet(MutableSet newDelegate) { this.delegate = newDelegate; } public void becomeUseless() { this.delegate = null; this.requestedIterators.forEach(new Procedure>() { public void value(UntouchableIterator each) { each.becomeUseless(); } }); } /** * This must be implemented this way to guarantee a reference to the delegate doesn't escape. */ public MutableSet with(T element) { this.add(element); return this; } public MutableSet without(T element) { this.remove(element); return this; } public MutableSet withAll(Iterable elements) { this.addAllIterable(elements); return this; } public MutableSet withoutAll(Iterable elements) { this.removeAllIterable(elements); return this; } public MutableSet asSynchronized() { throw new UnsupportedOperationException("Cannot call asSynchronized() on " + this.getClass().getSimpleName()); } public MutableSet asUnmodifiable() { throw new UnsupportedOperationException("Cannot call asUnmodifiable() on " + this.getClass().getSimpleName()); } public ImmutableSet toImmutable() { return Sets.immutable.withAll(this.getDelegate()); } public LazyIterable asLazy() { return LazyIterate.adapt(this); } @Override public MutableSet clone() { return this.getDelegate().clone(); } public MutableSet collect(Function function) { return this.getDelegate().collect(function); } public MutableBooleanSet collectBoolean(BooleanFunction booleanFunction) { return this.getDelegate().collectBoolean(booleanFunction); } public R collectBoolean(BooleanFunction booleanFunction, R target) { return this.getDelegate().collectBoolean(booleanFunction, target); } public MutableByteSet collectByte(ByteFunction byteFunction) { return this.getDelegate().collectByte(byteFunction); } public R collectByte(ByteFunction byteFunction, R target) { return this.getDelegate().collectByte(byteFunction, target); } public MutableCharSet collectChar(CharFunction charFunction) { return this.getDelegate().collectChar(charFunction); } public R collectChar(CharFunction charFunction, R target) { return this.getDelegate().collectChar(charFunction, target); } public MutableDoubleSet collectDouble(DoubleFunction doubleFunction) { return this.getDelegate().collectDouble(doubleFunction); } public R collectDouble(DoubleFunction doubleFunction, R target) { return this.getDelegate().collectDouble(doubleFunction, target); } public MutableFloatSet collectFloat(FloatFunction floatFunction) { return this.getDelegate().collectFloat(floatFunction); } public R collectFloat(FloatFunction floatFunction, R target) { return this.getDelegate().collectFloat(floatFunction, target); } public MutableIntSet collectInt(IntFunction intFunction) { return this.getDelegate().collectInt(intFunction); } public R collectInt(IntFunction intFunction, R target) { return this.getDelegate().collectInt(intFunction, target); } public MutableLongSet collectLong(LongFunction longFunction) { return this.getDelegate().collectLong(longFunction); } public R collectLong(LongFunction longFunction, R target) { return this.getDelegate().collectLong(longFunction, target); } public MutableShortSet collectShort(ShortFunction shortFunction) { return this.getDelegate().collectShort(shortFunction); } public R collectShort(ShortFunction shortFunction, R target) { return this.getDelegate().collectShort(shortFunction, target); } public MutableSet flatCollect(Function> function) { return this.getDelegate().flatCollect(function); } public MutableSet collectIf( Predicate predicate, Function function) { return this.getDelegate().collectIf(predicate, function); } public MutableSet collectWith( Function2 function, P parameter) { return this.getDelegate().collectWith(function, parameter); } public MutableSetMultimap groupBy( Function function) { return this.getDelegate().groupBy(function); } public MutableSetMultimap groupByEach( Function> function) { return this.getDelegate().groupByEach(function); } public MutableMap groupByUniqueKey(Function function) { return this.getDelegate().groupByUniqueKey(function); } public MutableSet newEmpty() { return this.getDelegate().newEmpty(); } public MutableSet reject(Predicate predicate) { return this.getDelegate().reject(predicate); } public

MutableSet rejectWith( Predicate2 predicate, P parameter) { return this.getDelegate().rejectWith(predicate, parameter); } public MutableSet tap(Procedure procedure) { this.forEach(procedure); return this; } public MutableSet select(Predicate predicate) { return this.getDelegate().select(predicate); } public

MutableSet selectWith( Predicate2 predicate, P parameter) { return this.getDelegate().selectWith(predicate, parameter); } public PartitionMutableSet partition(Predicate predicate) { return this.getDelegate().partition(predicate); } public

PartitionMutableSet partitionWith(Predicate2 predicate, P parameter) { return this.getDelegate().partitionWith(predicate, parameter); } public MutableSet selectInstancesOf(Class clazz) { return this.getDelegate().selectInstancesOf(clazz); } public Iterator iterator() { UntouchableIterator iterator = new UntouchableIterator(this.delegate.iterator()); this.requestedIterators.add(iterator); return iterator; } /** * @deprecated in 6.0. Use {@link OrderedIterable#zip(Iterable)} instead. */ @Deprecated public MutableSet> zip(Iterable that) { return this.getDelegate().zip(that); } /** * @deprecated in 6.0. Use {@link OrderedIterable#zipWithIndex()} instead. */ @Deprecated public MutableSet> zipWithIndex() { return this.getDelegate().zipWithIndex(); } public MutableSet union(SetIterable set) { return this.getDelegate().union(set); } public > R unionInto(SetIterable set, R targetSet) { return this.getDelegate().unionInto(set, targetSet); } public MutableSet intersect(SetIterable set) { return this.getDelegate().intersect(set); } public > R intersectInto(SetIterable set, R targetSet) { return this.getDelegate().intersectInto(set, targetSet); } public MutableSet difference(SetIterable subtrahendSet) { return this.getDelegate().difference(subtrahendSet); } public > R differenceInto(SetIterable subtrahendSet, R targetSet) { return this.getDelegate().differenceInto(subtrahendSet, targetSet); } public MutableSet symmetricDifference(SetIterable setB) { return this.getDelegate().symmetricDifference(setB); } public > R symmetricDifferenceInto(SetIterable set, R targetSet) { return this.getDelegate().symmetricDifferenceInto(set, targetSet); } public boolean isSubsetOf(SetIterable candidateSuperset) { return this.getDelegate().isSubsetOf(candidateSuperset); } public boolean isProperSubsetOf(SetIterable candidateSuperset) { return this.getDelegate().isProperSubsetOf(candidateSuperset); } public MutableSet> powerSet() { return this.getDelegate().powerSet(); } public LazyIterable> cartesianProduct(SetIterable set) { return this.getDelegate().cartesianProduct(set); } public ParallelUnsortedSetIterable asParallel(ExecutorService executorService, int batchSize) { return this.getDelegate().asParallel(executorService, batchSize); } private MutableSet getDelegate() { return (MutableSet) this.delegate; } } private static final class UntouchableIterator implements Iterator { private Iterator delegate; private UntouchableIterator(Iterator newDelegate) { this.delegate = newDelegate; } public boolean hasNext() { return this.delegate.hasNext(); } public T next() { return this.delegate.next(); } public void remove() { this.delegate.remove(); } public void becomeUseless() { this.delegate = null; } } public MutableSetMultimap groupBy(Function function) { this.acquireReadLock(); try { return this.delegate.groupBy(function); } finally { this.unlockReadLock(); } } public MutableSetMultimap groupByEach(Function> function) { this.acquireReadLock(); try { return this.delegate.groupByEach(function); } finally { this.unlockReadLock(); } } public MutableMap groupByUniqueKey(Function function) { this.acquireReadLock(); try { return this.delegate.groupByUniqueKey(function); } finally { this.unlockReadLock(); } } /** * @deprecated in 6.0. Use {@link OrderedIterable#zip(Iterable)} instead. */ @Deprecated public MutableSet> zip(Iterable that) { this.acquireReadLock(); try { return this.delegate.zip(that); } finally { this.unlockReadLock(); } } /** * @deprecated in 6.0. Use {@link OrderedIterable#zipWithIndex()} instead. */ @Deprecated public MutableSet> zipWithIndex() { this.acquireReadLock(); try { return this.delegate.zipWithIndex(); } finally { this.unlockReadLock(); } } public RichIterable> chunk(int size) { this.acquireReadLock(); try { return this.delegate.chunk(size); } finally { this.unlockReadLock(); } } public MutableSet union(SetIterable set) { this.acquireReadLock(); try { return this.delegate.union(set); } finally { this.unlockReadLock(); } } public > R unionInto(SetIterable set, R targetSet) { this.acquireReadLock(); try { return this.delegate.unionInto(set, targetSet); } finally { this.unlockReadLock(); } } public MutableSet intersect(SetIterable set) { this.acquireReadLock(); try { return this.delegate.intersect(set); } finally { this.unlockReadLock(); } } public > R intersectInto(SetIterable set, R targetSet) { this.acquireReadLock(); try { return this.delegate.intersectInto(set, targetSet); } finally { this.unlockReadLock(); } } public MutableSet difference(SetIterable subtrahendSet) { this.acquireReadLock(); try { return this.delegate.difference(subtrahendSet); } finally { this.unlockReadLock(); } } public > R differenceInto(SetIterable subtrahendSet, R targetSet) { this.acquireReadLock(); try { return this.delegate.differenceInto(subtrahendSet, targetSet); } finally { this.unlockReadLock(); } } public MutableSet symmetricDifference(SetIterable setB) { this.acquireReadLock(); try { return this.delegate.symmetricDifference(setB); } finally { this.unlockReadLock(); } } public > R symmetricDifferenceInto(SetIterable set, R targetSet) { this.acquireReadLock(); try { return this.delegate.symmetricDifferenceInto(set, targetSet); } finally { this.unlockReadLock(); } } public boolean isSubsetOf(SetIterable candidateSuperset) { this.acquireReadLock(); try { return this.delegate.isSubsetOf(candidateSuperset); } finally { this.unlockReadLock(); } } public boolean isProperSubsetOf(SetIterable candidateSuperset) { this.acquireReadLock(); try { return this.delegate.isProperSubsetOf(candidateSuperset); } finally { this.unlockReadLock(); } } public MutableSet> powerSet() { this.acquireReadLock(); try { return this.delegate.powerSet(); } finally { this.unlockReadLock(); } } public LazyIterable> cartesianProduct(SetIterable set) { this.acquireReadLock(); try { return this.delegate.cartesianProduct(set); } finally { this.unlockReadLock(); } } public ParallelUnsortedSetIterable asParallel(ExecutorService executorService, int batchSize) { return new MultiReaderParallelUnsortedSetIterable(this.delegate.asParallel(executorService, batchSize), this.lock); } }