@Realtime @Parallelizable(mutexFree=false, comment="Shared/Parallel views may use read-write locks.") @DefaultTextFormat(value=FastCollection.StandardText.class) public abstract class FastCollection<E> extends Object implements Collection<E>, Serializable
A high-performance collection with real-time
behavior;
smooth capacity increase/decrease and minimal memory footprint.
Fast collections support multiple views which can be chained.
unmodifiable()
- View which does not allow any modification.shared()
- Thread-safe view allowing concurrent read/write operations.parallel()
- Shared
view allowing parallel processing (closure-based).sequential()
- View disallowing parallel processing.filtered(filter)
- View exposing the elements matching the specified filter.mapped(function)
- View exposing elements through the specified mapping function.sorted()
- View exposing elements according to the collection sorting order.reversed()
- View exposing elements in reverse iterative order.distinct()
- View exposing each element only once.comparator(cmp)
- View using the specified comparator for element equality/order. Unmodifiable collections are not always immutable. An immutable
.
reference (or const reference) can only be obtained
when the originator
guarantees that the collection source cannot be modified even by himself
(the value of the immutable reference is an unmodifiable
collection).
Immutable<List<String>> winners = new FastTable<String>().addAll("John Deuff", "Otto Graf", "Sim Kamil").toImmutable(); // Immutability is guaranteed, no reference left on the collection source.
Immutable collections may be preferred to shared()
views in case of infrequent updates
since they do not have mutexes (and locking during updates).
static Immutable<FastSet<Unit>> basicUnits = new FastSet<Unit>().toImmutable(); synchronized void addBasicUnits(Unit... units) { // Infrequent. basicUnits = basicUnits.values().copy().addAll(units).toImmutable(); }
Views are similar to Java 8 streams except that views are themselves collections (virtual collections) and actions on a view can impact the original collection. Collection views are nothing "new" since they already existed in the original java.util collection classes (e.g. List.subList(...), Map.keySet(), Map.values()). Javolution extends to this concept and allows views to be chained which addresses the concern of class proliferation (see State of the Lambda: Libraries Edition).
FastTable<String> names = new FastTable<String>().addAll("Oscar Thon", "Eva Poret", "Paul Auchon"); boolean found = names.comparator(Comparators.LEXICAL_CASE_INSENSITIVE).contains("LUC SURIEUX"); names.subTable(0, n).clear(); // Removes the n first names (see java.util.List.subList). names.distinct().add("Guy Liguili"); // Adds "Guy Liguili" only if not already present. names.filtered(isLong).clear(); // Removes all the persons with long names. names.parallel().filtered(isLong).clear(); // Same as above but performed concurrently. ... Predicate<CharSequence> isLong = new Predicate<CharSequence>() { public boolean test(CharSequence csq) { return csq.length() > 16; } });
Views can of course be used to perform "stream" oriented filter-map-reduce operations with the same benefits: Parallelism support, excellent memory characteristics (no caching and cost nothing to create), etc.
String anyLongName = names.filtered(isLong).reduce(Operators.ANY); // Returns any long name. int nbrChars = names.mapped(toLength).reduce(Operators.SUM); // Returns the total number of characters. int maxLength = names.parallel().mapped(toLength).reduce(Operators.MAX); // Finds the longest name in parallel. ... Function<CharSequence, Integer> toLength = new Function<CharSequence, Integer>() { public Integer apply(CharSequence csq) { return csq.length(); } }); // JDK Class.getEnclosingMethod using Javolution's views and Java 8 (to be compared with the current 20 lines implementation !). Method matching = new FastTable<Method>().addAll(enclosingInfo.getEnclosingClass().getDeclaredMethods()) .filtered(m -> Comparators.STANDARD.areEqual(m.getName(), enclosingInfo.getName()) .filtered(m -> Comparators.ARRAY.areEqual(m.getParameterTypes(), parameterClasses)) .filtered(m -> Comparators.STANDARD.areEqual(m.getReturnType(), returnType)) .reduce(Operators.ANY); if (matching == null) throw new InternalError("Enclosing method not found"); return matching;
Fast collections can be iterated over using closures, this is also the preferred way
to iterate over shared
collections (concurrent update are safe).
If a collection (or a map) is shared, derived views are also thread-safe.
Similarly, if a collection is parallel
, closure-based iterations
on derived views can be performed concurrently.
FastMap<String, Runnable> tasks = ... ... tasks.values().parallel().forEach(new Consumer<Runnable>() { // Executes task concurrently. public void accept(Runnable task) { task.run(); } });
With Java 8, closures are greatly simplified using lambda expressions.
tasks.values().parallel().forEach(task -> task.run()); // Same as above. names.sorted().reversed().forEach(str -> System.out.println(str)); // Prints names in reverse alphabetical order.
Modifier and Type | Class and Description |
---|---|
static class |
FastCollection.StandardText
The standard java collection format (parsing not supported).
|
Modifier | Constructor and Description |
---|---|
protected |
FastCollection()
Default constructor.
|
Modifier and Type | Method and Description |
---|---|
boolean |
add(E element)
Collection operations.
|
boolean |
addAll(Collection<? extends E> that) |
FastCollection<E> |
addAll(E... elements)
Returns this collection with the specified element added.
|
FastCollection<E> |
addAll(FastCollection<? extends E> that)
Returns this collection with the specified collection's elements added.
|
void |
atomic(Runnable update)
Executes the specified update in an atomic manner.
|
void |
clear() |
EqualityComparator<? super E> |
comparator()
Returns the comparator uses by this collection for equality and/or
ordering if this collection is ordered.
|
FastCollection<E> |
comparator(Comparator<? super E> cmp)
Returns a view over this collection using the specified comparator
for element equality or sorting.
|
boolean |
contains(Object element) |
boolean |
containsAll(Collection<?> that) |
FastCollection<E> |
distinct()
Returns a view exposing only distinct elements (it does not iterate twice
over the
same elements). |
boolean |
doWhile(Predicate<? super E> doContinue)
Iterates over this collection elements applying the specified predicate
until that predicate returns
false (if the collection is
parallel all concurrent iterations will terminate then). |
boolean |
equals(Object obj)
Compares the specified object with this collection for equality.
|
FastCollection<E> |
filtered(Predicate<? super E> filter)
Returns a view exposing only the elements matching the specified
filter.
|
void |
forEach(Consumer<? super E> consumer)
Iterates over all this collection elements applying the specified
consumer.
|
int |
hashCode() |
boolean |
isEmpty() |
Iterator<E> |
iterator() |
<R> FastCollection<R> |
mapped(Function<? super E,? extends R> function)
Returns a view exposing elements through the specified mapping function.
|
FastCollection<E> |
parallel()
Returns a parallel/
shared view of this collection. |
E |
reduce(CollectionOperator<? super E> operator)
Performs a reduction of the elements of this collection using the
specified operator (convenience method).
|
boolean |
remove(Object element) |
boolean |
removeAll(Collection<?> that) |
boolean |
removeIf(Predicate<? super E> filter)
Removes from this collection all the elements matching the specified
functional predicate.
|
boolean |
retainAll(Collection<?> that) |
FastCollection<E> |
reversed()
Returns a view exposing elements in reverse iterative order.
|
FastCollection<E> |
sequential()
Returns a sequential view of this collection.
|
protected abstract CollectionService<E> |
service()
Returns the service implementation of this collection (for sub-classes).
|
protected static <E> CollectionService<E> |
serviceOf(FastCollection<E> collection)
Returns the service implementation of any fast collection
(for sub-classes).
|
FastCollection<E> |
shared()
Returns a thread-safe view over this collection.
|
int |
size() |
FastCollection<E> |
sorted()
Returns an unmodifiable view exposing element sorted according to this
collection
comparator . |
Object[] |
toArray() |
<T> T[] |
toArray(T[] array) |
<T extends Collection<E>> |
toImmutable()
Returns an immutable reference over this collection.
|
String |
toString() |
FastCollection<E> |
unmodifiable()
Returns an unmodifiable view over this collection.
|
public FastCollection<E> unmodifiable()
UnsupportedOperationException
being raised.public FastCollection<E> shared()
immutable
collections to be replaced at each update rather than shared views.public FastCollection<E> parallel()
shared
view of this collection.
Using this view, closure-based iteration can be performed concurrently.
The default implementation is based upon
ConcurrentContext
.
Note: Some view may prevent parallel processing over their
collection target. It is therefore preferable for
parallel views to be the last view before processing.
For example collection.unmodifiable().parallel()
is preferred to collection.parallel().unmodifiable()
.
public FastCollection<E> sequential()
public FastCollection<E> comparator(Comparator<? super E> cmp)
cmp.compare(e1, e2) == 0
.public FastCollection<E> filtered(Predicate<? super E> filter)
public <R> FastCollection<R> mapped(Function<? super E,? extends R> function)
public FastCollection<E> sorted()
comparator
.
The comparator view
can be used
to sort elements using any user-defined comparator.public FastCollection<E> reversed()
public FastCollection<E> distinct()
same
elements). Adding elements already
in the collection through this view has no effect (if this collection is
initially empty, using the distinct view prevents element duplication).@Realtime(limit=LINEAR) public void forEach(Consumer<? super E> consumer)
parallel
.consumer
- the functional consumer applied to the collection elements.@Realtime(limit=LINEAR) public boolean doWhile(Predicate<? super E> doContinue)
false
(if the collection is
parallel
all concurrent iterations will terminate then).doContinue
- the functional predicate applied to the collection elements.true
if the iteration has not been interrupted (no predicate
evaluation returned false
); true
otherwise.@Realtime(limit=LINEAR) public boolean removeIf(Predicate<? super E> filter)
parallel
.filter
- a predicate returning true
for elements to be removed.true
if at least one element has been removed;
false
otherwise.@Realtime(limit=LINEAR) public E reduce(CollectionOperator<? super E> operator)
ANY
, AND
and
Operators.OR
may stop iterating early.operator
- the operator.operator.apply(this.getService())
public boolean add(E element)
add
in interface Collection<E>
public boolean isEmpty()
isEmpty
in interface Collection<E>
@Realtime(limit=LINEAR) public boolean contains(Object element)
contains
in interface Collection<E>
@Realtime(limit=LINEAR) public boolean remove(Object element)
remove
in interface Collection<E>
@Realtime(limit=LINEAR) public boolean addAll(Collection<? extends E> that)
addAll
in interface Collection<E>
@Realtime(limit=N_SQUARE) public boolean containsAll(Collection<?> that)
containsAll
in interface Collection<E>
@Realtime(limit=N_SQUARE) public boolean removeAll(Collection<?> that)
removeAll
in interface Collection<E>
@Realtime(limit=N_SQUARE) public boolean retainAll(Collection<?> that)
retainAll
in interface Collection<E>
@Realtime(limit=LINEAR) public Object[] toArray()
toArray
in interface Collection<E>
@Realtime(limit=LINEAR) public <T> T[] toArray(T[] array)
toArray
in interface Collection<E>
public FastCollection<E> addAll(E... elements)
elements
- the elements to be added.this
public FastCollection<E> addAll(FastCollection<? extends E> that)
public EqualityComparator<? super E> comparator()
@Parallelizable(mutexFree=false, comment="The collection is locked during atomic updates") public void atomic(Runnable update)
shared
or
parallel
collections.update
- the update action to be executed on this collection.public <T extends Collection<E>> Immutable<T> toImmutable()
unmodifiable
view of this collection
for which the caller guarantees that no change will ever be made
(e.g. there is no reference left to the original collection).@Realtime(limit=LINEAR) public boolean equals(Object obj)
true
if the specified
object is also a set, the two sets have the same size and the specified
set contains all the element of this set. If this collection is a list,
returns true
if and
only if the specified object is also a list, both lists have the same
size, and all corresponding pairs of elements in
the two lists are equal using the default object equality.
If this collection is neither a list, nor a set, this method returns
the default object equality (this == obj
).equals
in interface Collection<E>
equals
in class Object
obj
- the object to be compared for equality with this collectiontrue
if both collection are considered equals;
false
otherwise.@Realtime(limit=LINEAR) public int hashCode()
hashCode
in interface Collection<E>
hashCode
in class Object
protected abstract CollectionService<E> service()
protected static <E> CollectionService<E> serviceOf(FastCollection<E> collection)
Copyright © 2005-2013 Javolution. All Rights Reserved.