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

com.gs.collections.impl.bag.mutable.MultiReaderHashBag 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 2014 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.bag.mutable;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Iterator;
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.bag.ImmutableBag;
import com.gs.collections.api.bag.MutableBag;
import com.gs.collections.api.bag.primitive.MutableBooleanBag;
import com.gs.collections.api.bag.primitive.MutableByteBag;
import com.gs.collections.api.bag.primitive.MutableCharBag;
import com.gs.collections.api.bag.primitive.MutableDoubleBag;
import com.gs.collections.api.bag.primitive.MutableFloatBag;
import com.gs.collections.api.bag.primitive.MutableIntBag;
import com.gs.collections.api.bag.primitive.MutableLongBag;
import com.gs.collections.api.bag.primitive.MutableShortBag;
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.predicate.primitive.IntPredicate;
import com.gs.collections.api.block.procedure.Procedure;
import com.gs.collections.api.block.procedure.primitive.ObjectIntProcedure;
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.MapIterable;
import com.gs.collections.api.map.MutableMap;
import com.gs.collections.api.multimap.bag.MutableBagMultimap;
import com.gs.collections.api.partition.bag.PartitionMutableBag;
import com.gs.collections.api.set.MutableSet;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.impl.collection.mutable.AbstractMultiReaderMutableCollection;
import com.gs.collections.impl.factory.Bags;
import com.gs.collections.impl.factory.Iterables;
import com.gs.collections.impl.utility.LazyIterate;

/**
 * MultiReaderHashBag provides a thread-safe wrapper around a HashBag, using a ReentrantReadWriteLock. In order to
 * provide true thread-safety, MultiReaderHashBag does not implement iterator() as this method requires an external lock
 * to be taken to provide thread-safe iteration. All of these methods are available however, 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 HashBag is returned. This wrapper guarantees that
 * no external pointer can ever reference the underlying HashBag 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 MultiReaderHashBag
        extends AbstractMultiReaderMutableCollection
        implements Externalizable, MutableBag
{
    private static final long serialVersionUID = 1L;

    private transient ReadWriteLock lock;
    private MutableBag delegate;

    @SuppressWarnings("UnusedDeclaration")
    public MultiReaderHashBag()
    {
        // For Externalizable use only
    }

    private MultiReaderHashBag(MutableBag newDelegate)
    {
        this(newDelegate, new ReentrantReadWriteLock());
    }

    private MultiReaderHashBag(MutableBag newDelegate, ReadWriteLock newLock)
    {
        this.lock = newLock;
        this.delegate = newDelegate;
    }

    public static  MultiReaderHashBag newBag()
    {
        return new MultiReaderHashBag(HashBag.newBag());
    }

    public static  MultiReaderHashBag newBag(int capacity)
    {
        return new MultiReaderHashBag(HashBag.newBag(capacity));
    }

    public static  MultiReaderHashBag newBag(Iterable iterable)
    {
        return new MultiReaderHashBag(HashBag.newBag(iterable));
    }

    public static  MultiReaderHashBag newBagWith(T... elements)
    {
        return new MultiReaderHashBag(HashBag.newBagWith(elements));
    }

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

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

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

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

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

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

    public MutableBag asSynchronized()
    {
        this.acquireReadLock();
        try
        {
            return SynchronizedBag.of(this);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public MutableBag asUnmodifiable()
    {
        this.acquireReadLock();
        try
        {
            return UnmodifiableBag.of(this);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public ImmutableBag toImmutable()
    {
        this.acquireReadLock();
        try
        {
            return Bags.immutable.ofAll(this.delegate);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public void addOccurrences(T item, int occurrences)
    {
        this.acquireWriteLock();
        try
        {
            this.delegate.addOccurrences(item, occurrences);
        }
        finally
        {
            this.unlockWriteLock();
        }
    }

    public boolean removeOccurrences(Object item, int occurrences)
    {
        this.acquireWriteLock();
        try
        {
            return this.delegate.removeOccurrences(item, occurrences);
        }
        finally
        {
            this.unlockWriteLock();
        }
    }

    public boolean setOccurrences(T item, int occurrences)
    {
        this.acquireWriteLock();
        try
        {
            return this.delegate.setOccurrences(item, occurrences);
        }
        finally
        {
            this.unlockWriteLock();
        }
    }

    public int occurrencesOf(Object item)
    {
        this.acquireReadLock();
        try
        {
            return this.delegate.occurrencesOf(item);
        }
        finally
        {
            this.unlockReadLock();
        }
    }

    public int sizeDistinct()
    {
        this.acquireReadLock();
        try
        {
            return this.delegate.sizeDistinct();
        }
        finally
        {
            this.unlockReadLock();
        }
    }

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

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

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

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

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

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

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

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

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

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

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

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

    public MutableBag newEmpty()
    {
        return MultiReaderHashBag.newBag();
    }

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

    public 

MutableBag rejectWith( Predicate2 predicate, P parameter) { this.acquireReadLock(); try { return this.delegate.rejectWith(predicate, parameter); } finally { this.unlockReadLock(); } } public MutableBag select(Predicate predicate) { this.acquireReadLock(); try { return this.delegate.select(predicate); } finally { this.unlockReadLock(); } } public

MutableBag selectWith( Predicate2 predicate, P parameter) { this.acquireReadLock(); try { return this.delegate.selectWith(predicate, parameter); } finally { this.unlockReadLock(); } } public MutableBag selectByOccurrences(IntPredicate predicate) { this.acquireReadLock(); try { return this.delegate.selectByOccurrences(predicate); } finally { this.unlockReadLock(); } } public MutableBag selectInstancesOf(Class clazz) { this.acquireReadLock(); try { return this.delegate.selectInstancesOf(clazz); } finally { this.unlockReadLock(); } } public PartitionMutableBag partition(Predicate predicate) { this.acquireReadLock(); try { return this.delegate.partition(predicate); } finally { this.unlockReadLock(); } } public

PartitionMutableBag partitionWith(Predicate2 predicate, P parameter) { this.acquireReadLock(); try { return this.delegate.partitionWith(predicate, parameter); } finally { this.unlockReadLock(); } } public MutableBag with(T element) { this.add(element); return this; } public MutableBag without(T element) { this.remove(element); return this; } public MutableBag withAll(Iterable elements) { this.addAllIterable(elements); return this; } public MutableBag withoutAll(Iterable elements) { this.removeAllIterable(elements); return this; } public MapIterable toMapOfItemToCount() { this.acquireReadLock(); try { return this.delegate.toMapOfItemToCount(); } finally { this.unlockReadLock(); } } public String toStringOfItemToCount() { this.acquireReadLock(); try { return this.delegate.toStringOfItemToCount(); } finally { this.unlockReadLock(); } } public MutableBagMultimap groupBy(Function function) { this.acquireReadLock(); try { return this.delegate.groupBy(function); } finally { this.unlockReadLock(); } } public MutableBagMultimap 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(); } } public MutableBag> zip(Iterable that) { this.acquireReadLock(); try { return this.delegate.zip(that); } finally { this.unlockReadLock(); } } 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 void forEachWithOccurrences(ObjectIntProcedure procedure) { this.acquireReadLock(); try { this.delegate.forEachWithOccurrences(procedure); } finally { this.unlockReadLock(); } } @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 = (MutableBag) in.readObject(); this.lock = new ReentrantReadWriteLock(); } //Exposed for testing static final class UntouchableMutableBag extends UntouchableMutableCollection implements MutableBag { private final MutableList> requestedIterators = Iterables.mList(); private UntouchableMutableBag(MutableBag newDelegate) { this.delegate = newDelegate; } public void becomeUseless() { this.delegate = null; this.requestedIterators.forEach(new Procedure>() { public void value(UntouchableIterator each) { each.becomeUseless(); } }); } public MutableBag with(T element) { this.add(element); return this; } public MutableBag without(T element) { this.remove(element); return this; } public MutableBag withAll(Iterable elements) { this.addAllIterable(elements); return this; } public MutableBag withoutAll(Iterable elements) { this.removeAllIterable(elements); return this; } public MutableBag asSynchronized() { throw new UnsupportedOperationException("cannot wrap an UntouchableMutableBag"); } public MutableBag asUnmodifiable() { throw new UnsupportedOperationException("cannot wrap an UntouchableMutableBag"); } public ImmutableBag toImmutable() { return Bags.immutable.ofAll(this.getDelegate()); } public LazyIterable asLazy() { return LazyIterate.adapt(this); } public Iterator iterator() { UntouchableIterator iterator = new UntouchableIterator(this.delegate.iterator()); this.requestedIterators.add(iterator); return iterator; } public void addOccurrences(T item, int occurrences) { this.getDelegate().addOccurrences(item, occurrences); } public boolean removeOccurrences(Object item, int occurrences) { return this.getDelegate().removeOccurrences(item, occurrences); } public boolean setOccurrences(T item, int occurrences) { return this.getDelegate().setOccurrences(item, occurrences); } public int occurrencesOf(Object item) { return this.getDelegate().occurrencesOf(item); } public int sizeDistinct() { return this.getDelegate().sizeDistinct(); } public MutableBag collect(Function function) { return this.getDelegate().collect(function); } public MutableBooleanBag collectBoolean(BooleanFunction booleanFunction) { return this.getDelegate().collectBoolean(booleanFunction); } public R collectBoolean(BooleanFunction booleanFunction, R target) { return this.getDelegate().collectBoolean(booleanFunction, target); } public MutableByteBag collectByte(ByteFunction byteFunction) { return this.getDelegate().collectByte(byteFunction); } public R collectByte(ByteFunction byteFunction, R target) { return this.getDelegate().collectByte(byteFunction, target); } public MutableCharBag collectChar(CharFunction charFunction) { return this.getDelegate().collectChar(charFunction); } public R collectChar(CharFunction charFunction, R target) { return this.getDelegate().collectChar(charFunction, target); } public MutableDoubleBag collectDouble(DoubleFunction doubleFunction) { return this.getDelegate().collectDouble(doubleFunction); } public R collectDouble(DoubleFunction doubleFunction, R target) { return this.getDelegate().collectDouble(doubleFunction, target); } public MutableFloatBag collectFloat(FloatFunction floatFunction) { return this.getDelegate().collectFloat(floatFunction); } public R collectFloat(FloatFunction floatFunction, R target) { return this.getDelegate().collectFloat(floatFunction, target); } public MutableIntBag collectInt(IntFunction intFunction) { return this.getDelegate().collectInt(intFunction); } public R collectInt(IntFunction intFunction, R target) { return this.getDelegate().collectInt(intFunction, target); } public MutableLongBag collectLong(LongFunction longFunction) { return this.getDelegate().collectLong(longFunction); } public R collectLong(LongFunction longFunction, R target) { return this.getDelegate().collectLong(longFunction, target); } public MutableShortBag collectShort(ShortFunction shortFunction) { return this.getDelegate().collectShort(shortFunction); } public R collectShort(ShortFunction shortFunction, R target) { return this.getDelegate().collectShort(shortFunction, target); } public MutableBag flatCollect(Function> function) { return this.getDelegate().flatCollect(function); } public MutableBag collectIf( Predicate predicate, Function function) { return this.getDelegate().collectIf(predicate, function); } public MutableBag collectWith( Function2 function, P parameter) { return this.getDelegate().collectWith(function, parameter); } public MutableBagMultimap groupBy(Function function) { return this.getDelegate().groupBy(function); } public MutableBagMultimap groupByEach(Function> function) { return this.getDelegate().groupByEach(function); } public MutableMap groupByUniqueKey(Function function) { return this.getDelegate().groupByUniqueKey(function); } public MutableBag newEmpty() { return this.getDelegate().newEmpty(); } public MutableBag reject(Predicate predicate) { return this.getDelegate().reject(predicate); } public

MutableBag rejectWith( Predicate2 predicate, P parameter) { return this.getDelegate().rejectWith(predicate, parameter); } public MutableBag select(Predicate predicate) { return this.getDelegate().select(predicate); } public

MutableBag selectWith( Predicate2 predicate, P parameter) { return this.getDelegate().selectWith(predicate, parameter); } public MutableBag selectByOccurrences(IntPredicate predicate) { return this.getDelegate().selectByOccurrences(predicate); } public MutableBag selectInstancesOf(Class clazz) { return this.getDelegate().selectInstancesOf(clazz); } public void forEachWithOccurrences(ObjectIntProcedure procedure) { this.getDelegate().forEachWithOccurrences(procedure); } public PartitionMutableBag partition(Predicate predicate) { return this.getDelegate().partition(predicate); } public

PartitionMutableBag partitionWith(Predicate2 predicate, P parameter) { return this.getDelegate().partitionWith(predicate, parameter); } public MutableBag> zip(Iterable that) { return this.getDelegate().zip(that); } public MutableSet> zipWithIndex() { return this.getDelegate().zipWithIndex(); } public MapIterable toMapOfItemToCount() { return this.getDelegate().toMapOfItemToCount(); } public String toStringOfItemToCount() { return this.getDelegate().toStringOfItemToCount(); } private MutableBag getDelegate() { return (MutableBag) 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; } } }