code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Map;
import java.util.SortedSet;
import javax.annotation.Nullable;
/**
* Basic implementation of the {@link SortedSetMultimap} interface. It's a
* wrapper around {@link AbstractMultimap} that converts the returned
* collections into sorted sets. The {@link #createCollection} method
* must return a {@code SortedSet}.
*
* @author Jared Levy
*/
@GwtCompatible
abstract class AbstractSortedSetMultimap<K, V>
extends AbstractSetMultimap<K, V> implements SortedSetMultimap<K, V> {
/**
* Creates a new multimap that uses the provided map.
*
* @param map place to store the mapping from each key to its corresponding
* values
*/
protected AbstractSortedSetMultimap(Map<K, Collection<V>> map) {
super(map);
}
@Override abstract SortedSet<V> createCollection();
// Following Javadoc copied from Multimap and SortedSetMultimap.
/**
* Returns a collection view of all values associated with a key. If no
* mappings in the multimap have the provided key, an empty collection is
* returned.
*
* <p>Changes to the returned collection will update the underlying multimap,
* and vice versa.
*
* <p>Because a {@code SortedSetMultimap} has unique sorted values for a given
* key, this method returns a {@link SortedSet}, instead of the
* {@link Collection} specified in the {@link Multimap} interface.
*/
@Override public SortedSet<V> get(@Nullable K key) {
return (SortedSet<V>) super.get(key);
}
/**
* Removes all values associated with a given key. The returned collection is
* immutable.
*
* <p>Because a {@code SortedSetMultimap} has unique sorted values for a given
* key, this method returns a {@link SortedSet}, instead of the
* {@link Collection} specified in the {@link Multimap} interface.
*/
@Override public SortedSet<V> removeAll(@Nullable Object key) {
return (SortedSet<V>) super.removeAll(key);
}
/**
* Stores a collection of values with the same key, replacing any existing
* values for that key. The returned collection is immutable.
*
* <p>Because a {@code SortedSetMultimap} has unique sorted values for a given
* key, this method returns a {@link SortedSet}, instead of the
* {@link Collection} specified in the {@link Multimap} interface.
*
* <p>Any duplicates in {@code values} will be stored in the multimap once.
*/
@Override public SortedSet<V> replaceValues(
K key, Iterable<? extends V> values) {
return (SortedSet<V>) super.replaceValues(key, values);
}
/**
* Returns a map view that associates each key with the corresponding values
* in the multimap. Changes to the returned map, such as element removal, will
* update the underlying multimap. The map does not support {@code setValue}
* on its entries, {@code put}, or {@code putAll}.
*
* <p>When passed a key that is present in the map, {@code
* asMap().get(Object)} has the same behavior as {@link #get}, returning a
* live collection. When passed a key that is not present, however, {@code
* asMap().get(Object)} returns {@code null} instead of an empty collection.
*
* <p>Though the method signature doesn't say so explicitly, the returned map
* has {@link SortedSet} values.
*/
@Override public Map<K, Collection<V>> asMap() {
return super.asMap();
}
/**
* {@inheritDoc}
*
* Consequently, the values do not follow their natural ordering or the
* ordering of the value comparator.
*/
@Override public Collection<V> values() {
return super.values();
}
private static final long serialVersionUID = 430848587173315748L;
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.collect;
import com.google.common.annotations.GwtCompatible;
/**
* A factory for extending paths in a binary search tree.
*
* @author Louis Wasserman
* @param <N> The type of binary search tree nodes used in the paths generated by this {@code
* BstPathFactory}.
* @param <P> The type of paths constructed by this {@code BstPathFactory}.
*/
@GwtCompatible
interface BstPathFactory<N extends BstNode<?, N>, P extends BstPath<N, P>> {
/**
* Returns this path extended by one node to the specified {@code side}.
*/
P extension(P path, BstSide side);
/**
* Returns the trivial path that starts at {@code root} and goes no further.
*/
P initialPath(N root);
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
/**
* A table which forwards all its method calls to another table. Subclasses
* should override one or more methods to modify the behavior of the backing
* map as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Gregory Kick
* @since 7.0
*/
@Beta
@GwtCompatible
public abstract class ForwardingTable<R, C, V> extends ForwardingObject
implements Table<R, C, V> {
/** Constructor for use by subclasses. */
protected ForwardingTable() {}
@Override protected abstract Table<R, C, V> delegate();
@Override
public Set<Cell<R, C, V>> cellSet() {
return delegate().cellSet();
}
@Override
public void clear() {
delegate().clear();
}
@Override
public Map<R, V> column(C columnKey) {
return delegate().column(columnKey);
}
@Override
public Set<C> columnKeySet() {
return delegate().columnKeySet();
}
@Override
public Map<C, Map<R, V>> columnMap() {
return delegate().columnMap();
}
@Override
public boolean contains(Object rowKey, Object columnKey) {
return delegate().contains(rowKey, columnKey);
}
@Override
public boolean containsColumn(Object columnKey) {
return delegate().containsColumn(columnKey);
}
@Override
public boolean containsRow(Object rowKey) {
return delegate().containsRow(rowKey);
}
@Override
public boolean containsValue(Object value) {
return delegate().containsValue(value);
}
@Override
public V get(Object rowKey, Object columnKey) {
return delegate().get(rowKey, columnKey);
}
@Override
public boolean isEmpty() {
return delegate().isEmpty();
}
@Override
public V put(R rowKey, C columnKey, V value) {
return delegate().put(rowKey, columnKey, value);
}
@Override
public void putAll(Table<? extends R, ? extends C, ? extends V> table) {
delegate().putAll(table);
}
@Override
public V remove(Object rowKey, Object columnKey) {
return delegate().remove(rowKey, columnKey);
}
@Override
public Map<C, V> row(R rowKey) {
return delegate().row(rowKey);
}
@Override
public Set<R> rowKeySet() {
return delegate().rowKeySet();
}
@Override
public Map<R, Map<C, V>> rowMap() {
return delegate().rowMap();
}
@Override
public int size() {
return delegate().size();
}
@Override
public Collection<V> values() {
return delegate().values();
}
@Override public boolean equals(Object obj) {
return (obj == this) || delegate().equals(obj);
}
@Override public int hashCode() {
return delegate().hashCode();
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* 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.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.TreeMap;
import javax.annotation.Nullable;
/**
* An immutable {@link Multimap}. Does not permit null keys or values.
*
* <p>Unlike {@link Multimaps#unmodifiableMultimap(Multimap)}, which is
* a <i>view</i> of a separate multimap which can still change, an instance of
* {@code ImmutableMultimap} contains its own data and will <i>never</i>
* change. {@code ImmutableMultimap} is convenient for
* {@code public static final} multimaps ("constant multimaps") and also lets
* you easily make a "defensive copy" of a multimap provided to your class by
* a caller.
*
* <p><b>Note:</b> Although this class is not final, it cannot be subclassed as
* it has no public or protected constructors. Thus, instances of this class
* are guaranteed to be immutable.
*
* <p>In addition to methods defined by {@link Multimap}, an {@link #inverse}
* method is also supported.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
* immutable collections</a>.
*
* @author Jared Levy
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
// TODO(user): If BiMultimap graduates from labs, this class should implement it.
public abstract class ImmutableMultimap<K, V>
implements Multimap<K, V>, Serializable {
/** Returns an empty multimap. */
public static <K, V> ImmutableMultimap<K, V> of() {
return ImmutableListMultimap.of();
}
/**
* Returns an immutable multimap containing a single entry.
*/
public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1) {
return ImmutableListMultimap.of(k1, v1);
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableMultimap<K, V> of(K k1, V v1, K k2, V v2) {
return ImmutableListMultimap.of(k1, v1, k2, v2);
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3) {
return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3);
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4);
}
/**
* Returns an immutable multimap containing the given entries, in order.
*/
public static <K, V> ImmutableMultimap<K, V> of(
K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5);
}
// looking for of() with > 5 entries? Use the builder instead.
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder} constructor.
*/
public static <K, V> Builder<K, V> builder() {
return new Builder<K, V>();
}
/**
* Multimap for {@link ImmutableMultimap.Builder} that maintains key and
* value orderings, allows duplicate values, and performs better than
* {@link LinkedListMultimap}.
*/
private static class BuilderMultimap<K, V> extends AbstractMultimap<K, V> {
BuilderMultimap() {
super(new LinkedHashMap<K, Collection<V>>());
}
@Override Collection<V> createCollection() {
return Lists.newArrayList();
}
private static final long serialVersionUID = 0;
}
/**
* Multimap for {@link ImmutableMultimap.Builder} that sorts key and allows
* duplicate values,
*/
private static class SortedKeyBuilderMultimap<K, V>
extends AbstractMultimap<K, V> {
SortedKeyBuilderMultimap(
Comparator<? super K> keyComparator, Multimap<K, V> multimap) {
super(new TreeMap<K, Collection<V>>(keyComparator));
putAll(multimap);
}
@Override Collection<V> createCollection() {
return Lists.newArrayList();
}
private static final long serialVersionUID = 0;
}
/**
* A builder for creating immutable multimap instances, especially
* {@code public static final} multimaps ("constant multimaps"). Example:
* <pre> {@code
*
* static final Multimap<String, Integer> STRING_TO_INTEGER_MULTIMAP =
* new ImmutableMultimap.Builder<String, Integer>()
* .put("one", 1)
* .putAll("several", 1, 2, 3)
* .putAll("many", 1, 2, 3, 4, 5)
* .build();}</pre>
*
* Builder instances can be reused; it is safe to call {@link #build} multiple
* times to build multiple multimaps in series. Each multimap contains the
* key-value mappings in the previously created multimaps.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static class Builder<K, V> {
Multimap<K, V> builderMultimap = new BuilderMultimap<K, V>();
Comparator<? super V> valueComparator;
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableMultimap#builder}.
*/
public Builder() {}
/**
* Adds a key-value mapping to the built multimap.
*/
public Builder<K, V> put(K key, V value) {
builderMultimap.put(checkNotNull(key), checkNotNull(value));
return this;
}
/**
* Adds an entry to the built multimap.
*
* @since 11.0
*/
public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
builderMultimap.put(
checkNotNull(entry.getKey()), checkNotNull(entry.getValue()));
return this;
}
/**
* Stores a collection of values with the same key in the built multimap.
*
* @throws NullPointerException if {@code key}, {@code values}, or any
* element in {@code values} is null. The builder is left in an invalid
* state.
*/
public Builder<K, V> putAll(K key, Iterable<? extends V> values) {
Collection<V> valueList = builderMultimap.get(checkNotNull(key));
for (V value : values) {
valueList.add(checkNotNull(value));
}
return this;
}
/**
* Stores an array of values with the same key in the built multimap.
*
* @throws NullPointerException if the key or any value is null. The builder
* is left in an invalid state.
*/
public Builder<K, V> putAll(K key, V... values) {
return putAll(key, Arrays.asList(values));
}
/**
* Stores another multimap's entries in the built multimap. The generated
* multimap's key and value orderings correspond to the iteration ordering
* of the {@code multimap.asMap()} view, with new keys and values following
* any existing keys and values.
*
* @throws NullPointerException if any key or value in {@code multimap} is
* null. The builder is left in an invalid state.
*/
public Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
for (Entry<? extends K, ? extends Collection<? extends V>> entry
: multimap.asMap().entrySet()) {
putAll(entry.getKey(), entry.getValue());
}
return this;
}
/**
* Specifies the ordering of the generated multimap's keys.
*
* @since 8.0
*/
@Beta
public Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
builderMultimap = new SortedKeyBuilderMultimap<K, V>(
checkNotNull(keyComparator), builderMultimap);
return this;
}
/**
* Specifies the ordering of the generated multimap's values for each key.
*
* @since 8.0
*/
@Beta
public Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
this.valueComparator = checkNotNull(valueComparator);
return this;
}
/**
* Returns a newly-created immutable multimap.
*/
public ImmutableMultimap<K, V> build() {
if (valueComparator != null) {
for (Collection<V> values : builderMultimap.asMap().values()) {
List<V> list = (List <V>) values;
Collections.sort(list, valueComparator);
}
}
return copyOf(builderMultimap);
}
}
/**
* Returns an immutable multimap containing the same mappings as {@code
* multimap}. The generated multimap's key and value orderings correspond to
* the iteration ordering of the {@code multimap.asMap()} view.
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*
* @throws NullPointerException if any key or value in {@code multimap} is
* null
*/
public static <K, V> ImmutableMultimap<K, V> copyOf(
Multimap<? extends K, ? extends V> multimap) {
if (multimap instanceof ImmutableMultimap) {
@SuppressWarnings("unchecked") // safe since multimap is not writable
ImmutableMultimap<K, V> kvMultimap
= (ImmutableMultimap<K, V>) multimap;
if (!kvMultimap.isPartialView()) {
return kvMultimap;
}
}
return ImmutableListMultimap.copyOf(multimap);
}
final transient ImmutableMap<K, ? extends ImmutableCollection<V>> map;
final transient int size;
// These constants allow the deserialization code to set final fields. This
// holder class makes sure they are not initialized unless an instance is
// deserialized.
@GwtIncompatible("java serialization is not supported")
static class FieldSettersHolder {
static final Serialization.FieldSetter<ImmutableMultimap>
MAP_FIELD_SETTER = Serialization.getFieldSetter(
ImmutableMultimap.class, "map");
static final Serialization.FieldSetter<ImmutableMultimap>
SIZE_FIELD_SETTER = Serialization.getFieldSetter(
ImmutableMultimap.class, "size");
}
ImmutableMultimap(ImmutableMap<K, ? extends ImmutableCollection<V>> map,
int size) {
this.map = map;
this.size = size;
}
// mutators (not supported)
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override
public ImmutableCollection<V> removeAll(Object key) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override
public ImmutableCollection<V> replaceValues(K key,
Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override
public void clear() {
throw new UnsupportedOperationException();
}
/**
* Returns an immutable collection of the values for the given key. If no
* mappings in the multimap have the provided key, an empty immutable
* collection is returned. The values are in the same order as the parameters
* used to build this multimap.
*/
@Override
public abstract ImmutableCollection<V> get(K key);
/**
* Returns an immutable multimap which is the inverse of this one. For every
* key-value mapping in the original, the result will have a mapping with
* key and value reversed.
*
* @since 11
*/
@Beta
public abstract ImmutableMultimap<V, K> inverse();
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override
public boolean put(K key, V value) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override
public boolean putAll(K key, Iterable<? extends V> values) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override
public boolean putAll(Multimap<? extends K, ? extends V> multimap) {
throw new UnsupportedOperationException();
}
/**
* Guaranteed to throw an exception and leave the multimap unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override
public boolean remove(Object key, Object value) {
throw new UnsupportedOperationException();
}
boolean isPartialView(){
return map.isPartialView();
}
// accessors
@Override
public boolean containsEntry(@Nullable Object key, @Nullable Object value) {
Collection<V> values = map.get(key);
return values != null && values.contains(value);
}
@Override
public boolean containsKey(@Nullable Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(@Nullable Object value) {
for (Collection<V> valueCollection : map.values()) {
if (valueCollection.contains(value)) {
return true;
}
}
return false;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public int size() {
return size;
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Multimap) {
Multimap<?, ?> that = (Multimap<?, ?>) object;
return this.map.equals(that.asMap());
}
return false;
}
@Override public int hashCode() {
return map.hashCode();
}
@Override public String toString() {
return map.toString();
}
// views
/**
* Returns an immutable set of the distinct keys in this multimap. These keys
* are ordered according to when they first appeared during the construction
* of this multimap.
*/
@Override
public ImmutableSet<K> keySet() {
return map.keySet();
}
/**
* Returns an immutable map that associates each key with its corresponding
* values in the multimap.
*/
@Override
@SuppressWarnings("unchecked") // a widening cast
public ImmutableMap<K, Collection<V>> asMap() {
return (ImmutableMap) map;
}
private transient ImmutableCollection<Entry<K, V>> entries;
/**
* Returns an immutable collection of all key-value pairs in the multimap. Its
* iterator traverses the values for the first key, the values for the second
* key, and so on.
*/
@Override
public ImmutableCollection<Entry<K, V>> entries() {
ImmutableCollection<Entry<K, V>> result = entries;
return (result == null)
? (entries = new EntryCollection<K, V>(this)) : result;
}
private static class EntryCollection<K, V>
extends ImmutableCollection<Entry<K, V>> {
final ImmutableMultimap<K, V> multimap;
EntryCollection(ImmutableMultimap<K, V> multimap) {
this.multimap = multimap;
}
@Override public UnmodifiableIterator<Entry<K, V>> iterator() {
final Iterator<? extends Entry<K, ? extends ImmutableCollection<V>>>
mapIterator = this.multimap.map.entrySet().iterator();
return new UnmodifiableIterator<Entry<K, V>>() {
K key;
Iterator<V> valueIterator;
@Override
public boolean hasNext() {
return (key != null && valueIterator.hasNext())
|| mapIterator.hasNext();
}
@Override
public Entry<K, V> next() {
if (key == null || !valueIterator.hasNext()) {
Entry<K, ? extends ImmutableCollection<V>> entry
= mapIterator.next();
key = entry.getKey();
valueIterator = entry.getValue().iterator();
}
return Maps.immutableEntry(key, valueIterator.next());
}
};
}
@Override boolean isPartialView() {
return multimap.isPartialView();
}
@Override
public int size() {
return multimap.size();
}
@Override public boolean contains(Object object) {
if (object instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) object;
return multimap.containsEntry(entry.getKey(), entry.getValue());
}
return false;
}
private static final long serialVersionUID = 0;
}
private transient ImmutableMultiset<K> keys;
/**
* Returns a collection, which may contain duplicates, of all keys. The number
* of times a key appears in the returned multiset equals the number of
* mappings the key has in the multimap. Duplicate keys appear consecutively
* in the multiset's iteration order.
*/
@Override
public ImmutableMultiset<K> keys() {
ImmutableMultiset<K> result = keys;
return (result == null) ? (keys = createKeys()) : result;
}
private ImmutableMultiset<K> createKeys() {
ImmutableMultiset.Builder<K> builder = ImmutableMultiset.builder();
for (Entry<K, ? extends ImmutableCollection<V>> entry
: map.entrySet()) {
builder.addCopies(entry.getKey(), entry.getValue().size());
}
return builder.build();
}
private transient ImmutableCollection<V> values;
/**
* Returns an immutable collection of the values in this multimap. Its
* iterator traverses the values for the first key, the values for the second
* key, and so on.
*/
@Override
public ImmutableCollection<V> values() {
ImmutableCollection<V> result = values;
return (result == null) ? (values = new Values<V>(this)) : result;
}
private static class Values<V> extends ImmutableCollection<V> {
final ImmutableMultimap<?, V> multimap;
Values(ImmutableMultimap<?, V> multimap) {
this.multimap = multimap;
}
@Override public UnmodifiableIterator<V> iterator() {
final Iterator<? extends Entry<?, V>> entryIterator
= multimap.entries().iterator();
return new UnmodifiableIterator<V>() {
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public V next() {
return entryIterator.next().getValue();
}
};
}
@Override
public int size() {
return multimap.size();
}
@Override boolean isPartialView() {
return true;
}
private static final long serialVersionUID = 0;
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* 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.google.common.collect;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;
/**
* Provides static methods for serializing collection classes.
*
* <p>This class assists the implementation of collection classes. Do not use
* this class to serialize collections that are defined elsewhere.
*
* @author Jared Levy
*/
final class Serialization {
private Serialization() {}
/**
* Reads a count corresponding to a serialized map, multiset, or multimap. It
* returns the size of a map serialized by {@link
* #writeMap(Map, ObjectOutputStream)}, the number of distinct elements in a
* multiset serialized by {@link
* #writeMultiset(Multiset, ObjectOutputStream)}, or the number of distinct
* keys in a multimap serialized by {@link
* #writeMultimap(Multimap, ObjectOutputStream)}.
*
* <p>The returned count may be used to construct an empty collection of the
* appropriate capacity before calling any of the {@code populate} methods.
*/
static int readCount(ObjectInputStream stream) throws IOException {
return stream.readInt();
}
/**
* Stores the contents of a map in an output stream, as part of serialization.
* It does not support concurrent maps whose content may change while the
* method is running.
*
* <p>The serialized output consists of the number of entries, first key,
* first value, second key, second value, and so on.
*/
static <K, V> void writeMap(Map<K, V> map, ObjectOutputStream stream)
throws IOException {
stream.writeInt(map.size());
for (Map.Entry<K, V> entry : map.entrySet()) {
stream.writeObject(entry.getKey());
stream.writeObject(entry.getValue());
}
}
/**
* Populates a map by reading an input stream, as part of deserialization.
* See {@link #writeMap} for the data format.
*/
static <K, V> void populateMap(Map<K, V> map, ObjectInputStream stream)
throws IOException, ClassNotFoundException {
int size = stream.readInt();
populateMap(map, stream, size);
}
/**
* Populates a map by reading an input stream, as part of deserialization.
* See {@link #writeMap} for the data format. The size is determined by a
* prior call to {@link #readCount}.
*/
static <K, V> void populateMap(Map<K, V> map, ObjectInputStream stream,
int size) throws IOException, ClassNotFoundException {
for (int i = 0; i < size; i++) {
@SuppressWarnings("unchecked") // reading data stored by writeMap
K key = (K) stream.readObject();
@SuppressWarnings("unchecked") // reading data stored by writeMap
V value = (V) stream.readObject();
map.put(key, value);
}
}
/**
* Stores the contents of a multiset in an output stream, as part of
* serialization. It does not support concurrent multisets whose content may
* change while the method is running.
*
* <p>The serialized output consists of the number of distinct elements, the
* first element, its count, the second element, its count, and so on.
*/
static <E> void writeMultiset(
Multiset<E> multiset, ObjectOutputStream stream) throws IOException {
int entryCount = multiset.entrySet().size();
stream.writeInt(entryCount);
for (Multiset.Entry<E> entry : multiset.entrySet()) {
stream.writeObject(entry.getElement());
stream.writeInt(entry.getCount());
}
}
/**
* Populates a multiset by reading an input stream, as part of
* deserialization. See {@link #writeMultiset} for the data format.
*/
static <E> void populateMultiset(
Multiset<E> multiset, ObjectInputStream stream)
throws IOException, ClassNotFoundException {
int distinctElements = stream.readInt();
populateMultiset(multiset, stream, distinctElements);
}
/**
* Populates a multiset by reading an input stream, as part of
* deserialization. See {@link #writeMultiset} for the data format. The number
* of distinct elements is determined by a prior call to {@link #readCount}.
*/
static <E> void populateMultiset(
Multiset<E> multiset, ObjectInputStream stream, int distinctElements)
throws IOException, ClassNotFoundException {
for (int i = 0; i < distinctElements; i++) {
@SuppressWarnings("unchecked") // reading data stored by writeMultiset
E element = (E) stream.readObject();
int count = stream.readInt();
multiset.add(element, count);
}
}
/**
* Stores the contents of a multimap in an output stream, as part of
* serialization. It does not support concurrent multimaps whose content may
* change while the method is running. The {@link Multimap#asMap} view
* determines the ordering in which data is written to the stream.
*
* <p>The serialized output consists of the number of distinct keys, and then
* for each distinct key: the key, the number of values for that key, and the
* key's values.
*/
static <K, V> void writeMultimap(
Multimap<K, V> multimap, ObjectOutputStream stream) throws IOException {
stream.writeInt(multimap.asMap().size());
for (Map.Entry<K, Collection<V>> entry : multimap.asMap().entrySet()) {
stream.writeObject(entry.getKey());
stream.writeInt(entry.getValue().size());
for (V value : entry.getValue()) {
stream.writeObject(value);
}
}
}
/**
* Populates a multimap by reading an input stream, as part of
* deserialization. See {@link #writeMultimap} for the data format.
*/
static <K, V> void populateMultimap(
Multimap<K, V> multimap, ObjectInputStream stream)
throws IOException, ClassNotFoundException {
int distinctKeys = stream.readInt();
populateMultimap(multimap, stream, distinctKeys);
}
/**
* Populates a multimap by reading an input stream, as part of
* deserialization. See {@link #writeMultimap} for the data format. The number
* of distinct keys is determined by a prior call to {@link #readCount}.
*/
static <K, V> void populateMultimap(
Multimap<K, V> multimap, ObjectInputStream stream, int distinctKeys)
throws IOException, ClassNotFoundException {
for (int i = 0; i < distinctKeys; i++) {
@SuppressWarnings("unchecked") // reading data stored by writeMultimap
K key = (K) stream.readObject();
Collection<V> values = multimap.get(key);
int valueCount = stream.readInt();
for (int j = 0; j < valueCount; j++) {
@SuppressWarnings("unchecked") // reading data stored by writeMultimap
V value = (V) stream.readObject();
values.add(value);
}
}
}
// Secret sauce for setting final fields; don't make it public.
static <T> FieldSetter<T> getFieldSetter(
final Class<T> clazz, String fieldName) {
try {
Field field = clazz.getDeclaredField(fieldName);
return new FieldSetter<T>(field);
} catch (NoSuchFieldException e) {
throw new AssertionError(e); // programmer error
}
}
// Secret sauce for setting final fields; don't make it public.
static final class FieldSetter<T> {
private final Field field;
private FieldSetter(Field field) {
this.field = field;
field.setAccessible(true);
}
void set(T instance, Object value) {
try {
field.set(instance, value);
} catch (IllegalAccessException impossible) {
throw new AssertionError(impossible);
}
}
void set(T instance, int value) {
try {
field.set(instance, value);
} catch (IllegalAccessException impossible) {
throw new AssertionError(impossible);
}
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
* Indicates whether an endpoint of some range is contained in the range itself ("closed") or not
* ("open"). If a range is unbounded on a side, it is neither open nor closed on that side; the
* bound simply does not exist.
*
* @since 10.0
*/
@Beta
@GwtCompatible
public enum BoundType {
/**
* The endpoint value <i>is not</i> considered part of the set ("exclusive").
*/
OPEN,
/**
* The endpoint value <i>is</i> considered part of the set ("inclusive").
*/
CLOSED;
/**
* Returns the bound type corresponding to a boolean value for inclusivity.
*/
static BoundType forBoolean(boolean inclusive) {
return inclusive ? CLOSED : OPEN;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Comparator;
import javax.annotation.Nullable;
/**
* An empty immutable sorted multiset.
*
* @author Louis Wasserman
*/
final class EmptyImmutableSortedMultiset<E> extends ImmutableSortedMultiset<E> {
EmptyImmutableSortedMultiset(Comparator<? super E> comparator) {
super(comparator);
}
@Override
public Entry<E> firstEntry() {
return null;
}
@Override
public Entry<E> lastEntry() {
return null;
}
@Override
public int count(@Nullable Object element) {
return 0;
}
@Override
public int size() {
return 0;
}
@Override
ImmutableSortedSet<E> createElementSet() {
return ImmutableSortedSet.emptySet(comparator());
}
@Override
ImmutableSortedSet<E> createDescendingElementSet() {
return ImmutableSortedSet.emptySet(reverseComparator());
}
@Override
UnmodifiableIterator<Entry<E>> descendingEntryIterator() {
return Iterators.emptyIterator();
}
@Override
UnmodifiableIterator<Entry<E>> entryIterator() {
return Iterators.emptyIterator();
}
@Override
public ImmutableSortedMultiset<E> headMultiset(E upperBound, BoundType boundType) {
checkNotNull(upperBound);
checkNotNull(boundType);
return this;
}
@Override
public ImmutableSortedMultiset<E> tailMultiset(E lowerBound, BoundType boundType) {
checkNotNull(lowerBound);
checkNotNull(boundType);
return this;
}
@Override
int distinctElements() {
return 0;
}
@Override
boolean isPartialView() {
return false;
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.SortedLists.KeyAbsentBehavior.INVERTED_INSERTION_INDEX;
import static com.google.common.collect.SortedLists.KeyAbsentBehavior.NEXT_HIGHER;
import static com.google.common.collect.SortedLists.KeyAbsentBehavior.NEXT_LOWER;
import static com.google.common.collect.SortedLists.KeyPresentBehavior.ANY_PRESENT;
import com.google.common.annotations.GwtCompatible;
import com.google.common.collect.SortedLists.KeyAbsentBehavior;
import com.google.common.collect.SortedLists.KeyPresentBehavior;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.annotation.Nullable;
/**
* An immutable {@link SortedMap}. Does not permit null keys or values.
*
* <p>Unlike {@link Collections#unmodifiableSortedMap}, which is a <i>view</i>
* of a separate map which can still change, an instance of {@code
* ImmutableSortedMap} contains its own data and will <i>never</i> change.
* {@code ImmutableSortedMap} is convenient for {@code public static final} maps
* ("constant maps") and also lets you easily make a "defensive copy" of a map
* provided to your class by a caller.
*
* <p><b>Note:</b> Although this class is not final, it cannot be subclassed as
* it has no public or protected constructors. Thus, instances of this class are
* guaranteed to be immutable.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ImmutableCollectionsExplained">
* immutable collections</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(serializable = true, emulated = true)
public class ImmutableSortedMap<K, V>
extends ImmutableSortedMapFauxverideShim<K, V> implements SortedMap<K, V> {
/*
* TODO(kevinb): Confirm that ImmutableSortedMap is faster to construct and
* uses less memory than TreeMap; then say so in the class Javadoc.
*
* TODO(kevinb): Create separate subclasses for empty, single-entry, and
* multiple-entry instances, if it's deemed beneficial.
*/
private static final Comparator<Comparable> NATURAL_ORDER =
Ordering.natural();
private static final ImmutableSortedMap<Comparable, Object>
NATURAL_EMPTY_MAP =
new ImmutableSortedMap<Comparable, Object>(
ImmutableList.<Entry<Comparable, Object>>of(), NATURAL_ORDER);
/**
* Returns the empty sorted map.
*/
@SuppressWarnings("unchecked")
// unsafe, comparator() returns a comparator on the specified type
// TODO(kevinb): evaluate whether or not of().comparator() should return null
public static <K, V> ImmutableSortedMap<K, V> of() {
return (ImmutableSortedMap<K, V>) NATURAL_EMPTY_MAP;
}
@SuppressWarnings("unchecked")
private static <K, V> ImmutableSortedMap<K, V> emptyMap(
Comparator<? super K> comparator) {
if (NATURAL_ORDER.equals(comparator)) {
return (ImmutableSortedMap<K, V>) NATURAL_EMPTY_MAP;
} else {
return new ImmutableSortedMap<K, V>(
ImmutableList.<Entry<K, V>>of(), comparator);
}
}
/**
* Returns an immutable map containing a single entry.
*/
public static <K extends Comparable<? super K>, V>
ImmutableSortedMap<K, V> of(K k1, V v1) {
return new ImmutableSortedMap<K, V>(
ImmutableList.of(entryOf(k1, v1)), Ordering.natural());
}
/**
* Returns an immutable sorted map containing the given entries, sorted by the
* natural ordering of their keys.
*
* @throws IllegalArgumentException if the two keys are equal according to
* their natural ordering
*/
public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V>
of(K k1, V v1, K k2, V v2) {
return new Builder<K, V>(Ordering.natural())
.put(k1, v1).put(k2, v2).build();
}
/**
* Returns an immutable sorted map containing the given entries, sorted by the
* natural ordering of their keys.
*
* @throws IllegalArgumentException if any two keys are equal according to
* their natural ordering
*/
public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V>
of(K k1, V v1, K k2, V v2, K k3, V v3) {
return new Builder<K, V>(Ordering.natural())
.put(k1, v1).put(k2, v2).put(k3, v3).build();
}
/**
* Returns an immutable sorted map containing the given entries, sorted by the
* natural ordering of their keys.
*
* @throws IllegalArgumentException if any two keys are equal according to
* their natural ordering
*/
public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V>
of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
return new Builder<K, V>(Ordering.natural())
.put(k1, v1).put(k2, v2).put(k3, v3).put(k4, v4).build();
}
/**
* Returns an immutable sorted map containing the given entries, sorted by the
* natural ordering of their keys.
*
* @throws IllegalArgumentException if any two keys are equal according to
* their natural ordering
*/
public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V>
of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
return new Builder<K, V>(Ordering.natural())
.put(k1, v1).put(k2, v2).put(k3, v3).put(k4, v4).put(k5, v5).build();
}
/**
* Returns an immutable map containing the same entries as {@code map}, sorted
* by the natural ordering of the keys.
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*
* <p>This method is not type-safe, as it may be called on a map with keys
* that are not mutually comparable.
*
* @throws ClassCastException if the keys in {@code map} are not mutually
* comparable
* @throws NullPointerException if any key or value in {@code map} is null
* @throws IllegalArgumentException if any two keys are equal according to
* their natural ordering
*/
public static <K, V> ImmutableSortedMap<K, V> copyOf(
Map<? extends K, ? extends V> map) {
// Hack around K not being a subtype of Comparable.
// Unsafe, see ImmutableSortedSetFauxverideShim.
@SuppressWarnings("unchecked")
Ordering<K> naturalOrder = (Ordering<K>) Ordering.<Comparable>natural();
return copyOfInternal(map, naturalOrder);
}
/**
* Returns an immutable map containing the same entries as {@code map}, with
* keys sorted by the provided comparator.
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*
* @throws NullPointerException if any key or value in {@code map} is null
* @throws IllegalArgumentException if any two keys are equal according to the
* comparator
*/
public static <K, V> ImmutableSortedMap<K, V> copyOf(
Map<? extends K, ? extends V> map, Comparator<? super K> comparator) {
return copyOfInternal(map, checkNotNull(comparator));
}
/**
* Returns an immutable map containing the same entries as the provided sorted
* map, with the same ordering.
*
* <p>Despite the method name, this method attempts to avoid actually copying
* the data when it is safe to do so. The exact circumstances under which a
* copy will or will not be performed are undocumented and subject to change.
*
* @throws NullPointerException if any key or value in {@code map} is null
*/
@SuppressWarnings("unchecked")
public static <K, V> ImmutableSortedMap<K, V> copyOfSorted(
SortedMap<K, ? extends V> map) {
Comparator<? super K> comparator = map.comparator();
if (comparator == null) {
// If map has a null comparator, the keys should have a natural ordering,
// even though K doesn't explicitly implement Comparable.
comparator = (Comparator<? super K>) NATURAL_ORDER;
}
return copyOfInternal(map, comparator);
}
private static <K, V> ImmutableSortedMap<K, V> copyOfInternal(
Map<? extends K, ? extends V> map, Comparator<? super K> comparator) {
boolean sameComparator = false;
if (map instanceof SortedMap) {
SortedMap<?, ?> sortedMap = (SortedMap<?, ?>) map;
Comparator<?> comparator2 = sortedMap.comparator();
sameComparator = (comparator2 == null)
? comparator == NATURAL_ORDER
: comparator.equals(comparator2);
}
if (sameComparator && (map instanceof ImmutableSortedMap)) {
// TODO(kevinb): Prove that this cast is safe, even though
// Collections.unmodifiableSortedMap requires the same key type.
@SuppressWarnings("unchecked")
ImmutableSortedMap<K, V> kvMap = (ImmutableSortedMap<K, V>) map;
if (!kvMap.isPartialView()) {
return kvMap;
}
}
// "adding" type params to an array of a raw type should be safe as
// long as no one can ever cast that same array instance back to a
// raw type.
@SuppressWarnings("unchecked")
Entry<K, V>[] entries = map.entrySet().toArray(new Entry[0]);
for (int i = 0; i < entries.length; i++) {
Entry<K, V> entry = entries[i];
entries[i] = entryOf(entry.getKey(), entry.getValue());
}
List<Entry<K, V>> list = Arrays.asList(entries);
if (!sameComparator) {
sortEntries(list, comparator);
validateEntries(list, comparator);
}
return new ImmutableSortedMap<K, V>(ImmutableList.copyOf(list), comparator);
}
private static <K, V> void sortEntries(
List<Entry<K, V>> entries, final Comparator<? super K> comparator) {
Comparator<Entry<K, V>> entryComparator = new Comparator<Entry<K, V>>() {
@Override public int compare(Entry<K, V> entry1, Entry<K, V> entry2) {
return comparator.compare(entry1.getKey(), entry2.getKey());
}
};
Collections.sort(entries, entryComparator);
}
private static <K, V> void validateEntries(List<Entry<K, V>> entries,
Comparator<? super K> comparator) {
for (int i = 1; i < entries.size(); i++) {
if (comparator.compare(
entries.get(i - 1).getKey(), entries.get(i).getKey()) == 0) {
throw new IllegalArgumentException(
"Duplicate keys in mappings " + entries.get(i - 1) + " and "
+ entries.get(i));
}
}
}
/**
* Returns a builder that creates immutable sorted maps whose keys are
* ordered by their natural ordering. The sorted maps use {@link
* Ordering#natural()} as the comparator.
*
* <p>Note: the type parameter {@code K} extends {@code Comparable<K>} rather
* than {@code Comparable<? super K>} as a workaround for javac <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug
* 6468354</a>.
*/
public static <K extends Comparable<K>, V> Builder<K, V> naturalOrder() {
return new Builder<K, V>(Ordering.natural());
}
/**
* Returns a builder that creates immutable sorted maps with an explicit
* comparator. If the comparator has a more general type than the map's keys,
* such as creating a {@code SortedMap<Integer, String>} with a {@code
* Comparator<Number>}, use the {@link Builder} constructor instead.
*
* @throws NullPointerException if {@code comparator} is null
*/
public static <K, V> Builder<K, V> orderedBy(Comparator<K> comparator) {
return new Builder<K, V>(comparator);
}
/**
* Returns a builder that creates immutable sorted maps whose keys are
* ordered by the reverse of their natural ordering.
*
* <p>Note: the type parameter {@code K} extends {@code Comparable<K>} rather
* than {@code Comparable<? super K>} as a workaround for javac <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6468354">bug
* 6468354</a>.
*/
public static <K extends Comparable<K>, V> Builder<K, V> reverseOrder() {
return new Builder<K, V>(Ordering.natural().reverse());
}
/**
* A builder for creating immutable sorted map instances, especially {@code
* public static final} maps ("constant maps"). Example: <pre> {@code
*
* static final ImmutableSortedMap<Integer, String> INT_TO_WORD =
* new ImmutableSortedMap.Builder<Integer, String>(Ordering.natural())
* .put(1, "one")
* .put(2, "two")
* .put(3, "three")
* .build();}</pre>
*
* For <i>small</i> immutable sorted maps, the {@code ImmutableSortedMap.of()}
* methods are even more convenient.
*
* <p>Builder instances can be reused - it is safe to call {@link #build}
* multiple times to build multiple maps in series. Each map is a superset of
* the maps created before it.
*
* @since 2.0 (imported from Google Collections Library)
*/
public static class Builder<K, V> extends ImmutableMap.Builder<K, V> {
private final Comparator<? super K> comparator;
/**
* Creates a new builder. The returned builder is equivalent to the builder
* generated by {@link ImmutableSortedMap#orderedBy}.
*/
public Builder(Comparator<? super K> comparator) {
this.comparator = checkNotNull(comparator);
}
/**
* Associates {@code key} with {@code value} in the built map. Duplicate
* keys, according to the comparator (which might be the keys' natural
* order), are not allowed, and will cause {@link #build} to fail.
*/
@Override public Builder<K, V> put(K key, V value) {
entries.add(entryOf(key, value));
return this;
}
/**
* Adds the given {@code entry} to the map, making it immutable if
* necessary. Duplicate keys, according to the comparator (which might be
* the keys' natural order), are not allowed, and will cause {@link #build}
* to fail.
*
* @since 11.0
*/
@Override public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
super.put(entry);
return this;
}
/**
* Associates all of the given map's keys and values in the built map.
* Duplicate keys, according to the comparator (which might be the keys'
* natural order), are not allowed, and will cause {@link #build} to fail.
*
* @throws NullPointerException if any key or value in {@code map} is null
*/
@Override public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
return this;
}
/**
* Returns a newly-created immutable sorted map.
*
* @throws IllegalArgumentException if any two keys are equal according to
* the comparator (which might be the keys' natural order)
*/
@Override public ImmutableSortedMap<K, V> build() {
sortEntries(entries, comparator);
validateEntries(entries, comparator);
return new ImmutableSortedMap<K, V>(
ImmutableList.copyOf(entries), comparator);
}
}
final transient ImmutableList<Entry<K, V>> entries;
private final transient Comparator<? super K> comparator;
ImmutableSortedMap(
ImmutableList<Entry<K, V>> entries, Comparator<? super K> comparator) {
this.entries = entries;
this.comparator = comparator;
}
@Override
public int size() {
return entries.size();
}
// Pretend the comparator can compare anything. If it turns out it can't
// compare two elements, it'll throw a CCE. Only methods that are specified to
// throw CCE should call this.
@SuppressWarnings("unchecked")
Comparator<Object> unsafeComparator() {
return (Comparator<Object>) comparator;
}
@Override public V get(@Nullable Object key) {
if (key == null) {
return null;
}
int i;
try {
i = index(key, ANY_PRESENT, INVERTED_INSERTION_INDEX);
} catch (ClassCastException e) {
return null;
}
return i >= 0 ? entries.get(i).getValue() : null;
}
@Override public boolean containsValue(@Nullable Object value) {
if (value == null) {
return false;
}
return Iterators.contains(valueIterator(), value);
}
@Override boolean isPartialView() {
return entries.isPartialView();
}
private transient ImmutableSet<Entry<K, V>> entrySet;
/**
* Returns an immutable set of the mappings in this map, sorted by the key
* ordering.
*/
@Override public ImmutableSet<Entry<K, V>> entrySet() {
ImmutableSet<Entry<K, V>> es = entrySet;
return (es == null) ? (entrySet = createEntrySet()) : es;
}
private ImmutableSet<Entry<K, V>> createEntrySet() {
return isEmpty() ? ImmutableSet.<Entry<K, V>>of()
: new EntrySet<K, V>(this);
}
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
private static class EntrySet<K, V> extends ImmutableSet<Entry<K, V>> {
final transient ImmutableSortedMap<K, V> map;
EntrySet(ImmutableSortedMap<K, V> map) {
this.map = map;
}
@Override boolean isPartialView() {
return map.isPartialView();
}
@Override
public int size() {
return map.size();
}
@Override public UnmodifiableIterator<Entry<K, V>> iterator() {
return map.entries.iterator();
}
@Override public boolean contains(Object target) {
if (target instanceof Entry) {
Entry<?, ?> entry = (Entry<?, ?>) target;
V mappedValue = map.get(entry.getKey());
return mappedValue != null && mappedValue.equals(entry.getValue());
}
return false;
}
@Override Object writeReplace() {
return new EntrySetSerializedForm<K, V>(map);
}
}
private static class EntrySetSerializedForm<K, V> implements Serializable {
final ImmutableSortedMap<K, V> map;
EntrySetSerializedForm(ImmutableSortedMap<K, V> map) {
this.map = map;
}
Object readResolve() {
return map.entrySet();
}
private static final long serialVersionUID = 0;
}
private transient ImmutableSortedSet<K> keySet;
/**
* Returns an immutable sorted set of the keys in this map.
*/
@Override public ImmutableSortedSet<K> keySet() {
ImmutableSortedSet<K> ks = keySet;
return (ks == null) ? (keySet = createKeySet()) : ks;
}
@SuppressWarnings("serial") // does not use default serialization
private ImmutableSortedSet<K> createKeySet() {
if (isEmpty()) {
return ImmutableSortedSet.emptySet(comparator);
}
return new RegularImmutableSortedSet<K>(
new TransformedImmutableList<Entry<K, V>, K>(entries) {
@Override K transform(Entry<K, V> entry) {
return entry.getKey();
}
}, comparator);
}
private transient ImmutableCollection<V> values;
/**
* Returns an immutable collection of the values in this map, sorted by the
* ordering of the corresponding keys.
*/
@Override public ImmutableCollection<V> values() {
ImmutableCollection<V> v = values;
return (v == null) ? (values = new Values<V>(this)) : v;
}
UnmodifiableIterator<V> valueIterator(){
final UnmodifiableIterator<Entry<K, V>> entryIterator = entries.iterator();
return new UnmodifiableIterator<V>() {
@Override public boolean hasNext() {
return entryIterator.hasNext();
}
@Override public V next() {
return entryIterator.next().getValue();
}
};
}
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
private static class Values<V> extends ImmutableCollection<V> {
private final ImmutableSortedMap<?, V> map;
Values(ImmutableSortedMap<?, V> map) {
this.map = map;
}
@Override
public int size() {
return map.size();
}
@Override public UnmodifiableIterator<V> iterator() {
return map.valueIterator();
}
@Override public boolean contains(Object target) {
return map.containsValue(target);
}
@Override boolean isPartialView() {
return true;
}
@Override Object writeReplace() {
return new ValuesSerializedForm<V>(map);
}
}
private static class ValuesSerializedForm<V> implements Serializable {
final ImmutableSortedMap<?, V> map;
ValuesSerializedForm(ImmutableSortedMap<?, V> map) {
this.map = map;
}
Object readResolve() {
return map.values();
}
private static final long serialVersionUID = 0;
}
/**
* Returns the comparator that orders the keys, which is
* {@link Ordering#natural()} when the natural ordering of the keys is used.
* Note that its behavior is not consistent with {@link TreeMap#comparator()},
* which returns {@code null} to indicate natural ordering.
*/
@Override
public Comparator<? super K> comparator() {
return comparator;
}
@Override
public K firstKey() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return entries.get(0).getKey();
}
@Override
public K lastKey() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return entries.get(size() - 1).getKey();
}
/**
* This method returns a {@code ImmutableSortedMap}, consisting of the entries
* whose keys are less than {@code toKey}.
*
* <p>The {@link SortedMap#headMap} documentation states that a submap of a
* submap throws an {@link IllegalArgumentException} if passed a {@code toKey}
* greater than an earlier {@code toKey}. However, this method doesn't throw
* an exception in that situation, but instead keeps the original {@code
* toKey}.
*/
@Override
public ImmutableSortedMap<K, V> headMap(K toKey) {
return headMap(toKey, false);
}
ImmutableSortedMap<K, V> headMap(K toKey, boolean inclusive){
int index;
if (inclusive) {
index = index(toKey, ANY_PRESENT, NEXT_LOWER) + 1;
} else {
index = index(toKey, ANY_PRESENT, NEXT_HIGHER);
}
return createSubmap(0, index);
}
/**
* This method returns a {@code ImmutableSortedMap}, consisting of the entries
* whose keys ranges from {@code fromKey}, inclusive, to {@code toKey},
* exclusive.
*
* <p>The {@link SortedMap#subMap} documentation states that a submap of a
* submap throws an {@link IllegalArgumentException} if passed a {@code
* fromKey} less than an earlier {@code fromKey}. However, this method doesn't
* throw an exception in that situation, but instead keeps the original {@code
* fromKey}. Similarly, this method keeps the original {@code toKey}, instead
* of throwing an exception, if passed a {@code toKey} greater than an earlier
* {@code toKey}.
*/
@Override
public ImmutableSortedMap<K, V> subMap(K fromKey, K toKey) {
return subMap(fromKey, true, toKey, false);
}
ImmutableSortedMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey,
boolean toInclusive) {
checkNotNull(fromKey);
checkNotNull(toKey);
checkArgument(comparator.compare(fromKey, toKey) <= 0);
return tailMap(fromKey, fromInclusive).headMap(toKey, toInclusive);
}
/**
* This method returns a {@code ImmutableSortedMap}, consisting of the entries
* whose keys are greater than or equals to {@code fromKey}.
*
* <p>The {@link SortedMap#tailMap} documentation states that a submap of a
* submap throws an {@link IllegalArgumentException} if passed a {@code
* fromKey} less than an earlier {@code fromKey}. However, this method doesn't
* throw an exception in that situation, but instead keeps the original {@code
* fromKey}.
*/
@Override
public ImmutableSortedMap<K, V> tailMap(K fromKey) {
return tailMap(fromKey, true);
}
ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive) {
int index;
if (inclusive) {
index = index(fromKey, ANY_PRESENT, NEXT_HIGHER);
} else {
index = index(fromKey, ANY_PRESENT, NEXT_LOWER) + 1;
}
return createSubmap(index, size());
}
private ImmutableList<K> keyList() {
return new TransformedImmutableList<Entry<K, V>, K>(entries) {
@Override
K transform(Entry<K, V> entry) {
return entry.getKey();
}
};
}
private int index(
Object key, KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) {
return SortedLists.binarySearch(
keyList(), checkNotNull(key), unsafeComparator(), presentBehavior, absentBehavior);
}
private ImmutableSortedMap<K, V> createSubmap(
int newFromIndex, int newToIndex) {
if (newFromIndex < newToIndex) {
return new ImmutableSortedMap<K, V>(
entries.subList(newFromIndex, newToIndex), comparator);
} else {
return emptyMap(comparator);
}
}
/**
* Serialized type for all ImmutableSortedMap instances. It captures the
* logical contents and they are reconstructed using public factory methods.
* This ensures that the implementation types remain as implementation
* details.
*/
private static class SerializedForm extends ImmutableMap.SerializedForm {
private final Comparator<Object> comparator;
@SuppressWarnings("unchecked")
SerializedForm(ImmutableSortedMap<?, ?> sortedMap) {
super(sortedMap);
comparator = (Comparator<Object>) sortedMap.comparator();
}
@Override Object readResolve() {
Builder<Object, Object> builder = new Builder<Object, Object>(comparator);
return createMap(builder);
}
private static final long serialVersionUID = 0;
}
@Override Object writeReplace() {
return new SerializedForm(this);
}
// This class is never actually serialized directly, but we have to make the
// warning go away (and suppressing would suppress for all nested classes too)
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.NoSuchElementException;
/**
* A descriptor for a <i>discrete</i> {@code Comparable} domain such as all
* {@link Integer}s. A discrete domain is one that supports the three basic
* operations: {@link #next}, {@link #previous} and {@link #distance}, according
* to their specifications. The methods {@link #minValue} and {@link #maxValue}
* should also be overridden for bounded types.
*
* <p>A discrete domain always represents the <i>entire</i> set of values of its
* type; it cannot represent partial domains such as "prime integers" or
* "strings of length 5."
*
* <p>See the Guava User Guide section on <a href=
* "http://code.google.com/p/guava-libraries/wiki/RangesExplained#Discrete_Domains">
* {@code DiscreteDomain}</a>.
*
* @author Kevin Bourrillion
* @since 10.0
* @see DiscreteDomains
*/
@GwtCompatible
@Beta
public abstract class DiscreteDomain<C extends Comparable> {
/** Constructor for use by subclasses. */
protected DiscreteDomain() {}
/**
* Returns the unique least value of type {@code C} that is greater than
* {@code value}, or {@code null} if none exists. Inverse operation to {@link
* #previous}.
*
* @param value any value of type {@code C}
* @return the least value greater than {@code value}, or {@code null} if
* {@code value} is {@code maxValue()}
*/
public abstract C next(C value);
/**
* Returns the unique greatest value of type {@code C} that is less than
* {@code value}, or {@code null} if none exists. Inverse operation to {@link
* #next}.
*
* @param value any value of type {@code C}
* @return the greatest value less than {@code value}, or {@code null} if
* {@code value} is {@code minValue()}
*/
public abstract C previous(C value);
/**
* Returns a signed value indicating how many nested invocations of {@link
* #next} (if positive) or {@link #previous} (if negative) are needed to reach
* {@code end} starting from {@code start}. For example, if {@code end =
* next(next(next(start)))}, then {@code distance(start, end) == 3} and {@code
* distance(end, start) == -3}. As well, {@code distance(a, a)} is always
* zero.
*
* <p>Note that this function is necessarily well-defined for any discrete
* type.
*
* @return the distance as described above, or {@link Long#MIN_VALUE} or
* {@link Long#MIN_VALUE} if the distance is too small or too large,
* respectively.
*/
public abstract long distance(C start, C end);
/**
* Returns the minimum value of type {@code C}, if it has one. The minimum
* value is the unique value for which {@link Comparable#compareTo(Object)}
* never returns a positive value for any input of type {@code C}.
*
* <p>The default implementation throws {@code NoSuchElementException}.
*
* @return the minimum value of type {@code C}; never null
* @throws NoSuchElementException if the type has no (practical) minimum
* value; for example, {@link java.math.BigInteger}
*/
public C minValue() {
throw new NoSuchElementException();
}
/**
* Returns the maximum value of type {@code C}, if it has one. The maximum
* value is the unique value for which {@link Comparable#compareTo(Object)}
* never returns a negative value for any input of type {@code C}.
*
* <p>The default implementation throws {@code NoSuchElementException}.
*
* @return the maximum value of type {@code C}; never null
* @throws NoSuchElementException if the type has no (practical) maximum
* value; for example, {@link java.math.BigInteger}
*/
public C maxValue() {
throw new NoSuchElementException();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.Iterator;
import javax.annotation.Nullable;
/** An ordering that uses the reverse of a given order. */
@GwtCompatible(serializable = true)
final class ReverseOrdering<T> extends Ordering<T> implements Serializable {
final Ordering<? super T> forwardOrder;
ReverseOrdering(Ordering<? super T> forwardOrder) {
this.forwardOrder = checkNotNull(forwardOrder);
}
@Override public int compare(T a, T b) {
return forwardOrder.compare(b, a);
}
@SuppressWarnings("unchecked") // how to explain?
@Override public <S extends T> Ordering<S> reverse() {
return (Ordering<S>) forwardOrder;
}
// Override the min/max methods to "hoist" delegation outside loops
@Override public <E extends T> E min(E a, E b) {
return forwardOrder.max(a, b);
}
@Override public <E extends T> E min(E a, E b, E c, E... rest) {
return forwardOrder.max(a, b, c, rest);
}
@Override public <E extends T> E min(Iterator<E> iterator) {
return forwardOrder.max(iterator);
}
@Override public <E extends T> E min(Iterable<E> iterable) {
return forwardOrder.max(iterable);
}
@Override public <E extends T> E max(E a, E b) {
return forwardOrder.min(a, b);
}
@Override public <E extends T> E max(E a, E b, E c, E... rest) {
return forwardOrder.min(a, b, c, rest);
}
@Override public <E extends T> E max(Iterator<E> iterator) {
return forwardOrder.min(iterator);
}
@Override public <E extends T> E max(Iterable<E> iterable) {
return forwardOrder.min(iterable);
}
@Override public int hashCode() {
return -forwardOrder.hashCode();
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof ReverseOrdering) {
ReverseOrdering<?> that = (ReverseOrdering<?>) object;
return this.forwardOrder.equals(that.forwardOrder);
}
return false;
}
@Override public String toString() {
return forwardOrder + ".reverse()";
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.primitives.Booleans;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import java.util.Comparator;
import javax.annotation.Nullable;
/**
* A utility for performing a "lazy" chained comparison statement, which
* performs comparisons only until it finds a nonzero result. For example:
* <pre> {@code
*
* public int compareTo(Foo that) {
* return ComparisonChain.start()
* .compare(this.aString, that.aString)
* .compare(this.anInt, that.anInt)
* .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast())
* .result();
* }}</pre>
*
* The value of this expression will have the same sign as the <i>first
* nonzero</i> comparison result in the chain, or will be zero if every
* comparison result was zero.
*
* <p>Once any comparison returns a nonzero value, remaining comparisons are
* "short-circuited".
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained#compare/compareTo">
* {@code ComparisonChain}</a>.
*
* @author Mark Davis
* @author Kevin Bourrillion
* @since 2.0
*/
@GwtCompatible
public abstract class ComparisonChain {
private ComparisonChain() {}
/**
* Begins a new chained comparison statement. See example in the class
* documentation.
*/
public static ComparisonChain start() {
return ACTIVE;
}
private static final ComparisonChain ACTIVE = new ComparisonChain() {
@SuppressWarnings("unchecked")
@Override public ComparisonChain compare(
Comparable left, Comparable right) {
return classify(left.compareTo(right));
}
@Override public <T> ComparisonChain compare(
@Nullable T left, @Nullable T right, Comparator<T> comparator) {
return classify(comparator.compare(left, right));
}
@Override public ComparisonChain compare(int left, int right) {
return classify(Ints.compare(left, right));
}
@Override public ComparisonChain compare(long left, long right) {
return classify(Longs.compare(left, right));
}
@Override public ComparisonChain compare(float left, float right) {
return classify(Float.compare(left, right));
}
@Override public ComparisonChain compare(double left, double right) {
return classify(Double.compare(left, right));
}
@Override public ComparisonChain compare(boolean left, boolean right) {
return classify(Booleans.compare(left, right));
}
ComparisonChain classify(int result) {
return (result < 0) ? LESS : (result > 0) ? GREATER : ACTIVE;
}
@Override public int result() {
return 0;
}
};
private static final ComparisonChain LESS = new InactiveComparisonChain(-1);
private static final ComparisonChain GREATER = new InactiveComparisonChain(1);
private static final class InactiveComparisonChain extends ComparisonChain {
final int result;
InactiveComparisonChain(int result) {
this.result = result;
}
@Override public ComparisonChain compare(
@Nullable Comparable left, @Nullable Comparable right) {
return this;
}
@Override public <T> ComparisonChain compare(@Nullable T left,
@Nullable T right, @Nullable Comparator<T> comparator) {
return this;
}
@Override public ComparisonChain compare(int left, int right) {
return this;
}
@Override public ComparisonChain compare(long left, long right) {
return this;
}
@Override public ComparisonChain compare(float left, float right) {
return this;
}
@Override public ComparisonChain compare(double left, double right) {
return this;
}
@Override public ComparisonChain compare(boolean left, boolean right) {
return this;
}
@Override public int result() {
return result;
}
}
/**
* Compares two comparable objects as specified by {@link
* Comparable#compareTo}, <i>if</i> the result of this comparison chain
* has not already been determined.
*/
public abstract ComparisonChain compare(
Comparable<?> left, Comparable<?> right);
/**
* Compares two objects using a comparator, <i>if</i> the result of this
* comparison chain has not already been determined.
*/
public abstract <T> ComparisonChain compare(
@Nullable T left, @Nullable T right, Comparator<T> comparator);
/**
* Compares two {@code int} values as specified by {@link Ints#compare},
* <i>if</i> the result of this comparison chain has not already been
* determined.
*/
public abstract ComparisonChain compare(int left, int right);
/**
* Compares two {@code long} values as specified by {@link Longs#compare},
* <i>if</i> the result of this comparison chain has not already been
* determined.
*/
public abstract ComparisonChain compare(long left, long right);
/**
* Compares two {@code float} values as specified by {@link
* Float#compare}, <i>if</i> the result of this comparison chain has not
* already been determined.
*/
public abstract ComparisonChain compare(float left, float right);
/**
* Compares two {@code double} values as specified by {@link
* Double#compare}, <i>if</i> the result of this comparison chain has not
* already been determined.
*/
public abstract ComparisonChain compare(double left, double right);
/**
* Compares two {@code boolean} values as specified by {@link
* Booleans#compare}, <i>if</i> the result of this comparison chain has not
* already been determined.
*/
public abstract ComparisonChain compare(boolean left, boolean right);
/**
* Ends this comparison chain and returns its result: a value having the
* same sign as the first nonzero comparison result in the chain, or zero if
* every result was zero.
*/
public abstract int result();
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.collect;
/**
* Wraps an exception that occurred during a computation in a different thread.
*
* @author Bob Lee
* @since 2.0 (imported from Google Collections Library)
* @deprecated this class is unused by com.google.common.collect. <b>This class
* is scheduled for deletion in November 2012.</b>
*/
@Deprecated
public
class AsynchronousComputationException extends ComputationException {
/**
* Creates a new instance with the given cause.
*/
public AsynchronousComputationException(Throwable cause) {
super(cause);
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The presence of this annotation on a type indicates that the type may be
* used with the
* <a href="http://code.google.com/webtoolkit/">Google Web Toolkit</a> (GWT).
* When applied to a method, the return type of the method is GWT compatible.
* It's useful to indicate that an instance created by factory methods has a GWT
* serializable type. In the following example,
*
* <pre style="code">
* {@literal @}GwtCompatible
* class Lists {
* ...
* {@literal @}GwtCompatible(serializable = true)
* static <E> List<E> newArrayList(E... elements) {
* ...
* }
* }
* </pre>
* The return value of {@code Lists.newArrayList(E[])} has GWT
* serializable type. It is also useful in specifying contracts of interface
* methods. In the following example,
*
* <pre style="code">
* {@literal @}GwtCompatible
* interface ListFactory {
* ...
* {@literal @}GwtCompatible(serializable = true)
* <E> List<E> newArrayList(E... elements);
* }
* </pre>
* The {@code newArrayList(E[])} method of all implementations of {@code
* ListFactory} is expected to return a value with a GWT serializable type.
*
* <p>Note that a {@code GwtCompatible} type may have some {@link
* GwtIncompatible} methods.
*
* @author Charles Fry
* @author Hayward Chan
*/
@Retention(RetentionPolicy.CLASS)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@GwtCompatible
public @interface GwtCompatible {
/**
* When {@code true}, the annotated type or the type of the method return
* value is GWT serializable.
*
* @see <a href="http://code.google.com/webtoolkit/doc/latest/DevGuideServerCommunication.html#DevGuideSerializableTypes">
* Documentation about GWT serialization</a>
*/
boolean serializable() default false;
/**
* When {@code true}, the annotated type is emulated in GWT. The emulated
* source (also known as super-source) is different from the implementation
* used by the JVM.
*
* @see <a href="http://code.google.com/webtoolkit/doc/latest/DevGuideOrganizingProjects.html#DevGuideModules">
* Documentation about GWT emulated source</a>
*/
boolean emulated() default false;
}
| Java |
/*
* Copyright (C) 2006 The Guava Authors
*
* 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.google.common.annotations;
/**
* An annotation that indicates that the visibility of a type or member has
* been relaxed to make the code testable.
*
* @author Johannes Henkel
*/
@GwtCompatible
public @interface VisibleForTesting {
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* 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.
*/
/**
* Common annotation types. This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*/
package com.google.common.annotations;
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The presence of this annotation on a method indicates that the method may
* <em>not</em> be used with the
* <a href="http://code.google.com/webtoolkit/">Google Web Toolkit</a> (GWT),
* even though its type is annotated as {@link GwtCompatible} and accessible in
* GWT. They can cause GWT compilation errors or simply unexpected exceptions
* when used in GWT.
*
* <p>Note that this annotation should only be applied to methods, fields, or
* inner classes of types which are annotated as {@link GwtCompatible}.
*
* @author Charles Fry
*/
@Retention(RetentionPolicy.CLASS)
@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD })
@Documented
@GwtCompatible
public @interface GwtIncompatible {
/**
* Describes why the annotated element is incompatible with GWT. Since this is
* generally due to a dependence on a type/method which GWT doesn't support,
* it is sufficient to simply reference the unsupported type/method. E.g.
* "Class.isInstance".
*/
String value();
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* 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.google.common.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Signifies that a public API (public class, method or field) is subject to
* incompatible changes, or even removal, in a future release. An API bearing
* this annotation is exempt from any compatibility guarantees made by its
* containing library.
*
* @author Kevin Bourrillion
*/
@Retention(RetentionPolicy.CLASS)
@Target({
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.METHOD,
ElementType.TYPE})
@Documented
@GwtCompatible
@Beta
public @interface Beta {}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.base.Preconditions;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
/**
* Skeleton implementation of {@link HashFunction}. Provides default implementations which
* invokes the appropriate method on {@link #newHasher()}, then return the result of
* {@link Hasher#hash}.
*
* <p>Invocations of {@link #newHasher(int)} also delegate to {@linkplain #newHasher()}, ignoring
* the expected input size parameter.
*
* @author Kevin Bourrillion
*/
abstract class AbstractStreamingHashFunction implements HashFunction {
@Override public HashCode hashString(CharSequence input) {
return newHasher().putString(input).hash();
}
@Override public HashCode hashString(CharSequence input, Charset charset) {
return newHasher().putString(input, charset).hash();
}
@Override public HashCode hashLong(long input) {
return newHasher().putLong(input).hash();
}
@Override public HashCode hashBytes(byte[] input) {
return newHasher().putBytes(input).hash();
}
@Override public HashCode hashBytes(byte[] input, int off, int len) {
return newHasher().putBytes(input, off, len).hash();
}
@Override public Hasher newHasher(int expectedInputSize) {
Preconditions.checkArgument(expectedInputSize >= 0);
return newHasher();
}
/**
* A convenience base class for implementors of {@code Hasher}; handles accumulating data
* until an entire "chunk" (of implementation-dependent length) is ready to be hashed.
*
* @author kevinb@google.com (Kevin Bourrillion)
* @author andreou@google.com (Dimitris Andreou)
*/
// TODO(kevinb): this class still needs some design-and-document-for-inheritance love
protected static abstract class AbstractStreamingHasher extends AbstractHasher {
/** Buffer via which we pass data to the hash algorithm (the implementor) */
private final ByteBuffer buffer;
/** Number of bytes to be filled before process() invocation(s). */
private final int bufferSize;
/** Number of bytes processed per process() invocation. */
private final int chunkSize;
/**
* Constructor for use by subclasses. This hasher instance will process chunks of the specified
* size.
*
* @param chunkSize the number of bytes available per {@link #process(ByteBuffer)} invocation;
* must be at least 4
*/
protected AbstractStreamingHasher(int chunkSize) {
this(chunkSize, chunkSize);
}
/**
* Constructor for use by subclasses. This hasher instance will process chunks of the specified
* size, using an internal buffer of {@code bufferSize} size, which must be a multiple of
* {@code chunkSize}.
*
* @param chunkSize the number of bytes available per {@link #process(ByteBuffer)} invocation;
* must be at least 4
* @param bufferSize the size of the internal buffer. Must be a multiple of chunkSize
*/
protected AbstractStreamingHasher(int chunkSize, int bufferSize) {
// TODO(kevinb): check more preconditions (as bufferSize >= chunkSize) if this is ever public
checkArgument(bufferSize % chunkSize == 0);
// TODO(user): benchmark performance difference with longer buffer
this.buffer = ByteBuffer
.allocate(bufferSize + 7) // always space for a single primitive
.order(ByteOrder.LITTLE_ENDIAN);
this.bufferSize = bufferSize;
this.chunkSize = chunkSize;
}
/**
* Processes the available bytes of the buffer (at most {@code chunk} bytes).
*/
protected abstract void process(ByteBuffer bb);
/**
* This is invoked for the last bytes of the input, which are not enough to
* fill a whole chunk. The passed {@code ByteBuffer} is guaranteed to be
* non-empty.
*
* <p>This implementation simply pads with zeros and delegates to
* {@link #process(ByteBuffer)}.
*/
protected void processRemaining(ByteBuffer bb) {
bb.position(bb.limit()); // move at the end
bb.limit(chunkSize + 7); // get ready to pad with longs
while (bb.position() < chunkSize) {
bb.putLong(0);
}
bb.limit(chunkSize);
bb.flip();
process(bb);
}
@Override
public final Hasher putBytes(byte[] bytes) {
return putBytes(bytes, 0, bytes.length);
}
@Override
public final Hasher putBytes(byte[] bytes, int off, int len) {
return putBytes(ByteBuffer.wrap(bytes, off, len).order(ByteOrder.LITTLE_ENDIAN));
}
private final Hasher putBytes(ByteBuffer readBuffer) {
// If we have room for all of it, this is easy
if (readBuffer.remaining() <= buffer.remaining()) {
buffer.put(readBuffer);
munchIfFull();
return this;
}
// First add just enough to fill buffer size, and munch that
int bytesToCopy = bufferSize - buffer.position();
for (int i = 0; i < bytesToCopy; i++) {
buffer.put(readBuffer.get());
}
munch(); // buffer becomes empty here, since chunkSize divides bufferSize
// Now process directly from the rest of the input buffer
while (readBuffer.remaining() >= chunkSize) {
process(readBuffer);
}
// Finally stick the remainder back in our usual buffer
buffer.put(readBuffer);
return this;
}
@Override
public final Hasher putString(CharSequence charSequence) {
for (int i = 0; i < charSequence.length(); i++) {
putChar(charSequence.charAt(i));
}
return this;
}
@Override
public final Hasher putByte(byte b) {
buffer.put(b);
munchIfFull();
return this;
}
@Override
public final Hasher putShort(short s) {
buffer.putShort(s);
munchIfFull();
return this;
}
@Override
public final Hasher putChar(char c) {
buffer.putChar(c);
munchIfFull();
return this;
}
@Override
public final Hasher putInt(int i) {
buffer.putInt(i);
munchIfFull();
return this;
}
@Override
public final Hasher putLong(long l) {
buffer.putLong(l);
munchIfFull();
return this;
}
@Override
public final <T> Hasher putObject(T instance, Funnel<? super T> funnel) {
funnel.funnel(instance, this);
return this;
}
@Override
public final HashCode hash() {
munch();
buffer.flip();
if (buffer.remaining() > 0) {
processRemaining(buffer);
}
return makeHash();
}
abstract HashCode makeHash();
// Process pent-up data in chunks
private void munchIfFull() {
if (buffer.remaining() < 8) {
// buffer is full; not enough room for a primitive. We have at least one full chunk.
munch();
}
}
private void munch() {
buffer.flip();
while (buffer.remaining() >= chunkSize) {
// we could limit the buffer to ensure process() does not read more than
// chunkSize number of bytes, but we trust the implementations
process(buffer);
}
buffer.compact(); // preserve any remaining data that do not make a full chunk
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.primitives.Chars;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import com.google.common.primitives.Shorts;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* {@link HashFunction} adapter for {@link MessageDigest}s.
*
* @author kevinb@google.com (Kevin Bourrillion)
* @author andreou@google.com (Dimitris Andreou)
*/
final class MessageDigestHashFunction extends AbstractStreamingHashFunction {
private final String algorithmName;
private final int bits;
MessageDigestHashFunction(String algorithmName) {
this.algorithmName = algorithmName;
this.bits = getMessageDigest(algorithmName).getDigestLength() * 8;
}
public int bits() {
return bits;
}
private static MessageDigest getMessageDigest(String algorithmName) {
try {
return MessageDigest.getInstance(algorithmName);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
@Override public Hasher newHasher() {
return new MessageDigestHasher(getMessageDigest(algorithmName));
}
private static class MessageDigestHasher implements Hasher {
private final MessageDigest digest;
private final ByteBuffer scratch; // lazy convenience
private boolean done;
private MessageDigestHasher(MessageDigest digest) {
this.digest = digest;
this.scratch = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
}
@Override public Hasher putByte(byte b) {
checkNotDone();
digest.update(b);
return this;
}
@Override public Hasher putBytes(byte[] bytes) {
checkNotDone();
digest.update(bytes);
return this;
}
@Override public Hasher putBytes(byte[] bytes, int off, int len) {
checkNotDone();
checkPositionIndexes(off, off + len, bytes.length);
digest.update(bytes, off, len);
return this;
}
@Override public Hasher putShort(short s) {
checkNotDone();
scratch.putShort(s);
digest.update(scratch.array(), 0, Shorts.BYTES);
scratch.clear();
return this;
}
@Override public Hasher putInt(int i) {
checkNotDone();
scratch.putInt(i);
digest.update(scratch.array(), 0, Ints.BYTES);
scratch.clear();
return this;
}
@Override public Hasher putLong(long l) {
checkNotDone();
scratch.putLong(l);
digest.update(scratch.array(), 0, Longs.BYTES);
scratch.clear();
return this;
}
@Override public Hasher putFloat(float f) {
checkNotDone();
scratch.putFloat(f);
digest.update(scratch.array(), 0, 4);
scratch.clear();
return this;
}
@Override public Hasher putDouble(double d) {
checkNotDone();
scratch.putDouble(d);
digest.update(scratch.array(), 0, 8);
scratch.clear();
return this;
}
@Override public Hasher putBoolean(boolean b) {
return putByte(b ? (byte) 1 : (byte) 0);
}
@Override public Hasher putChar(char c) {
checkNotDone();
scratch.putChar(c);
digest.update(scratch.array(), 0, Chars.BYTES);
scratch.clear();
return this;
}
@Override public Hasher putString(CharSequence charSequence) {
for (int i = 0; i < charSequence.length(); i++) {
putChar(charSequence.charAt(i));
}
return this;
}
@Override public Hasher putString(CharSequence charSequence, Charset charset) {
return putBytes(charSequence.toString().getBytes(charset));
}
@Override public <T> Hasher putObject(T instance, Funnel<? super T> funnel) {
checkNotDone();
funnel.funnel(instance, this);
return this;
}
private void checkNotDone() {
checkState(!done, "Cannot use Hasher after calling #hash() on it");
}
public HashCode hash() {
done = true;
return HashCodes.fromBytes(digest.digest());
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
import com.google.common.annotations.Beta;
import java.nio.charset.Charset;
/**
* An object which can receive a stream of primitive values.
*
* @author Kevin Bourrillion
* @since 11.0
*/
@Beta
public interface Sink {
/**
* Puts a byte into this sink.
*
* @param b a byte
* @return this instance
*/
Sink putByte(byte b);
/**
* Puts an array of bytes into this sink.
*
* @param bytes a byte array
* @return this instance
*/
Sink putBytes(byte[] bytes);
/**
* Puts a chunk of an array of bytes into this sink. {@code bytes[off]} is the first byte written,
* {@code bytes[off + len - 1]} is the last.
*
* @param bytes a byte array
* @param off the start offset in the array
* @param len the number of bytes to write
* @return this instance
* @throws IndexOutOfBoundsException if {@code off < 0} or {@code off + len > bytes.length} or
* {@code len < 0}
*/
Sink putBytes(byte[] bytes, int off, int len);
/**
* Puts a short into this sink.
*/
Sink putShort(short s);
/**
* Puts an int into this sink.
*/
Sink putInt(int i);
/**
* Puts a long into this sink.
*/
Sink putLong(long l);
/**
* Puts a float into this sink.
*/
Sink putFloat(float f);
/**
* Puts a double into this sink.
*/
Sink putDouble(double d);
/**
* Puts a boolean into this sink.
*/
Sink putBoolean(boolean b);
/**
* Puts a character into this sink.
*/
Sink putChar(char c);
/**
* Puts a string into this sink.
*/
Sink putString(CharSequence charSequence);
/**
* Puts a string into this sink using the given charset.
*/
Sink putString(CharSequence charSequence, Charset charset);
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
import static com.google.common.primitives.UnsignedBytes.toInt;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* See http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp
* MurmurHash3_x64_128
*
* @author aappleby@google.com (Austin Appleby)
* @author andreou@google.com (Dimitris Andreou)
*/
final class Murmur3_128HashFunction extends AbstractStreamingHashFunction implements Serializable {
// TODO(user): when the shortcuts are implemented, update BloomFilterStrategies
private final int seed;
Murmur3_128HashFunction(int seed) {
this.seed = seed;
}
@Override public int bits() {
return 128;
}
@Override public Hasher newHasher() {
return new Murmur3_128Hasher(seed);
}
private static final class Murmur3_128Hasher extends AbstractStreamingHasher {
long h1;
long h2;
long c1 = 0x87c37b91114253d5L;
long c2 = 0x4cf5ad432745937fL;
int len;
Murmur3_128Hasher(int seed) {
super(16);
h1 = seed;
h2 = seed;
}
@Override protected void process(ByteBuffer bb) {
long k1 = bb.getLong();
long k2 = bb.getLong();
len += 16;
bmix64(k1, k2);
}
private void bmix64(long k1, long k2) {
k1 *= c1;
k1 = Long.rotateLeft(k1, 31);
k1 *= c2;
h1 ^= k1;
h1 = Long.rotateLeft(h1, 27);
h1 += h2;
h1 = h1 * 5 + 0x52dce729;
k2 *= c2;
k2 = Long.rotateLeft(k2, 33);
k2 *= c1;
h2 ^= k2;
h2 = Long.rotateLeft(h2, 31);
h2 += h1;
h2 = h2 * 5 + 0x38495ab5;
}
@Override protected void processRemaining(ByteBuffer bb) {
long k1 = 0;
long k2 = 0;
len += bb.remaining();
switch (bb.remaining()) {
case 15:
k2 ^= (long) toInt(bb.get(14)) << 48; // fall through
case 14:
k2 ^= (long) toInt(bb.get(13)) << 40; // fall through
case 13:
k2 ^= (long) toInt(bb.get(12)) << 32; // fall through
case 12:
k2 ^= (long) toInt(bb.get(11)) << 24; // fall through
case 11:
k2 ^= (long) toInt(bb.get(10)) << 16; // fall through
case 10:
k2 ^= (long) toInt(bb.get(9)) << 8; // fall through
case 9:
k2 ^= (long) toInt(bb.get(8)) << 0;
k2 *= c2;
k2 = Long.rotateLeft(k2, 33);
k2 *= c1;
h2 ^= k2;
// fall through
case 8:
k1 ^= (long) toInt(bb.get(7)) << 56; // fall through
case 7:
k1 ^= (long) toInt(bb.get(6)) << 48; // fall through
case 6:
k1 ^= (long) toInt(bb.get(5)) << 40; // fall through
case 5:
k1 ^= (long) toInt(bb.get(4)) << 32; // fall through
case 4:
k1 ^= (long) toInt(bb.get(3)) << 24; // fall through
case 3:
k1 ^= (long) toInt(bb.get(2)) << 16; // fall through
case 2:
k1 ^= (long) toInt(bb.get(1)) << 8; // fall through
case 1:
k1 ^= (long) toInt(bb.get(0)) << 0;
k1 *= c1;
k1 = Long.rotateLeft(k1, 31);
k1 *= c2;
h1 ^= k1;
// fall through
default:
}
}
@Override public HashCode makeHash() {
h1 ^= len;
h2 ^= len;
h1 += h2;
h2 += h1;
h1 = fmix64(h1);
h2 = fmix64(h2);
h1 += h2;
h2 += h1;
ByteBuffer bb = ByteBuffer.wrap(new byte[16]).order(ByteOrder.LITTLE_ENDIAN);
bb.putLong(h1);
bb.putLong(h2);
return HashCodes.fromBytes(bb.array());
}
private long fmix64(long k) {
k ^= k >>> 33;
k *= 0xff51afd7ed558ccdL;
k ^= k >>> 33;
k *= 0xc4ceb9fe1a85ec53L;
k ^= k >>> 33;
return k;
}
}
private static final long serialVersionUID = 0L;
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors.
*
* 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.
*/
// TODO(user): when things stabilize, flesh this out
/**
* Hash functions and related structures.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/HashingExplained">
* hashing</a>.
*/
@ParametersAreNonnullByDefault
package com.google.common.hash;
import javax.annotation.ParametersAreNonnullByDefault;
| Java |
// Copyright 2011 Google Inc. All Rights Reserved.
package com.google.common.hash;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* Skeleton implementation of {@link HashFunction}, appropriate for non-streaming algorithms.
* All the hash computation done using {@linkplain #newHasher()} are delegated to the {@linkplain
* #hashBytes(byte[], int, int)} method.
*
* @author andreou@google.com (Dimitris Andreou)
*/
abstract class AbstractNonStreamingHashFunction implements HashFunction {
@Override
public Hasher newHasher() {
return new BufferingHasher(32);
}
@Override
public Hasher newHasher(int expectedInputSize) {
Preconditions.checkArgument(expectedInputSize >= 0);
return new BufferingHasher(expectedInputSize);
}
/**
* In-memory stream-based implementation of Hasher.
*/
private final class BufferingHasher extends AbstractHasher {
final ExposedByteArrayOutputStream stream;
static final int BOTTOM_BYTE = 0xFF;
BufferingHasher(int expectedInputSize) {
this.stream = new ExposedByteArrayOutputStream(expectedInputSize);
}
@Override
public Hasher putByte(byte b) {
stream.write(b);
return this;
}
@Override
public Hasher putBytes(byte[] bytes) {
try {
stream.write(bytes);
} catch (IOException e) {
throw Throwables.propagate(e);
}
return this;
}
@Override
public Hasher putBytes(byte[] bytes, int off, int len) {
stream.write(bytes, off, len);
return this;
}
@Override
public Hasher putShort(short s) {
stream.write(s & BOTTOM_BYTE);
stream.write((s >>> 8) & BOTTOM_BYTE);
return this;
}
@Override
public Hasher putInt(int i) {
stream.write(i & BOTTOM_BYTE);
stream.write((i >>> 8) & BOTTOM_BYTE);
stream.write((i >>> 16) & BOTTOM_BYTE);
stream.write((i >>> 24) & BOTTOM_BYTE);
return this;
}
@Override
public Hasher putLong(long l) {
for (int i = 0; i < 64; i += 8) {
stream.write((byte) ((l >>> i) & BOTTOM_BYTE));
}
return this;
}
@Override
public Hasher putChar(char c) {
stream.write(c & BOTTOM_BYTE);
stream.write((c >>> 8) & BOTTOM_BYTE);
return this;
}
@Override
public <T> Hasher putObject(T instance, Funnel<? super T> funnel) {
funnel.funnel(instance, this);
return this;
}
@Override
public HashCode hash() {
return hashBytes(stream.byteArray(), 0, stream.length());
}
}
// Just to access the byte[] without introducing an unnecessary copy
private static final class ExposedByteArrayOutputStream extends ByteArrayOutputStream {
ExposedByteArrayOutputStream(int expectedInputSize) {
super(expectedInputSize);
}
byte[] byteArray() {
return buf;
}
int length() {
return count;
}
}
}
| Java |
// Copyright 2011 Google Inc. All Rights Reserved.
package com.google.common.hash;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.math.IntMath;
import java.math.RoundingMode;
/**
* Collections of strategies of generating the {@code k * log(M)} bits required for an element to
* be mapped to a {@link BloomFilter} of {@code M} bits and {@code k} hash functions. These
* strategies are part of the serialized form of the Bloom filters that use them, thus they must be
* preserved as is (no updates allowed, only introduction of new versions).
*
* @author andreou@google.com (Dimitris Andreou)
*/
enum BloomFilterStrategies implements BloomFilter.Strategy {
/**
* See "Less Hashing, Same Performance: Building a Better Bloom Filter" by Adam Kirsch and
* Michael Mitzenmacher. The paper argues that this trick doesn't significantly deteriorate the
* performance of a Bloom filter (yet only needs two 32bit hash functions).
*/
MURMUR128_MITZ_32() {
@Override public <T> void put(T object, Funnel<? super T> funnel,
int numHashFunctions, BitArray bits) {
// TODO(user): when the murmur's shortcuts are implemented, update this code
long hash64 = Hashing.murmur3_128().newHasher().putObject(object, funnel).hash().asLong();
int hash1 = (int) hash64;
int hash2 = (int) (hash64 >>> 32);
for (int i = 1; i <= numHashFunctions; i++) {
int nextHash = hash1 + i * hash2;
if (nextHash < 0) {
nextHash = ~nextHash;
}
// up to here, the code is identical with the next method
bits.set(nextHash % bits.size());
}
}
@Override public <T> boolean mightContain(T object, Funnel<? super T> funnel,
int numHashFunctions, BitArray bits) {
long hash64 = Hashing.murmur3_128().newHasher().putObject(object, funnel).hash().asLong();
int hash1 = (int) hash64;
int hash2 = (int) (hash64 >>> 32);
for (int i = 1; i <= numHashFunctions; i++) {
int nextHash = hash1 + i * hash2;
if (nextHash < 0) {
nextHash = ~nextHash;
}
// up to here, the code is identical with the previous method
if (!bits.get(nextHash % bits.size())) {
return false;
}
}
return true;
}
};
static class BitArray {
final long[] data;
BitArray(int bits) {
this(new long[IntMath.divide(bits, 64, RoundingMode.CEILING)]);
}
// Used by serialization
BitArray(long[] data) {
checkArgument(data.length > 0, "data length is zero!");
this.data = data;
}
void set(int index) {
data[index >> 6] |= (1L << index);
}
boolean get(int index) {
return (data[index >> 6] & (1L << index)) != 0;
}
/** Number of bits */
int size() {
return data.length * Long.SIZE;
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.hash.BloomFilterStrategies.BitArray;
import java.io.Serializable;
/**
* A Bloom filter for instances of {@code T}. A Bloom filter offers an approximate containment test
* with one-sided error: if it claims that an element is contained in it, this might be in error,
* but if it claims that an element is <i>not</i> contained in it, then this is definitely true.
*
* <p>If you are unfamiliar with Bloom filters, this nice
* <a href="http://llimllib.github.com/bloomfilter-tutorial/">tutorial</a> may help you understand
* how they work.
*
* @param <T> the type of instances that the {@code BloomFilter} accepts
* @author Kevin Bourrillion
* @author Dimitris Andreou
* @since 11.0
*/
@Beta
public final class BloomFilter<T> implements Serializable {
/**
* A strategy to translate T instances, to {@code numHashFunctions} bit indexes.
*/
interface Strategy extends java.io.Serializable {
/**
* Sets {@code numHashFunctions} bits of the given bit array, by hashing a user element.
*/
<T> void put(T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits);
/**
* Queries {@code numHashFunctions} bits of the given bit array, by hashing a user element;
* returns {@code true} if and only if all selected bits are set.
*/
<T> boolean mightContain(
T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits);
}
/** The bit set of the BloomFilter (not necessarily power of 2!)*/
private final BitArray bits;
/** Number of hashes per element */
private final int numHashFunctions;
/** The funnel to translate Ts to bytes */
private final Funnel<T> funnel;
/**
* The strategy we employ to map an element T to {@code numHashFunctions} bit indexes.
*/
private final Strategy strategy;
/**
* Creates a BloomFilter.
*/
private BloomFilter(BitArray bits, int numHashFunctions, Funnel<T> funnel,
Strategy strategy) {
Preconditions.checkArgument(numHashFunctions > 0, "numHashFunctions zero or negative");
this.bits = checkNotNull(bits);
this.numHashFunctions = numHashFunctions;
this.funnel = checkNotNull(funnel);
this.strategy = strategy;
}
/**
* Returns {@code true} if the element <i>might</i> have been put in this Bloom filter,
* {@code false} if this is <i>definitely</i> not the case.
*/
public boolean mightContain(T object) {
return strategy.mightContain(object, funnel, numHashFunctions, bits);
}
/**
* Puts an element into this {@code BloomFilter}. Ensures that subsequent invocations of
* {@link #mightContain(Object)} with the same element will always return {@code true}.
*/
public void put(T object) {
strategy.put(object, funnel, numHashFunctions, bits);
}
@VisibleForTesting int getHashCount() {
return numHashFunctions;
}
@VisibleForTesting double computeExpectedFalsePositiveRate(int insertions) {
return Math.pow(
1 - Math.exp(-numHashFunctions * ((double) insertions / (bits.size()))),
numHashFunctions);
}
/**
* Creates a {@code Builder} of a {@link BloomFilter BloomFilter<T>}, with the expected number
* of insertions and expected false positive probability.
*
* <p>Note that overflowing a {@code BloomFilter} with significantly more elements
* than specified, will result in its saturation, and a sharp deterioration of its
* false positive probability.
*
* <p>The constructed {@code BloomFilter<T>} will be serializable if the provided
* {@code Funnel<T>} is.
*
* @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use
* @param expectedInsertions the number of expected insertions to the constructed
* {@code BloomFilter<T>}; must be positive
* @param falsePositiveProbability the desired false positive probability (must be positive and
* less than 1.0)
* @return a {@code Builder}
*/
public static <T> BloomFilter<T> create(Funnel<T> funnel, int expectedInsertions /* n */,
double falsePositiveProbability) {
checkNotNull(funnel);
checkArgument(expectedInsertions > 0, "Expected insertions must be positive");
checkArgument(falsePositiveProbability > 0.0 & falsePositiveProbability < 1.0,
"False positive probability in (0.0, 1.0)");
/*
* andreou: I wanted to put a warning in the javadoc about tiny fpp values,
* since the resulting size is proportional to -log(p), but there is not
* much of a point after all, e.g. optimalM(1000, 0.0000000000000001) = 76680
* which is less that 10kb. Who cares!
*/
int numBits = optimalNumOfBits(expectedInsertions, falsePositiveProbability);
int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits);
return new BloomFilter<T>(new BitArray(numBits), numHashFunctions, funnel,
BloomFilterStrategies.MURMUR128_MITZ_32);
}
/**
* Creates a {@code Builder} of a {@link BloomFilter BloomFilter<T>}, with the expected number
* of insertions, and a default expected false positive probability of 3%.
*
* <p>Note that overflowing a {@code BloomFilter} with significantly more elements
* than specified, will result in its saturation, and a sharp deterioration of its
* false positive probability.
*
* <p>The constructed {@code BloomFilter<T>} will be serializable if the provided
* {@code Funnel<T>} is.
*
* @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use
* @param expectedInsertions the number of expected insertions to the constructed
* {@code BloomFilter<T>}; must be positive
* @return a {@code Builder}
*/
public static <T> BloomFilter<T> create(Funnel<T> funnel, int expectedInsertions /* n */) {
return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions
}
/*
* Cheat sheet:
*
* m: total bits
* n: expected insertions
* b: m/n, bits per insertion
* p: expected false positive probability
*
* 1) Optimal k = b * ln2
* 2) p = (1 - e ^ (-kn/m))^k
* 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b
* 4) For optimal k: m = -nlnp / ((ln2) ^ 2)
*/
private static final double LN2 = Math.log(2);
private static final double LN2_SQUARED = LN2 * LN2;
/**
* Computes the optimal k (number of hashes per element inserted in Bloom filter), given the
* expected insertions and total number of bits in the Bloom filter.
*
* See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula.
*
* @param n expected insertions (must be positive)
* @param m total number of bits in Bloom filter (must be positive)
*/
@VisibleForTesting static int optimalNumOfHashFunctions(int n, int m) {
return Math.max(1, (int) Math.round(m / n * LN2));
}
/**
* Computes m (total bits of Bloom filter) which is expected to achieve, for the specified
* expected insertions, the required false positive probability.
*
* See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the formula.
*
* @param n expected insertions (must be positive)
* @param p false positive rate (must be 0 < p < 1)
*/
@VisibleForTesting static int optimalNumOfBits(int n, double p) {
return (int) (-n * Math.log(p) / LN2_SQUARED);
}
private Object writeReplace() {
return new SerialForm<T>(this);
}
private static class SerialForm<T> implements Serializable {
final long[] data;
final int numHashFunctions;
final Funnel<T> funnel;
final Strategy strategy;
SerialForm(BloomFilter<T> bf) {
this.data = bf.bits.data;
this.numHashFunctions = bf.numHashFunctions;
this.funnel = bf.funnel;
this.strategy = bf.strategy;
}
Object readResolve() {
return new BloomFilter<T>(new BitArray(data), numHashFunctions, funnel, strategy);
}
private static final long serialVersionUID = 1;
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
import com.google.common.annotations.Beta;
import com.google.common.primitives.Ints;
import java.nio.charset.Charset;
/**
* A hash function is a collision-averse pure function that maps an arbitrary block of
* data to a number called a <i>hash code</i>.
*
* <h3>Definition</h3>
*
* <p>Unpacking this definition:
*
* <ul>
* <li><b>block of data:</b> the input for a hash function is always, in concept, an
* ordered byte array. This hashing API accepts an arbitrary sequence of byte and
* multibyte values (via {@link Hasher}), but this is merely a convenience; these are
* always translated into raw byte sequences under the covers.
*
* <li><b>hash code:</b> each hash function always yields hash codes of the same fixed bit
* length (given by {@link #bits}). For example, {@link Hashing#sha1} produces a
* 160-bit number, while {@link Hashing#murmur3_32()} yields only 32 bits. Because a
* {@code long} value is clearly insufficient to hold all hash code values, this API
* represents a hash code as an instance of {@link HashCode}.
*
* <li><b>pure function:</b> the value produced must depend only on the input bytes, in
* the order they appear. Input data is never modified.
*
* <li><b>collision-averse:</b> while it can't be helped that a hash function will
* sometimes produce the same hash code for distinct inputs (a "collision"), every
* hash function strives to <i>some</i> degree to make this unlikely. (Without this
* condition, a function that always returns zero could be called a hash function. It
* is not.)
* </ul>
*
* <p>Summarizing the last two points: "equal yield equal <i>always</i>; unequal yield
* unequal <i>often</i>." This is the most important characteristic of all hash functions.
*
* <h3>Desirable properties</h3>
*
* <p>A high-quality hash function strives for some subset of the following virtues:
*
* <ul>
* <li><b>collision-resistant:</b> while the definition above requires making at least
* <i>some</i> token attempt, one measure of the quality of a hash function is <i>how
* well</i> it succeeds at this goal. Important note: it may be easy to achieve the
* theoretical minimum collision rate when using completely <i>random</i> sample
* input. The true test of a hash function is how it performs on representative
* real-world data, which tends to contain many hidden patterns and clumps. The goal
* of a good hash function is to stamp these patterns out as thoroughly as possible.
*
* <li><b>bit-dispersing:</b> masking out any <i>single bit</i> from a hash code should
* yield only the expected <i>twofold</i> increase to all collision rates. Informally,
* the "information" in the hash code should be as evenly "spread out" through the
* hash code's bits as possible. The result is that, for example, when choosing a
* bucket in a hash table of size 2^8, <i>any</i> eight bits could be consistently
* used.
*
* <li><b>cryptographic:</b> certain hash functions such as {@link Hashing#sha512} are
* designed to make it as infeasible as possible to reverse-engineer the input that
* produced a given hash code, or even to discover <i>any</i> two distinct inputs that
* yield the same result. These are called <i>cryptographic hash functions</i>. But,
* whenever it is learned that either of these feats has become computationally
* feasible, the function is deemed "broken" and should no longer be used for secure
* purposes. (This is the likely eventual fate of <i>all</i> cryptographic hashes.)
*
* <li><b>fast:</b> perhaps self-explanatory, but often the most important consideration.
* We have published <a href="#noWeHaventYet">microbenchmark results</a> for many
* common hash functions.
* </ul>
*
* <h3>Providing input to a hash function</h3>
*
* <p>The primary way to provide the data that your hash function should act on is via a
* {@link Hasher}. Obtain a new hasher from the hash function using {@link #newHasher},
* "push" the relevant data into it using methods like {@link Hasher#putBytes(byte[])},
* and finally ask for the {@code HashCode} when finished using {@link Hasher#hash}. (See
* an {@linkplain #newHasher example} of this.)
*
* <p>If all you want to hash is a single byte array, string or {@code long} value, there
* are convenient shortcut methods defined directly on {@link HashFunction} to make this
* easier.
*
* <p>Hasher accepts primitive data types, but can also accept any Object of type {@code
* T} provided that you implement a {@link Funnel Funnel<T>} to specify how to "feed" data
* from that object into the function. (See {@linkplain Hasher#putObject an example} of
* this.)
*
* <p><b>Compatibility note:</b> Throughout this API, multibyte values are always
* interpreted in <i>little-endian</i> order. That is, hashing the byte array {@code
* {0x01, 0x02, 0x03, 0x04}} is equivalent to hashing the {@code int} value {@code
* 0x04030201}. If this isn't what you need, methods such as {@link Integer#reverseBytes}
* and {@link Ints#toByteArray} will help.
*
* <h3>Relationship to {@link Object#hashCode}</h3>
*
* <p>Java's baked-in concept of hash codes is constrained to 32 bits, and provides no
* separation between hash algorithms and the data they act on, so alternate hash
* algorithms can't be easily substituted. Also, implementations of {@code hashCode} tend
* to be poor-quality, in part because they end up depending on <i>other</i> existing
* poor-quality {@code hashCode} implementations, including those in many JDK classes.
*
* <p>{@code Object.hashCode} implementations tend to be very fast, but have weak
* collision prevention and <i>no</i> expectation of bit dispersion. This leaves them
* perfectly suitable for use in hash tables, because extra collisions cause only a slight
* performance hit, while poor bit dispersion is easily corrected using a secondary hash
* function (which all reasonable hash table implementations in Java use). For the many
* uses of hash functions beyond data structures, however, {@code Object.hashCode} almost
* always falls short -- hence this library.
*
* @author Kevin Bourrillion
* @since 11.0
*/
@Beta
public interface HashFunction {
/**
* Begins a new hash code computation by returning an initialized, stateful {@code
* Hasher} instance that is ready to receive data. Example: <pre> {@code
*
* HashFunction hf = Hashing.md5();
* HashCode hc = hf.newHasher()
* .putLong(id)
* .putString(name)
* .hash();}</pre>
*/
Hasher newHasher();
/**
* Begins a new hash code computation as {@link #newHasher()}, but provides a hint of the
* expected size of the input (in bytes). This is only important for non-streaming hash
* functions (hash functions that need to buffer their whole input before processing any
* of it).
*/
Hasher newHasher(int expectedInputSize);
/**
* Shortcut for {@code newHasher().putLong(input).hash()}; returns the hash code for the
* given {@code long} value, interpreted in little-endian byte order. The implementation
* <i>might</i> perform better than its longhand equivalent, but should not perform worse.
*/
HashCode hashLong(long input);
/**
* Shortcut for {@code newHasher().putBytes(input).hash()}. The implementation
* <i>might</i> perform better than its longhand equivalent, but should not perform
* worse.
*/
HashCode hashBytes(byte[] input);
/**
* Shortcut for {@code newHasher().putBytes(input, off, len).hash()}. The implementation
* <i>might</i> perform better than its longhand equivalent, but should not perform
* worse.
*
* @throws IndexOutOfBoundsException if {@code off < 0} or {@code off + len > bytes.length}
* or {@code len < 0}
*/
HashCode hashBytes(byte[] input, int off, int len);
/**
* Shortcut for {@code newHasher().putString(input).hash()}. The implementation <i>might</i>
* perform better than its longhand equivalent, but should not perform worse. Note that no
* character encoding is performed; the low byte and high byte of each character are hashed
* directly (in that order). This is equivalent to using
* {@code hashString(input, Charsets.UTF_16LE)}.
*/
HashCode hashString(CharSequence input);
/**
* Shortcut for {@code newHasher().putString(input, charset).hash()}. Characters are encoded
* using the given {@link Charset}. The implementation <i>might</i> perform better than its
* longhand equivalent, but should not perform worse.
*/
HashCode hashString(CharSequence input, Charset charset);
/**
* Returns the number of bits (a multiple of 32) that each hash code produced by this
* hash function has.
*/
int bits();
}
| Java |
// Copyright 2011 Google Inc. All Rights Reserved.
package com.google.common.hash;
import java.nio.charset.Charset;
/**
* An abstract composition of multiple hash functions. {@linkplain #newHasher()} delegates to the
* {@code Hasher} objects of the delegate hash functions, and in the end, they are used by
* {@linkplain #makeHash(Hasher[])} that constructs the final {@code HashCode}.
*
* @author andreou@google.com (Dimitris Andreou)
*/
abstract class AbstractCompositeHashFunction extends AbstractStreamingHashFunction {
final HashFunction[] functions;
AbstractCompositeHashFunction(HashFunction... functions) {
this.functions = functions;
}
/**
* Constructs a {@code HashCode} from the {@code Hasher} objects of the functions. Each of them
* has consumed the entire input and they are ready to output a {@code HashCode}. The order of
* the hashers are the same order as the functions given to the constructor.
*/
// this could be cleaner if it passed HashCode[], but that would create yet another array...
/* protected */ abstract HashCode makeHash(Hasher[] hashers);
@Override
public Hasher newHasher() {
final Hasher[] hashers = new Hasher[functions.length];
for (int i = 0; i < hashers.length; i++) {
hashers[i] = functions[i].newHasher();
}
return new Hasher() {
@Override public Hasher putByte(byte b) {
for (Hasher hasher : hashers) {
hasher.putByte(b);
}
return this;
}
@Override public Hasher putBytes(byte[] bytes) {
for (Hasher hasher : hashers) {
hasher.putBytes(bytes);
}
return this;
}
@Override public Hasher putBytes(byte[] bytes, int off, int len) {
for (Hasher hasher : hashers) {
hasher.putBytes(bytes, off, len);
}
return this;
}
@Override public Hasher putShort(short s) {
for (Hasher hasher : hashers) {
hasher.putShort(s);
}
return this;
}
@Override public Hasher putInt(int i) {
for (Hasher hasher : hashers) {
hasher.putInt(i);
}
return this;
}
@Override public Hasher putLong(long l) {
for (Hasher hasher : hashers) {
hasher.putLong(l);
}
return this;
}
@Override public Hasher putFloat(float f) {
for (Hasher hasher : hashers) {
hasher.putFloat(f);
}
return this;
}
@Override public Hasher putDouble(double d) {
for (Hasher hasher : hashers) {
hasher.putDouble(d);
}
return this;
}
@Override public Hasher putBoolean(boolean b) {
for (Hasher hasher : hashers) {
hasher.putBoolean(b);
}
return this;
}
@Override public Hasher putChar(char c) {
for (Hasher hasher : hashers) {
hasher.putChar(c);
}
return this;
}
@Override public Hasher putString(CharSequence chars) {
for (Hasher hasher : hashers) {
hasher.putString(chars);
}
return this;
}
@Override public Hasher putString(CharSequence chars, Charset charset) {
for (Hasher hasher : hashers) {
hasher.putString(chars, charset);
}
return this;
}
@Override public <T> Hasher putObject(T instance, Funnel<? super T> funnel) {
for (Hasher hasher : hashers) {
hasher.putObject(instance, funnel);
}
return this;
}
@Override public HashCode hash() {
return makeHash(hashers);
}
};
}
private static final long serialVersionUID = 0L;
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
import com.google.common.annotations.Beta;
/**
* An object which can send data from an object of type {@code T} into a {@code Sink}.
*
* @author Dimitris Andreou
* @since 11.0
*/
@Beta
public interface Funnel<T> {
/**
* Sends a stream of data from the {@code from} object into the sink {@code into}. There
* is no requirement that this data be complete enough to fully reconstitute the object
* later.
*/
void funnel(T from, Sink into);
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
import com.google.common.annotations.Beta;
/**
* Funnels for common types. All implementations are serializable.
*
* @author Dimitris Andreou
* @since 11.0
*/
@Beta
public final class Funnels {
private Funnels() {}
/**
* Returns a funnel that extracts the bytes from a {@code byte} array.
*/
public static Funnel<byte[]> byteArrayFunnel() {
return ByteArrayFunnel.INSTANCE;
}
private enum ByteArrayFunnel implements Funnel<byte[]> {
INSTANCE;
public void funnel(byte[] from, Sink into) {
into.putBytes(from);
}
@Override public String toString() {
return "Funnels.byteArrayFunnel()";
}
}
/**
* Returns a funnel that extracts the characters from a {@code CharSequence}.
*/
public static Funnel<CharSequence> stringFunnel() {
return StringFunnel.INSTANCE;
}
private enum StringFunnel implements Funnel<CharSequence> {
INSTANCE;
public void funnel(CharSequence from, Sink into) {
into.putString(from);
}
@Override public String toString() {
return "Funnels.stringFunnel()";
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
/**
* Static factories for {@link HashCode} instances.
*
* @author andreou@google.com (Dimitris Andreou)
*/
final class HashCodes {
private HashCodes() { }
/**
* Creates a 32-bit {@code HashCode}, of which the bytes will form the passed int, interpreted
* in little endian order.
*/
static HashCode fromInt(int hash) {
return new IntHashCode(hash);
}
private static class IntHashCode extends HashCode {
final int hash;
IntHashCode(int hash) {
this.hash = hash;
}
@Override public int bits() {
return 32;
}
@Override public byte[] asBytes() {
return new byte[] {
(byte) hash,
(byte) (hash >> 8),
(byte) (hash >> 16),
(byte) (hash >> 24)};
}
@Override public int asInt() {
return hash;
}
@Override public long asLong() {
throw new IllegalStateException("this HashCode only has 32 bits; cannot create a long");
}
}
/**
* Creates a 64-bit {@code HashCode}, of which the bytes will form the passed long, interpreted
* in little endian order.
*/
static HashCode fromLong(long hash) {
return new LongHashCode(hash);
}
private static class LongHashCode extends HashCode {
final long hash;
LongHashCode(long hash) {
this.hash = hash;
}
@Override public int bits() {
return 64;
}
@Override public byte[] asBytes() {
return new byte[] {
(byte) hash,
(byte) (hash >> 8),
(byte) (hash >> 16),
(byte) (hash >> 24),
(byte) (hash >> 32),
(byte) (hash >> 40),
(byte) (hash >> 48),
(byte) (hash >> 56)};
}
@Override public int asInt() {
return (int) hash;
}
@Override public long asLong() {
return hash;
}
}
/**
* Creates a {@code HashCode} from a byte array. The array is <i>not</i> copied defensively,
* so it must be handed-off so as to preserve the immutability contract of {@code HashCode}.
* The array must be at least of length 4 (not checked).
*/
static HashCode fromBytes(byte[] bytes) {
return new BytesHashCode(bytes);
}
private static class BytesHashCode extends HashCode {
final byte[] bytes;
BytesHashCode(byte[] bytes) {
this.bytes = bytes;
}
@Override public int bits() {
return bytes.length * 8;
}
@Override public byte[] asBytes() {
return bytes.clone();
}
@Override public int asInt() {
return (bytes[0] & 0xFF)
| ((bytes[1] & 0xFF) << 8)
| ((bytes[2] & 0xFF) << 16)
| ((bytes[3] & 0xFF) << 24);
}
@Override public long asLong() {
if (bytes.length < 8) {
// Checking this to throw the correct type of exception
throw new IllegalStateException("Not enough bytes");
}
return (bytes[0] & 0xFFL)
| ((bytes[1] & 0xFFL) << 8)
| ((bytes[2] & 0xFFL) << 16)
| ((bytes[3] & 0xFFL) << 24)
| ((bytes[4] & 0xFFL) << 32)
| ((bytes[5] & 0xFFL) << 40)
| ((bytes[6] & 0xFFL) << 48)
| ((bytes[7] & 0xFFL) << 56);
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.UnsignedInts;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.util.Iterator;
/**
* Static methods to obtain {@link HashFunction} instances, and other static
* hashing-related utilities.
*
* @author Kevin Bourrillion
* @author Dimitris Andreou
* @author Kurt Alfred Kluever
* @since 11.0
*/
@Beta
public final class Hashing {
private Hashing() {}
/**
* Returns a general-purpose, <b>non-cryptographic-strength</b>, streaming hash function that
* produces hash codes of length at least {@code minimumBits}. Users without specific
* compatibility requirements and who do not persist the hash codes are encouraged to
* choose this hash function.
*
* <p><b>Warning: the implementation is unspecified and is subject to change.</b>
*
* @throws IllegalArgumentException if {@code minimumBits} is not positive
*/
public static HashFunction goodFastHash(int minimumBits) {
int bits = checkPositiveAndMakeMultipleOf32(minimumBits);
if (bits == 32) {
return murmur3_32();
} else if (bits <= 128) {
return murmur3_128();
} else {
// Join some 128-bit murmur3s
int hashFunctionsNeeded = (bits + 127) / 128;
HashFunction[] hashFunctions = new HashFunction[hashFunctionsNeeded];
for (int i = 0; i < hashFunctionsNeeded; i++) {
hashFunctions[i] = murmur3_128(i * 1500450271 /* a prime; shouldn't matter */);
}
return new ConcatenatedHashFunction(hashFunctions);
}
}
/**
* Returns a hash function implementing the
* <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp">32-bit murmur3
* algorithm</a> (little-endian variant), using the given seed value.
*/
public static HashFunction murmur3_32(int seed) {
return new Murmur3_32HashFunction(seed);
}
/**
* Returns a hash function implementing the
* <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp">32-bit murmur3
* algorithm</a> (little-endian variant), using a seed value of zero.
*/
public static HashFunction murmur3_32() {
return MURMUR3_32;
}
private static final Murmur3_32HashFunction MURMUR3_32 = new Murmur3_32HashFunction(0);
/**
* Returns a hash function implementing the
* <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp">
* 128-bit murmur3 algorithm, x64 variant</a> (little-endian variant), using the given seed
* value.
*/
public static HashFunction murmur3_128(int seed) {
return new Murmur3_128HashFunction(seed);
}
/**
* Returns a hash function implementing the
* <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp">
* 128-bit murmur3 algorithm, x64 variant</a> (little-endian variant), using a seed value
* of zero.
*/
public static HashFunction murmur3_128() {
return MURMUR3_128;
}
private static final Murmur3_128HashFunction MURMUR3_128 = new Murmur3_128HashFunction(0);
/**
* Returns a hash function implementing the MD5 hash algorithm (128 hash bits) by delegating to
* the MD5 {@link MessageDigest}.
*/
public static HashFunction md5() {
return MD5;
}
private static final HashFunction MD5 = new MessageDigestHashFunction("MD5");
/**
* Returns a hash function implementing the SHA-1 algorithm (160 hash bits) by delegating to the
* SHA-1 {@link MessageDigest}.
*/
public static HashFunction sha1() {
return SHA_1;
}
private static final HashFunction SHA_1 = new MessageDigestHashFunction("SHA-1");
/**
* Returns a hash function implementing the SHA-256 algorithm (256 hash bits) by delegating to
* the SHA-256 {@link MessageDigest}.
*/
public static HashFunction sha256() {
return SHA_256;
}
private static final HashFunction SHA_256 = new MessageDigestHashFunction("SHA-256");
/**
* Returns a hash function implementing the SHA-512 algorithm (512 hash bits) by delegating to the
* SHA-512 {@link MessageDigest}.
*/
public static HashFunction sha512() {
return SHA_512;
}
private static final HashFunction SHA_512 = new MessageDigestHashFunction("SHA-512");
/**
* If {@code hashCode} has enough bits, returns {@code hashCode.asLong()}, otherwise
* returns a {@code long} value with {@code hashCode.asInt()} as the least-significant
* four bytes and {@code 0x00} as each of the most-significant four bytes.
*/
public static long padToLong(HashCode hashCode) {
return (hashCode.bits() < 64) ? UnsignedInts.toLong(hashCode.asInt()) : hashCode.asLong();
}
/**
* Assigns to {@code hashCode} a "bucket" in the range {@code [0, buckets)}, in a uniform
* manner that minimizes the need for remapping as {@code buckets} grows. That is,
* {@code consistentHash(h, n)} equals:
*
* <ul>
* <li>{@code n - 1}, with approximate probability {@code 1/n}
* <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n})
* </ul>
*
* <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">wikipedia
* article on consistent hashing</a> for more information.
*/
public static int consistentHash(HashCode hashCode, int buckets) {
return consistentHash(padToLong(hashCode), buckets);
}
/**
* Assigns to {@code input} a "bucket" in the range {@code [0, buckets)}, in a uniform
* manner that minimizes the need for remapping as {@code buckets} grows. That is,
* {@code consistentHash(h, n)} equals:
*
* <ul>
* <li>{@code n - 1}, with approximate probability {@code 1/n}
* <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n})
* </ul>
*
* <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">wikipedia
* article on consistent hashing</a> for more information.
*/
public static int consistentHash(long input, int buckets) {
checkArgument(buckets > 0, "buckets must be positive: %s", buckets);
long h = input;
int candidate = 0;
int next;
// Jump from bucket to bucket until we go out of range
while (true) {
// See http://en.wikipedia.org/wiki/Linear_congruential_generator
// These values for a and m come from the C++ version of this function.
h = 2862933555777941757L * h + 1;
double inv = 0x1.0p31 / ((int) (h >>> 33) + 1);
next = (int) ((candidate + 1) * inv);
if (next >= 0 && next < buckets) {
candidate = next;
} else {
return candidate;
}
}
}
/**
* Returns a hash code, having the same bit length as each of the input hash codes,
* that combines the information of these hash codes in an ordered fashion. That
* is, whenever two equal hash codes are produced by two calls to this method, it
* is <i>as likely as possible</i> that each was computed from the <i>same</i>
* input hash codes in the <i>same</i> order.
*
* @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes
* do not all have the same bit length
*/
public static HashCode combineOrdered(Iterable<HashCode> hashCodes) {
Iterator<HashCode> iterator = hashCodes.iterator();
checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine.");
int bits = iterator.next().bits();
byte[] resultBytes = new byte[bits / 8];
for (HashCode hashCode : hashCodes) {
byte[] nextBytes = hashCode.asBytes();
checkArgument(nextBytes.length == resultBytes.length,
"All hashcodes must have the same bit length.");
for (int i = 0; i < nextBytes.length; i++) {
resultBytes[i] = (byte) (resultBytes[i] * 37 ^ nextBytes[i]);
}
}
return HashCodes.fromBytes(resultBytes);
}
/**
* Returns a hash code, having the same bit length as each of the input hash codes,
* that combines the information of these hash codes in an unordered fashion. That
* is, whenever two equal hash codes are produced by two calls to this method, it
* is <i>as likely as possible</i> that each was computed from the <i>same</i>
* input hash codes in <i>some</i> order.
*
* @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes
* do not all have the same bit length
*/
public static HashCode combineUnordered(Iterable<HashCode> hashCodes) {
Iterator<HashCode> iterator = hashCodes.iterator();
checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine.");
byte[] resultBytes = new byte[iterator.next().bits() / 8];
for (HashCode hashCode : hashCodes) {
byte[] nextBytes = hashCode.asBytes();
checkArgument(nextBytes.length == resultBytes.length,
"All hashcodes must have the same bit length.");
for (int i = 0; i < nextBytes.length; i++) {
resultBytes[i] += nextBytes[i];
}
}
return HashCodes.fromBytes(resultBytes);
}
/**
* Checks that the passed argument is positive, and ceils it to a multiple of 32.
*/
static int checkPositiveAndMakeMultipleOf32(int bits) {
checkArgument(bits > 0, "Number of bits must be positive");
return (bits + 31) & ~31;
}
// TODO(kevinb): Maybe expose this class via a static Hashing method?
@VisibleForTesting
static final class ConcatenatedHashFunction extends AbstractCompositeHashFunction {
private final int bits;
ConcatenatedHashFunction(HashFunction... functions) {
super(functions);
int bitSum = 0;
for (HashFunction function : functions) {
bitSum += function.bits();
}
this.bits = bitSum;
}
@Override
HashCode makeHash(Hasher[] hashers) {
// TODO(user): Get rid of the ByteBuffer here?
byte[] bytes = new byte[bits / 8];
ByteBuffer buffer = ByteBuffer.wrap(bytes);
for (Hasher hasher : hashers) {
buffer.put(hasher.hash().asBytes());
}
return HashCodes.fromBytes(bytes);
}
@Override
public int bits() {
return bits;
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
import com.google.common.base.Charsets;
import java.nio.charset.Charset;
/**
* An abstract hasher, implementing {@link #putBoolean(boolean)}, {@link #putDouble(double)},
* {@link #putFloat(float)}, {@link #putString(CharSequence)}, and
* {@link #putString(CharSequence, Charset)} as prescribed by {@link Hasher}.
*
* @author andreou@google.com (Dimitris Andreou)
*/
abstract class AbstractHasher implements Hasher {
@Override public final Hasher putBoolean(boolean b) {
return putByte(b ? (byte) 1 : (byte) 0);
}
@Override public final Hasher putDouble(double d) {
return putLong(Double.doubleToRawLongBits(d));
}
@Override public final Hasher putFloat(float f) {
return putInt(Float.floatToRawIntBits(f));
}
@Override public Hasher putString(CharSequence charSequence) {
// TODO(user): Should we instead loop over the CharSequence and call #putChar?
return putString(charSequence, Charsets.UTF_16LE);
}
@Override public Hasher putString(CharSequence charSequence, Charset charset) {
return putBytes(charSequence.toString().getBytes(charset));
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
import com.google.common.annotations.Beta;
import java.nio.charset.Charset;
/**
* A {@link Sink} that can compute a hash code after reading the input. Each hasher should
* translate all multibyte values ({@link #putInt(int)}, {@link #putLong(long)}, etc) to bytes
* in little-endian order.
*
* @author Kevin Bourrillion
* @since 11.0
*/
@Beta
public interface Hasher extends Sink {
@Override Hasher putByte(byte b);
@Override Hasher putBytes(byte[] bytes);
@Override Hasher putBytes(byte[] bytes, int off, int len);
@Override Hasher putShort(short s);
@Override Hasher putInt(int i);
@Override Hasher putLong(long l);
/**
* Equivalent to {@code putInt(Float.floatToRawIntBits(f))}.
*/
@Override Hasher putFloat(float f);
/**
* Equivalent to {@code putLong(Double.doubleToRawLongBits(d))}.
*/
@Override Hasher putDouble(double d);
/**
* Equivalent to {@code putByte(b ? (byte) 1 : (byte) 0)}.
*/
@Override Hasher putBoolean(boolean b);
@Override Hasher putChar(char c);
/**
* Equivalent to {@code putBytes(charSequence.toString().getBytes(Charsets.UTF_16LE)}.
*/
@Override Hasher putString(CharSequence charSequence);
/**
* Equivalent to {@code putBytes(charSequence.toString().getBytes(charset)}.
*/
@Override Hasher putString(CharSequence charSequence, Charset charset);
/**
* A simple convenience for {@code funnel.funnel(object, this)}.
*/
<T> Hasher putObject(T instance, Funnel<? super T> funnel);
/**
* Computes a hash code based on the data that have been provided to this hasher. The result is
* unspecified if this method is called more than once on the same instance.
*/
HashCode hash();
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
import static com.google.common.primitives.UnsignedBytes.toInt;
import java.io.Serializable;
import java.nio.ByteBuffer;
/**
* See http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp
* MurmurHash3_x86_32
*
* @author aappleby@google.com (Austin Appleby)
* @author andreou@google.com (Dimitris Andreou)
*/
final class Murmur3_32HashFunction extends AbstractStreamingHashFunction implements Serializable {
private final int seed;
Murmur3_32HashFunction(int seed) {
this.seed = seed;
}
@Override public int bits() {
return 32;
}
@Override public Hasher newHasher() {
return new Murmur3_32Hasher(seed);
}
private static final class Murmur3_32Hasher extends AbstractStreamingHasher {
int h1;
int c1 = 0xcc9e2d51;
int c2 = 0x1b873593;
int len;
Murmur3_32Hasher(int seed) {
super(4);
h1 = seed;
}
@Override protected void process(ByteBuffer bb) {
int k1 = bb.getInt();
len += 4;
k1 *= c1;
k1 = Integer.rotateLeft(k1, 15);
k1 *= c2;
h1 ^= k1;
h1 = Integer.rotateLeft(h1, 13);
h1 = h1 * 5 + 0xe6546b64;
}
@Override protected void processRemaining(ByteBuffer bb) {
len += bb.remaining();
int k1 = 0;
switch (bb.remaining()) {
case 3:
k1 ^= toInt(bb.get(2)) << 16;
// fall through
case 2:
k1 ^= toInt(bb.get(1)) << 8;
// fall through
case 1:
k1 ^= toInt(bb.get(0));
// fall through
default:
k1 *= c1;
k1 = Integer.rotateLeft(k1, 15);
k1 *= c2;
h1 ^= k1;
}
}
@Override public HashCode makeHash() {
h1 ^= len;
h1 ^= h1 >>> 16;
h1 *= 0x85ebca6b;
h1 ^= h1 >>> 13;
h1 *= 0xc2b2ae35;
h1 ^= h1 >>> 16;
return HashCodes.fromInt(h1);
}
}
private static final long serialVersionUID = 0L;
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.hash;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints;
import java.security.MessageDigest;
/**
* An immutable hash code of arbitrary bit length.
*
* @author Dimitris Andreou
* @since 11.0
*/
@Beta
public abstract class HashCode {
HashCode() {}
/**
* Returns the first four bytes of {@linkplain #asBytes() this hashcode's bytes}, converted to
* an {@code int} value in little-endian order.
*/
public abstract int asInt();
/**
* Returns the first eight bytes of {@linkplain #asBytes() this hashcode's bytes}, converted to
* a {@code long} value in little-endian order.
*
* @throws IllegalStateException if {@code bits() < 64}
*/
public abstract long asLong();
/**
* Returns the value of this hash code as a byte array. The caller may modify the byte array;
* changes to it will <i>not</i> be reflected in this {@code HashCode} object or any other arrays
* returned by this method.
*/
// TODO(user): consider ByteString here, when that is available
public abstract byte[] asBytes();
/**
* Copies bytes from this hash code into {@code dest}.
*
* @param dest the byte array into which the hash code will be written
* @param offset the start offset in the data
* @param maxLength the maximum number of bytes to write
* @return the number of bytes written to {@code dest}
* @throws IndexOutOfBoundsException if there is not enough room in {@code dest}
*/
public int writeBytesTo(byte[] dest, int offset, int maxLength) {
byte[] hash = asBytes();
maxLength = Ints.min(maxLength, hash.length);
Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length);
System.arraycopy(hash, 0, dest, offset, maxLength);
return maxLength;
}
/**
* Returns the number of bits in this hash code; a positive multiple of 32.
*/
public abstract int bits();
@Override public boolean equals(Object object) {
if (object instanceof HashCode) {
HashCode that = (HashCode) object;
// Undocumented: this is a non-short-circuiting equals(), in case this is a cryptographic
// hash code, in which case we don't want to leak timing information
return MessageDigest.isEqual(this.asBytes(), that.asBytes());
}
return false;
}
/**
* Returns a "Java hash code" for this {@code HashCode} instance; this is well-defined
* (so, for example, you can safely put {@code HashCode} instances into a {@code
* HashSet}) but is otherwise probably not what you want to use.
*/
@Override public int hashCode() {
/*
* As long as the hash function that produced this isn't of horrible quality, this
* won't be of horrible quality either.
*/
return asInt();
}
/**
* Returns a string containing each byte of {@link #asBytes}, in order, as a two-digit unsigned
* hexadecimal number in lower case.
*
* <p>Note that if the output is considered to be a single hexadecimal number, this hash code's
* bytes are the <i>big-endian</i> representation of that number. This may be surprising since
* everything else in the hashing API uniformly treats multibyte values as little-endian. But
* this format conveniently matches that of utilities such as the UNIX {@code md5sum} command.
*/
@Override public String toString() {
byte[] bytes = asBytes();
// TODO(user): Use c.g.common.base.ByteArrays once it is open sourced.
StringBuilder sb = new StringBuilder(2 * bytes.length);
for (byte b : bytes) {
sb.append(hexDigits[(b >> 4) & 0xf]).append(hexDigits[b & 0xf]);
}
return sb.toString();
}
private static final char[] hexDigits = "0123456789abcdef".toCharArray();
}
| Java |
/*
* Copyright (C) 2006 The Guava Authors
*
* 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.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.collect.ObjectArrays;
import com.google.common.collect.Sets;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* A TimeLimiter that runs method calls in the background using an
* {@link ExecutorService}. If the time limit expires for a given method call,
* the thread running the call will be interrupted.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@Beta
public final class SimpleTimeLimiter implements TimeLimiter {
private final ExecutorService executor;
/**
* Constructs a TimeLimiter instance using the given executor service to
* execute proxied method calls.
* <p>
* <b>Warning:</b> using a bounded executor
* may be counterproductive! If the thread pool fills up, any time callers
* spend waiting for a thread may count toward their time limit, and in
* this case the call may even time out before the target method is ever
* invoked.
*
* @param executor the ExecutorService that will execute the method calls on
* the target objects; for example, a {@link
* Executors#newCachedThreadPool()}.
*/
public SimpleTimeLimiter(ExecutorService executor) {
this.executor = checkNotNull(executor);
}
/**
* Constructs a TimeLimiter instance using a {@link
* Executors#newCachedThreadPool()} to execute proxied method calls.
*
* <p><b>Warning:</b> using a bounded executor may be counterproductive! If
* the thread pool fills up, any time callers spend waiting for a thread may
* count toward their time limit, and in this case the call may even time out
* before the target method is ever invoked.
*/
public SimpleTimeLimiter() {
this(Executors.newCachedThreadPool());
}
@Override
public <T> T newProxy(final T target, Class<T> interfaceType,
final long timeoutDuration, final TimeUnit timeoutUnit) {
checkNotNull(target);
checkNotNull(interfaceType);
checkNotNull(timeoutUnit);
checkArgument(timeoutDuration > 0, "bad timeout: " + timeoutDuration);
checkArgument(interfaceType.isInterface(),
"interfaceType must be an interface type");
final Set<Method> interruptibleMethods
= findInterruptibleMethods(interfaceType);
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object obj, final Method method, final Object[] args)
throws Throwable {
Callable<Object> callable = new Callable<Object>() {
@Override
public Object call() throws Exception {
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
throwCause(e, false);
throw new AssertionError("can't get here");
}
}
};
return callWithTimeout(callable, timeoutDuration, timeoutUnit,
interruptibleMethods.contains(method));
}
};
return newProxy(interfaceType, handler);
}
// TODO: should this actually throw only ExecutionException?
@Override
public <T> T callWithTimeout(Callable<T> callable, long timeoutDuration,
TimeUnit timeoutUnit, boolean amInterruptible) throws Exception {
checkNotNull(callable);
checkNotNull(timeoutUnit);
checkArgument(timeoutDuration > 0, "timeout must be positive: %s",
timeoutDuration);
Future<T> future = executor.submit(callable);
try {
if (amInterruptible) {
try {
return future.get(timeoutDuration, timeoutUnit);
} catch (InterruptedException e) {
future.cancel(true);
throw e;
}
} else {
return Uninterruptibles.getUninterruptibly(future,
timeoutDuration, timeoutUnit);
}
} catch (ExecutionException e) {
throw throwCause(e, true);
} catch (TimeoutException e) {
future.cancel(true);
throw new UncheckedTimeoutException(e);
}
}
private static Exception throwCause(Exception e, boolean combineStackTraces)
throws Exception {
Throwable cause = e.getCause();
if (cause == null) {
throw e;
}
if (combineStackTraces) {
StackTraceElement[] combined = ObjectArrays.concat(cause.getStackTrace(),
e.getStackTrace(), StackTraceElement.class);
cause.setStackTrace(combined);
}
if (cause instanceof Exception) {
throw (Exception) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
// The cause is a weird kind of Throwable, so throw the outer exception.
throw e;
}
private static Set<Method> findInterruptibleMethods(Class<?> interfaceType) {
Set<Method> set = Sets.newHashSet();
for (Method m : interfaceType.getMethods()) {
if (declaresInterruptedEx(m)) {
set.add(m);
}
}
return set;
}
private static boolean declaresInterruptedEx(Method method) {
for (Class<?> exType : method.getExceptionTypes()) {
// debate: == or isAssignableFrom?
if (exType == InterruptedException.class) {
return true;
}
}
return false;
}
// TODO: replace with version in common.reflect if and when it's open-sourced
private static <T> T newProxy(
Class<T> interfaceType, InvocationHandler handler) {
Object object = Proxy.newProxyInstance(interfaceType.getClassLoader(),
new Class<?>[] { interfaceType }, handler);
return interfaceType.cast(object);
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
* A callback for accepting the results of a {@link java.util.concurrent.Future}
* computation asynchronously.
*
* <p>To attach to a {@link ListenableFuture} use {@link Futures#addCallback}.
*
* @author Anthony Zana
* @since 10.0
*/
@Beta
public interface FutureCallback<V> {
/**
* Invoked with the result of the {@code Future} computation when it is
* successful.
*/
void onSuccess(V result);
/**
* Invoked when a {@code Future} computation fails or is canceled.
*
* <p>If the future's {@link Future#get() get} method throws an {@link
* ExecutionException}, then the cause is passed to this method. Any other
* thrown object is passed unaltered.
*/
void onFailure(Throwable t);
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import java.util.concurrent.ExecutionException;
/**
* An object with an operational state, plus asynchronous {@link #start()} and
* {@link #stop()} lifecycle methods to transition between states.
* Example services include webservers, RPC servers and timers.
*
* <p>The normal lifecycle of a service is:
* <ul>
* <li>{@link State#NEW} -></li>
* <li>{@link State#STARTING} -></li>
* <li>{@link State#RUNNING} -></li>
* <li>{@link State#STOPPING} -></li>
* <li>{@link State#TERMINATED}</li>
* </ul>
*
* <p>The valid state transitions of a Service are:
* <ul>
* <li>{@link State#NEW} -> {@link State#STARTING}: This occurs when
* start() is called the first time and is the only valid state transition
* from the NEW state.</li>
* <li>{@link State#NEW} -> {@link State#TERMINATED}: This occurs when
* stop() is called from the NEW state.</li>
* <li>{@link State#STARTING} -> {@link State#RUNNING}: This occurs when
* a service has successfully started</li>
* <li>{@link State#STARTING} -> {@link State#FAILED}: This occurs when a
* service experiences an unrecoverable error while starting up</li>
* <li>{@link State#STARTING} -> {@link State#STOPPING}: This occurs when
* stop() is called while a service is starting up.</li>
* <li>{@link State#RUNNING} -> {@link State#STOPPING}: This occurs when
* stop() is called on a running service.</li>
* <li>{@link State#RUNNING} -> {@link State#FAILED}: This occurs when an
* unrecoverable error occurs while a service is running.</li>
* <li>{@link State#STOPPING} -> {@link State#FAILED}: This occurs when an
* unrecoverable error occurs while a service is stopping.</li>
* <li>{@link State#STOPPING} -> {@link State#TERMINATED}: This occurs
* when the service successfully stops.</li>
* </ul>
*
* <p>N.B. The {@link State#FAILED} and {@link State#TERMINATED} states are
* terminal states, once a service enters either of these states it cannot ever
* leave them.
*
* <p>Implementors of this interface are strongly encouraged to extend one of
* the abstract classes in this package which implement this interface and
* make the threading and state management easier.
*
* @author Jesse Wilson
* @since 9.0 (in 1.0 as
* {@code com.google.common.base.Service})
*/
@Beta // TODO(kevinb): make abstract class?
public interface Service {
/**
* If the service state is {@link State#NEW}, this initiates service startup
* and returns immediately. If the service has already been started, this
* method returns immediately without taking action. A stopped service may not
* be restarted.
*
* @return a future for the startup result, regardless of whether this call
* initiated startup. Calling {@link ListenableFuture#get} will block
* until the service has finished starting, and returns one of {@link
* State#RUNNING}, {@link State#STOPPING} or {@link State#TERMINATED}. If
* the service fails to start, {@link ListenableFuture#get} will throw an
* {@link ExecutionException}, and the service's state will be {@link
* State#FAILED}. If it has already finished starting, {@link
* ListenableFuture#get} returns immediately. Cancelling this future has
* no effect on the service.
*/
ListenableFuture<State> start();
/**
* Initiates service startup (if necessary), returning once the service has
* finished starting. Unlike calling {@code start().get()}, this method throws
* no checked exceptions, and it cannot be {@linkplain Thread#interrupt
* interrupted}.
*
* @throws UncheckedExecutionException if startup failed
* @return the state of the service when startup finished.
*/
State startAndWait();
/**
* Returns {@code true} if this service is {@linkplain State#RUNNING running}.
*/
boolean isRunning();
/**
* Returns the lifecycle state of the service.
*/
State state();
/**
* If the service is {@linkplain State#STARTING starting} or {@linkplain
* State#RUNNING running}, this initiates service shutdown and returns
* immediately. If the service is {@linkplain State#NEW new}, it is
* {@linkplain State#TERMINATED terminated} without having been started nor
* stopped. If the service has already been stopped, this method returns
* immediately without taking action.
*
* @return a future for the shutdown result, regardless of whether this call
* initiated shutdown. Calling {@link ListenableFuture#get} will block
* until the service has finished shutting down, and either returns
* {@link State#TERMINATED} or throws an {@link ExecutionException}. If
* it has already finished stopping, {@link ListenableFuture#get} returns
* immediately. Cancelling this future has no effect on the service.
*/
ListenableFuture<State> stop();
/**
* Initiates service shutdown (if necessary), returning once the service has
* finished stopping. If this is {@link State#STARTING}, startup will be
* cancelled. If this is {@link State#NEW}, it is {@link State#TERMINATED
* terminated} without having been started nor stopped. Unlike calling {@code
* stop().get()}, this method throws no checked exceptions.
*
* @throws UncheckedExecutionException if shutdown failed
* @return the state of the service when shutdown finished.
*/
State stopAndWait();
/**
* The lifecycle states of a service.
*
* @since 9.0 (in 1.0 as
* {@code com.google.common.base.Service.State})
*/
@Beta // should come out of Beta when Service does
enum State {
/**
* A service in this state is inactive. It does minimal work and consumes
* minimal resources.
*/
NEW,
/**
* A service in this state is transitioning to {@link #RUNNING}.
*/
STARTING,
/**
* A service in this state is operational.
*/
RUNNING,
/**
* A service in this state is transitioning to {@link #TERMINATED}.
*/
STOPPING,
/**
* A service in this state has completed execution normally. It does minimal
* work and consumes minimal resources.
*/
TERMINATED,
/**
* A service in this state has encountered a problem and may not be
* operational. It cannot be started nor stopped.
*/
FAILED
}
}
| Java |
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
/*
* Source:
* http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/extra/AtomicDoubleArray.java?revision=1.5
* (Modified to adapt to guava coding conventions and
* to use AtomicLongArray instead of sun.misc.Unsafe)
*/
package com.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import static java.lang.Double.doubleToRawLongBits;
import static java.lang.Double.longBitsToDouble;
import java.util.concurrent.atomic.AtomicLongArray;
/**
* A {@code double} array in which elements may be updated atomically.
* See the {@link java.util.concurrent.atomic} package specification
* for description of the properties of atomic variables.
*
* <p><a name="bitEquals">This class compares primitive {@code double}
* values in methods such as {@link #compareAndSet} by comparing their
* bitwise representation using {@link Double#doubleToRawLongBits},
* which differs from both the primitive double {@code ==} operator
* and from {@link Double#equals}, as if implemented by:
* <pre> {@code
* static boolean bitEquals(double x, double y) {
* long xBits = Double.doubleToRawLongBits(x);
* long yBits = Double.doubleToRawLongBits(y);
* return xBits == yBits;
* }}</pre>
*
* @author Doug Lea
* @author Martin Buchholz
* @since 11.0
*/
@Beta
public class AtomicDoubleArray implements java.io.Serializable {
private static final long serialVersionUID = 0L;
// Making this non-final is the lesser evil according to Effective
// Java 2nd Edition Item 76: Write readObject methods defensively.
private transient AtomicLongArray longs;
/**
* Creates a new {@code AtomicDoubleArray} of the given length,
* with all elements initially zero.
*
* @param length the length of the array
*/
public AtomicDoubleArray(int length) {
this.longs = new AtomicLongArray(length);
}
/**
* Creates a new {@code AtomicDoubleArray} with the same length
* as, and all elements copied from, the given array.
*
* @param array the array to copy elements from
* @throws NullPointerException if array is null
*/
public AtomicDoubleArray(double[] array) {
final int len = array.length;
long[] longArray = new long[len];
for (int i = 0; i < len; i++) {
longArray[i] = doubleToRawLongBits(array[i]);
}
this.longs = new AtomicLongArray(longArray);
}
/**
* Returns the length of the array.
*
* @return the length of the array
*/
public final int length() {
return longs.length();
}
/**
* Gets the current value at position {@code i}.
*
* @param i the index
* @return the current value
*/
public final double get(int i) {
return longBitsToDouble(longs.get(i));
}
/**
* Sets the element at position {@code i} to the given value.
*
* @param i the index
* @param newValue the new value
*/
public final void set(int i, double newValue) {
long next = doubleToRawLongBits(newValue);
longs.set(i, next);
}
/**
* Eventually sets the element at position {@code i} to the given value.
*
* @param i the index
* @param newValue the new value
*/
public final void lazySet(int i, double newValue) {
set(i, newValue);
// TODO(user): replace with code below when jdk5 support is dropped.
// long next = doubleToRawLongBits(newValue);
// longs.lazySet(i, next);
}
/**
* Atomically sets the element at position {@code i} to the given value
* and returns the old value.
*
* @param i the index
* @param newValue the new value
* @return the previous value
*/
public final double getAndSet(int i, double newValue) {
long next = doubleToRawLongBits(newValue);
return longBitsToDouble(longs.getAndSet(i, next));
}
/**
* Atomically sets the element at position {@code i} to the given
* updated value
* if the current value is <a href="#bitEquals">bitwise equal</a>
* to the expected value.
*
* @param i the index
* @param expect the expected value
* @param update the new value
* @return true if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(int i, double expect, double update) {
return longs.compareAndSet(i,
doubleToRawLongBits(expect),
doubleToRawLongBits(update));
}
/**
* Atomically sets the element at position {@code i} to the given
* updated value
* if the current value is <a href="#bitEquals">bitwise equal</a>
* to the expected value.
*
* <p>May <a
* href="http://download.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html#Spurious">
* fail spuriously</a>
* and does not provide ordering guarantees, so is only rarely an
* appropriate alternative to {@code compareAndSet}.
*
* @param i the index
* @param expect the expected value
* @param update the new value
* @return true if successful
*/
public final boolean weakCompareAndSet(int i, double expect, double update) {
return longs.weakCompareAndSet(i,
doubleToRawLongBits(expect),
doubleToRawLongBits(update));
}
/**
* Atomically adds the given value to the element at index {@code i}.
*
* @param i the index
* @param delta the value to add
* @return the previous value
*/
public final double getAndAdd(int i, double delta) {
while (true) {
long current = longs.get(i);
double currentVal = longBitsToDouble(current);
double nextVal = currentVal + delta;
long next = doubleToRawLongBits(nextVal);
if (longs.compareAndSet(i, current, next)) {
return currentVal;
}
}
}
/**
* Atomically adds the given value to the element at index {@code i}.
*
* @param i the index
* @param delta the value to add
* @return the updated value
*/
public double addAndGet(int i, double delta) {
while (true) {
long current = longs.get(i);
double currentVal = longBitsToDouble(current);
double nextVal = currentVal + delta;
long next = doubleToRawLongBits(nextVal);
if (longs.compareAndSet(i, current, next)) {
return nextVal;
}
}
}
/**
* Returns the String representation of the current values of array.
* @return the String representation of the current values of array
*/
public String toString() {
int iMax = length() - 1;
if (iMax == -1) {
return "[]";
}
// Double.toString(Math.PI).length() == 17
StringBuilder b = new StringBuilder((17 + 2) * (iMax + 1));
b.append('[');
for (int i = 0;; i++) {
b.append(longBitsToDouble(longs.get(i)));
if (i == iMax) {
return b.append(']').toString();
}
b.append(',').append(' ');
}
}
/**
* Saves the state to a stream (that is, serializes it).
*
* @serialData The length of the array is emitted (int), followed by all
* of its elements (each a {@code double}) in the proper order.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
s.defaultWriteObject();
// Write out array length
int length = length();
s.writeInt(length);
// Write out all elements in the proper order.
for (int i = 0; i < length; i++) {
s.writeDouble(get(i));
}
}
/**
* Reconstitutes the instance from a stream (that is, deserializes it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
// Read in array length and allocate array
int length = s.readInt();
this.longs = new AtomicLongArray(length);
// Read in all elements in the proper order.
for (int i = 0; i < length; i++) {
set(i, s.readDouble());
}
}
}
| Java |
/*
* Copyright (C) 2006 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
/**
* Produces proxies that impose a time limit on method
* calls to the proxied object. For example, to return the value of
* {@code target.someMethod()}, but substitute {@code DEFAULT_VALUE} if this
* method call takes over 50 ms, you can use this code:
* <pre>
* TimeLimiter limiter = . . .;
* TargetType proxy = limiter.newProxy(
* target, TargetType.class, 50, TimeUnit.MILLISECONDS);
* try {
* return proxy.someMethod();
* } catch (UncheckedTimeoutException e) {
* return DEFAULT_VALUE;
* }
* </pre>
* Please see {@code SimpleTimeLimiterTest} for more usage examples.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@Beta
public interface TimeLimiter {
/**
* Returns an instance of {@code interfaceType} that delegates all method
* calls to the {@code target} object, enforcing the specified time limit on
* each call. This time-limited delegation is also performed for calls to
* {@link Object#equals}, {@link Object#hashCode}, and
* {@link Object#toString}.
* <p>
* If the target method call finishes before the limit is reached, the return
* value or exception is propagated to the caller exactly as-is. If, on the
* other hand, the time limit is reached, the proxy will attempt to abort the
* call to the target, and will throw an {@link UncheckedTimeoutException} to
* the caller.
* <p>
* It is important to note that the primary purpose of the proxy object is to
* return control to the caller when the timeout elapses; aborting the target
* method call is of secondary concern. The particular nature and strength
* of the guarantees made by the proxy is implementation-dependent. However,
* it is important that each of the methods on the target object behaves
* appropriately when its thread is interrupted.
*
* @param target the object to proxy
* @param interfaceType the interface you wish the returned proxy to
* implement
* @param timeoutDuration with timeoutUnit, the maximum length of time that
* callers are willing to wait on each method call to the proxy
* @param timeoutUnit with timeoutDuration, the maximum length of time that
* callers are willing to wait on each method call to the proxy
* @return a time-limiting proxy
* @throws IllegalArgumentException if {@code interfaceType} is a regular
* class, enum, or annotation type, rather than an interface
*/
<T> T newProxy(T target, Class<T> interfaceType,
long timeoutDuration, TimeUnit timeoutUnit);
/**
* Invokes a specified Callable, timing out after the specified time limit.
* If the target method call finished before the limit is reached, the return
* value or exception is propagated to the caller exactly as-is. If, on the
* other hand, the time limit is reached, we attempt to abort the call to the
* target, and throw an {@link UncheckedTimeoutException} to the caller.
* <p>
* <b>Warning:</b> The future of this method is in doubt. It may be nuked, or
* changed significantly.
*
* @param callable the Callable to execute
* @param timeoutDuration with timeoutUnit, the maximum length of time to wait
* @param timeoutUnit with timeoutDuration, the maximum length of time to wait
* @param interruptible whether to respond to thread interruption by aborting
* the operation and throwing InterruptedException; if false, the
* operation is allowed to complete or time out, and the current thread's
* interrupt status is re-asserted.
* @return the result returned by the Callable
* @throws InterruptedException if {@code interruptible} is true and our
* thread is interrupted during execution
* @throws UncheckedTimeoutException if the time limit is reached
* @throws Exception
*/
<T> T callWithTimeout(Callable<T> callable, long timeoutDuration,
TimeUnit timeoutUnit, boolean interruptible) throws Exception;
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.base.Preconditions;
import java.util.concurrent.Executor;
/**
* A {@link ListenableFuture} which forwards all its method calls to another
* future. Subclasses should override one or more methods to modify the behavior
* of the backing future as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p>Most subclasses can just use {@link SimpleForwardingListenableFuture}.
*
* @param <V> The result type returned by this Future's {@code get} method
*
* @author Shardul Deo
* @since 4.0
*/
public abstract class ForwardingListenableFuture<V> extends ForwardingFuture<V>
implements ListenableFuture<V> {
/** Constructor for use by subclasses. */
protected ForwardingListenableFuture() {}
@Override
protected abstract ListenableFuture<V> delegate();
@Override
public void addListener(Runnable listener, Executor exec) {
delegate().addListener(listener, exec);
}
/*
* TODO(cpovirk): Use standard Javadoc form for SimpleForwarding* class and
* constructor
*/
/**
* A simplified version of {@link ForwardingListenableFuture} where subclasses
* can pass in an already constructed {@link ListenableFuture}
* as the delegate.
*
* @since 9.0
*/
public abstract static class SimpleForwardingListenableFuture<V>
extends ForwardingListenableFuture<V> {
private final ListenableFuture<V> delegate;
protected SimpleForwardingListenableFuture(ListenableFuture<V> delegate) {
this.delegate = Preconditions.checkNotNull(delegate);
}
@Override
protected final ListenableFuture<V> delegate() {
return delegate;
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.collect.ForwardingObject;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* An executor service which forwards all its method calls to another executor
* service. Subclasses should override one or more methods to modify the
* behavior of the backing executor service as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Kurt Alfred Kluever
* @since 10.0
*/
public abstract class ForwardingExecutorService extends ForwardingObject
implements ExecutorService {
/** Constructor for use by subclasses. */
protected ForwardingExecutorService() {}
@Override
protected abstract ExecutorService delegate();
@Override
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
return delegate().awaitTermination(timeout, unit);
}
@Override
public <T> List<Future<T>> invokeAll(
Collection<? extends Callable<T>> tasks) throws InterruptedException {
return delegate().invokeAll(tasks);
}
@Override
public <T> List<Future<T>> invokeAll(
Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException {
return delegate().invokeAll(tasks, timeout, unit);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException {
return delegate().invokeAny(tasks);
}
@Override
public <T> T invokeAny(
Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return delegate().invokeAny(tasks, timeout, unit);
}
@Override
public boolean isShutdown() {
return delegate().isShutdown();
}
@Override
public boolean isTerminated() {
return delegate().isTerminated();
}
@Override
public void shutdown() {
delegate().shutdown();
}
@Override
public List<Runnable> shutdownNow() {
return delegate().shutdownNow();
}
@Override
public void execute(Runnable command) {
delegate().execute(command);
}
public <T> Future<T> submit(Callable<T> task) {
return delegate().submit(task);
}
@Override
public Future<?> submit(Runnable task) {
return delegate().submit(task);
}
@Override
public <T> Future<T> submit(Runnable task, T result) {
return delegate().submit(task, result);
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.util.concurrent;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Utilities for treating interruptible operations as uninterruptible.
* In all cases, if a thread is interrupted during such a call, the call
* continues to block until the result is available or the timeout elapses,
* and only then re-interrupts the thread.
*
* @author Anthony Zana
* @since 10.0
*/
@Beta
public final class Uninterruptibles {
// Implementation Note: As of 3-7-11, the logic for each blocking/timeout
// methods is identical, save for method being invoked.
/**
* Invokes {@code latch.}{@link CountDownLatch#await() await()}
* uninterruptibly.
*/
public static void awaitUninterruptibly(CountDownLatch latch) {
boolean interrupted = false;
try {
while (true) {
try {
latch.await();
return;
} catch (InterruptedException e) {
interrupted = true;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
/**
* Invokes
* {@code latch.}{@link CountDownLatch#await(long, TimeUnit)
* await(timeout, unit)} uninterruptibly.
*/
public static boolean awaitUninterruptibly(CountDownLatch latch,
long timeout, TimeUnit unit) {
boolean interrupted = false;
try {
long remainingNanos = unit.toNanos(timeout);
long end = System.nanoTime() + remainingNanos;
while (true) {
try {
// CountDownLatch treats negative timeouts just like zero.
return latch.await(remainingNanos, NANOSECONDS);
} catch (InterruptedException e) {
interrupted = true;
remainingNanos = end - System.nanoTime();
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
/**
* Invokes {@code toJoin.}{@link Thread#join() join()} uninterruptibly.
*/
public static void joinUninterruptibly(Thread toJoin) {
boolean interrupted = false;
try {
while (true) {
try {
toJoin.join();
return;
} catch (InterruptedException e) {
interrupted = true;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
/**
* Invokes {@code future.}{@link Future#get() get()} uninterruptibly.
* To get uninterruptibility and remove checked exceptions, see
* {@link Futures#getUnchecked}.
*
* <p>If instead, you wish to treat {@link InterruptedException} uniformly
* with other exceptions, see {@link Futures#get(Future, Class) Futures.get}
* or {@link Futures#makeChecked}.
*/
public static <V> V getUninterruptibly(Future<V> future)
throws ExecutionException {
boolean interrupted = false;
try {
while (true) {
try {
return future.get();
} catch (InterruptedException e) {
interrupted = true;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
/**
* Invokes
* {@code future.}{@link Future#get(long, TimeUnit) get(timeout, unit)}
* uninterruptibly.
*
* <p>If instead, you wish to treat {@link InterruptedException} uniformly
* with other exceptions, see {@link Futures#get(Future, Class) Futures.get}
* or {@link Futures#makeChecked}.
*/
public static <V> V getUninterruptibly(
Future<V> future, long timeout, TimeUnit unit)
throws ExecutionException, TimeoutException {
boolean interrupted = false;
try {
long remainingNanos = unit.toNanos(timeout);
long end = System.nanoTime() + remainingNanos;
while (true) {
try {
// Future treats negative timeouts just like zero.
return future.get(remainingNanos, NANOSECONDS);
} catch (InterruptedException e) {
interrupted = true;
remainingNanos = end - System.nanoTime();
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
/**
* Invokes
* {@code unit.}{@link TimeUnit#timedJoin(Thread, long)
* timedJoin(toJoin, timeout)} uninterruptibly.
*/
public static void joinUninterruptibly(Thread toJoin,
long timeout, TimeUnit unit) {
Preconditions.checkNotNull(toJoin);
boolean interrupted = false;
try {
long remainingNanos = unit.toNanos(timeout);
long end = System.nanoTime() + remainingNanos;
while (true) {
try {
// TimeUnit.timedJoin() treats negative timeouts just like zero.
NANOSECONDS.timedJoin(toJoin, remainingNanos);
return;
} catch (InterruptedException e) {
interrupted = true;
remainingNanos = end - System.nanoTime();
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
/**
* Invokes {@code queue.}{@link BlockingQueue#take() take()} uninterruptibly.
*/
public static <E> E takeUninterruptibly(BlockingQueue<E> queue) {
boolean interrupted = false;
try {
while (true) {
try {
return queue.take();
} catch (InterruptedException e) {
interrupted = true;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
/**
* Invokes {@code queue.}{@link BlockingQueue#put(Object) put(element)}
* uninterruptibly.
*/
public static <E> void putUninterruptibly(BlockingQueue<E> queue, E element) {
boolean interrupted = false;
try {
while (true) {
try {
queue.put(element);
return;
} catch (InterruptedException e) {
interrupted = true;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
// TODO(user): Support Sleeper somehow (wrapper or interface method)?
/**
* Invokes {@code unit.}{@link TimeUnit#sleep(long) sleep(sleepFor)}
* uninterruptibly.
*/
public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) {
boolean interrupted = false;
try {
long remainingNanos = unit.toNanos(sleepFor);
long end = System.nanoTime() + remainingNanos;
while (true) {
try {
// TimeUnit.sleep() treats negative timeouts just like zero.
NANOSECONDS.sleep(remainingNanos);
return;
} catch (InterruptedException e) {
interrupted = true;
remainingNanos = end - System.nanoTime();
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
// TODO(user): Add support for waitUninterruptibly.
private Uninterruptibles() {}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import javax.annotation.Nullable;
/**
* An abstract implementation of the {@link ListenableFuture} interface. This
* class is preferable to {@link java.util.concurrent.FutureTask} for two
* reasons: It implements {@code ListenableFuture}, and it does not implement
* {@code Runnable}. (If you want a {@code Runnable} implementation of {@code
* ListenableFuture}, create a {@link ListenableFutureTask}, or submit your
* tasks to a {@link ListeningExecutorService}.)
*
* <p>This class implements all methods in {@code ListenableFuture}.
* Subclasses should provide a way to set the result of the computation through
* the protected methods {@link #set(Object)} and
* {@link #setException(Throwable)}. Subclasses may also override {@link
* #interruptTask()}, which will be invoked automatically if a call to {@link
* #cancel(boolean) cancel(true)} succeeds in canceling the future.
*
* <p>{@code AbstractFuture} uses an {@link AbstractQueuedSynchronizer} to deal
* with concurrency issues and guarantee thread safety.
*
* <p>The state changing methods all return a boolean indicating success or
* failure in changing the future's state. Valid states are running,
* completed, failed, or cancelled.
*
* <p>This class uses an {@link ExecutionList} to guarantee that all registered
* listeners will be executed, either when the future finishes or, for listeners
* that are added after the future completes, immediately.
* {@code Runnable}-{@code Executor} pairs are stored in the execution list but
* are not necessarily executed in the order in which they were added. (If a
* listener is added after the Future is complete, it will be executed
* immediately, even if earlier listeners have not been executed. Additionally,
* executors need not guarantee FIFO execution, or different listeners may run
* in different executors.)
*
* @author Sven Mawson
* @since 1.0
*/
public abstract class AbstractFuture<V> implements ListenableFuture<V> {
/** Synchronization control for AbstractFutures. */
private final Sync<V> sync = new Sync<V>();
// The execution list to hold our executors.
private final ExecutionList executionList = new ExecutionList();
/*
* Improve the documentation of when InterruptedException is thrown. Our
* behavior matches the JDK's, but the JDK's documentation is misleading.
*/
/**
* {@inheritDoc}
*
* <p>The default {@link AbstractFuture} implementation throws {@code
* InterruptedException} if the current thread is interrupted before or during
* the call, even if the value is already available.
*
* @throws InterruptedException if the current thread was interrupted before
* or during the call (optional but recommended).
* @throws CancellationException {@inheritDoc}
*/
@Override
public V get(long timeout, TimeUnit unit) throws InterruptedException,
TimeoutException, ExecutionException {
return sync.get(unit.toNanos(timeout));
}
/*
* Improve the documentation of when InterruptedException is thrown. Our
* behavior matches the JDK's, but the JDK's documentation is misleading.
*/
/**
* {@inheritDoc}
*
* <p>The default {@link AbstractFuture} implementation throws {@code
* InterruptedException} if the current thread is interrupted before or during
* the call, even if the value is already available.
*
* @throws InterruptedException if the current thread was interrupted before
* or during the call (optional but recommended).
* @throws CancellationException {@inheritDoc}
*/
@Override
public V get() throws InterruptedException, ExecutionException {
return sync.get();
}
@Override
public boolean isDone() {
return sync.isDone();
}
@Override
public boolean isCancelled() {
return sync.isCancelled();
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (!sync.cancel()) {
return false;
}
executionList.execute();
if (mayInterruptIfRunning) {
interruptTask();
}
return true;
}
/**
* Subclasses can override this method to implement interruption of the
* future's computation. The method is invoked automatically by a successful
* call to {@link #cancel(boolean) cancel(true)}.
*
* <p>The default implementation does nothing.
*
* @since 10.0
*/
protected void interruptTask() {
}
/**
* {@inheritDoc}
*
* @since 10.0
*/
@Override
public void addListener(Runnable listener, Executor exec) {
executionList.add(listener, exec);
}
/**
* Subclasses should invoke this method to set the result of the computation
* to {@code value}. This will set the state of the future to
* {@link AbstractFuture.Sync#COMPLETED} and invoke the listeners if the
* state was successfully changed.
*
* @param value the value that was the result of the task.
* @return true if the state was successfully changed.
*/
protected boolean set(@Nullable V value) {
boolean result = sync.set(value);
if (result) {
executionList.execute();
}
return result;
}
/**
* Subclasses should invoke this method to set the result of the computation
* to an error, {@code throwable}. This will set the state of the future to
* {@link AbstractFuture.Sync#COMPLETED} and invoke the listeners if the
* state was successfully changed.
*
* @param throwable the exception that the task failed with.
* @return true if the state was successfully changed.
* @throws Error if the throwable was an {@link Error}.
*/
protected boolean setException(Throwable throwable) {
boolean result = sync.setException(checkNotNull(throwable));
if (result) {
executionList.execute();
}
// If it's an Error, we want to make sure it reaches the top of the
// call stack, so we rethrow it.
if (throwable instanceof Error) {
throw (Error) throwable;
}
return result;
}
/**
* <p>Following the contract of {@link AbstractQueuedSynchronizer} we create a
* private subclass to hold the synchronizer. This synchronizer is used to
* implement the blocking and waiting calls as well as to handle state changes
* in a thread-safe manner. The current state of the future is held in the
* Sync state, and the lock is released whenever the state changes to either
* {@link #COMPLETED} or {@link #CANCELLED}.
*
* <p>To avoid races between threads doing release and acquire, we transition
* to the final state in two steps. One thread will successfully CAS from
* RUNNING to COMPLETING, that thread will then set the result of the
* computation, and only then transition to COMPLETED or CANCELLED.
*
* <p>We don't use the integer argument passed between acquire methods so we
* pass around a -1 everywhere.
*/
static final class Sync<V> extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 0L;
/* Valid states. */
static final int RUNNING = 0;
static final int COMPLETING = 1;
static final int COMPLETED = 2;
static final int CANCELLED = 4;
private V value;
private Throwable exception;
/*
* Acquisition succeeds if the future is done, otherwise it fails.
*/
@Override
protected int tryAcquireShared(int ignored) {
if (isDone()) {
return 1;
}
return -1;
}
/*
* We always allow a release to go through, this means the state has been
* successfully changed and the result is available.
*/
@Override
protected boolean tryReleaseShared(int finalState) {
setState(finalState);
return true;
}
/**
* Blocks until the task is complete or the timeout expires. Throws a
* {@link TimeoutException} if the timer expires, otherwise behaves like
* {@link #get()}.
*/
V get(long nanos) throws TimeoutException, CancellationException,
ExecutionException, InterruptedException {
// Attempt to acquire the shared lock with a timeout.
if (!tryAcquireSharedNanos(-1, nanos)) {
throw new TimeoutException("Timeout waiting for task.");
}
return getValue();
}
/**
* Blocks until {@link #complete(Object, Throwable, int)} has been
* successfully called. Throws a {@link CancellationException} if the task
* was cancelled, or a {@link ExecutionException} if the task completed with
* an error.
*/
V get() throws CancellationException, ExecutionException,
InterruptedException {
// Acquire the shared lock allowing interruption.
acquireSharedInterruptibly(-1);
return getValue();
}
/**
* Implementation of the actual value retrieval. Will return the value
* on success, an exception on failure, a cancellation on cancellation, or
* an illegal state if the synchronizer is in an invalid state.
*/
private V getValue() throws CancellationException, ExecutionException {
int state = getState();
switch (state) {
case COMPLETED:
if (exception != null) {
throw new ExecutionException(exception);
} else {
return value;
}
case CANCELLED:
throw new CancellationException("Task was cancelled.");
default:
throw new IllegalStateException(
"Error, synchronizer in invalid state: " + state);
}
}
/**
* Checks if the state is {@link #COMPLETED} or {@link #CANCELLED}.
*/
boolean isDone() {
return (getState() & (COMPLETED | CANCELLED)) != 0;
}
/**
* Checks if the state is {@link #CANCELLED}.
*/
boolean isCancelled() {
return getState() == CANCELLED;
}
/**
* Transition to the COMPLETED state and set the value.
*/
boolean set(@Nullable V v) {
return complete(v, null, COMPLETED);
}
/**
* Transition to the COMPLETED state and set the exception.
*/
boolean setException(Throwable t) {
return complete(null, t, COMPLETED);
}
/**
* Transition to the CANCELLED state.
*/
boolean cancel() {
return complete(null, null, CANCELLED);
}
/**
* Implementation of completing a task. Either {@code v} or {@code t} will
* be set but not both. The {@code finalState} is the state to change to
* from {@link #RUNNING}. If the state is not in the RUNNING state we
* return {@code false} after waiting for the state to be set to a valid
* final state ({@link #COMPLETED} or {@link #CANCELLED}).
*
* @param v the value to set as the result of the computation.
* @param t the exception to set as the result of the computation.
* @param finalState the state to transition to.
*/
private boolean complete(@Nullable V v, @Nullable Throwable t,
int finalState) {
boolean doCompletion = compareAndSetState(RUNNING, COMPLETING);
if (doCompletion) {
// If this thread successfully transitioned to COMPLETING, set the value
// and exception and then release to the final state.
this.value = v;
this.exception = t;
releaseShared(finalState);
} else if (getState() == COMPLETING) {
// If some other thread is currently completing the future, block until
// they are done so we can guarantee completion.
acquireShared(-1);
}
return doCompletion;
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import com.google.common.collect.ForwardingObject;
/**
* A {@link Service} that forwards all method calls to another service.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public abstract class ForwardingService extends ForwardingObject
implements Service {
/** Constructor for use by subclasses. */
protected ForwardingService() {}
@Override protected abstract Service delegate();
@Override public ListenableFuture<State> start() {
return delegate().start();
}
@Override public State state() {
return delegate().state();
}
@Override public ListenableFuture<State> stop() {
return delegate().stop();
}
@Override public State startAndWait() {
return delegate().startAndWait();
}
@Override public State stopAndWait() {
return delegate().stopAndWait();
}
@Override public boolean isRunning() {
return delegate().isRunning();
}
/**
* A sensible default implementation of {@link #startAndWait()}, in terms of
* {@link #start}. If you override {@link #start}, you may wish to override
* {@link #startAndWait()} to forward to this implementation.
* @since 9.0
*/
protected State standardStartAndWait() {
return Futures.getUnchecked(start());
}
/**
* A sensible default implementation of {@link #stopAndWait()}, in terms of
* {@link #stop}. If you override {@link #stop}, you may wish to override
* {@link #stopAndWait()} to forward to this implementation.
* @since 9.0
*/
protected State standardStopAndWait() {
return Futures.getUnchecked(stop());
}
}
| Java |
/*
* Copyright (C) 2006 The Guava Authors
*
* 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.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import static com.google.common.util.concurrent.Uninterruptibles.putUninterruptibly;
import static com.google.common.util.concurrent.Uninterruptibles.takeUninterruptibly;
import static java.lang.Thread.currentThread;
import static java.util.Arrays.asList;
import com.google.common.annotations.Beta;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to the {@link Future} interface.
*
* <p>Many of these methods use the {@link ListenableFuture} API; consult the
* Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained">
* {@code ListenableFuture}</a>.
*
* @author Kevin Bourrillion
* @author Nishant Thakkar
* @author Sven Mawson
* @since 1.0
*/
@Beta
public final class Futures {
private Futures() {}
/**
* Creates a {@link CheckedFuture} out of a normal {@link ListenableFuture}
* and a {@link Function} that maps from {@link Exception} instances into the
* appropriate checked type.
*
* <p>The given mapping function will be applied to an
* {@link InterruptedException}, a {@link CancellationException}, or an
* {@link ExecutionException} with the actual cause of the exception.
* See {@link Future#get()} for details on the exceptions thrown.
*
* @since 9.0 (source-compatible since 1.0)
*/
public static <V, X extends Exception> CheckedFuture<V, X> makeChecked(
ListenableFuture<V> future, Function<Exception, X> mapper) {
return new MappingCheckedFuture<V, X>(checkNotNull(future), mapper);
}
/**
* Creates a {@code ListenableFuture} which has its value set immediately upon
* construction. The getters just return the value. This {@code Future} can't
* be canceled or timed out and its {@code isDone()} method always returns
* {@code true}.
*/
public static <V> ListenableFuture<V> immediateFuture(@Nullable V value) {
SettableFuture<V> future = SettableFuture.create();
future.set(value);
return future;
}
/**
* Returns a {@code CheckedFuture} which has its value set immediately upon
* construction.
*
* <p>The returned {@code Future} can't be cancelled, and its {@code isDone()}
* method always returns {@code true}. Calling {@code get()} or {@code
* checkedGet()} will immediately return the provided value.
*/
public static <V, X extends Exception> CheckedFuture<V, X>
immediateCheckedFuture(@Nullable V value) {
SettableFuture<V> future = SettableFuture.create();
future.set(value);
return Futures.makeChecked(future, new Function<Exception, X>() {
@Override
public X apply(Exception e) {
throw new AssertionError("impossible");
}
});
}
/**
* Returns a {@code ListenableFuture} which has an exception set immediately
* upon construction.
*
* <p>The returned {@code Future} can't be cancelled, and its {@code isDone()}
* method always returns {@code true}. Calling {@code get()} will immediately
* throw the provided {@code Throwable} wrapped in an {@code
* ExecutionException}.
*
* @throws Error if the throwable is an {@link Error}.
*/
public static <V> ListenableFuture<V> immediateFailedFuture(
Throwable throwable) {
checkNotNull(throwable);
SettableFuture<V> future = SettableFuture.create();
future.setException(throwable);
return future;
}
/**
* Returns a {@code CheckedFuture} which has an exception set immediately upon
* construction.
*
* <p>The returned {@code Future} can't be cancelled, and its {@code isDone()}
* method always returns {@code true}. Calling {@code get()} will immediately
* throw the provided {@code Throwable} wrapped in an {@code
* ExecutionException}, and calling {@code checkedGet()} will throw the
* provided exception itself.
*
* @throws Error if the throwable is an {@link Error}.
*/
public static <V, X extends Exception> CheckedFuture<V, X>
immediateFailedCheckedFuture(final X exception) {
checkNotNull(exception);
return makeChecked(Futures.<V>immediateFailedFuture(exception),
new Function<Exception, X>() {
@Override
public X apply(Exception e) {
return exception;
}
});
}
/**
* Returns a new {@code ListenableFuture} whose result is asynchronously
* derived from the result of the given {@code Future}. More precisely, the
* returned {@code Future} takes its result from a {@code Future} produced by
* applying the given {@code AsyncFunction} to the result of the original
* {@code Future}. Example:
*
* <pre> {@code
* ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
* AsyncFunction<RowKey, QueryResult> queryFunction =
* new AsyncFunction<RowKey, QueryResult>() {
* public ListenableFuture<QueryResult> apply(RowKey rowKey) {
* return dataService.read(rowKey);
* }
* };
* ListenableFuture<QueryResult> queryFuture =
* transform(rowKeyFuture, queryFunction);
* }</pre>
*
* <p>Note: This overload of {@code transform} is designed for cases in which
* the work of creating the derived {@code Future} is fast and lightweight,
* as the method does not accept an {@code Executor} in which to perform the
* the work. (The created {@code Future} itself need not complete quickly.)
* For heavier operations, this overload carries some caveats: First, the
* thread that {@code function.apply} runs in depends on whether the input
* {@code Future} is done at the time {@code transform} is called. In
* particular, if called late, {@code transform} will run the operation in
* the thread that called {@code transform}. Second, {@code function.apply}
* may run in an internal thread of the system responsible for the input
* {@code Future}, such as an RPC network thread. Finally, during the
* execution of a {@code sameThreadExecutor} {@code function.apply}, all
* other registered but unexecuted listeners are prevented from running, even
* if those listeners are to run in other executors.
*
* <p>The returned {@code Future} attempts to keep its cancellation state in
* sync with that of the input future and that of the future returned by the
* function. That is, if the returned {@code Future} is cancelled, it will
* attempt to cancel the other two, and if either of the other two is
* cancelled, the returned {@code Future} will receive a callback in which it
* will attempt to cancel itself.
*
* @param input The future to transform
* @param function A function to transform the result of the input future
* to the result of the output future
* @return A future that holds result of the function (if the input succeeded)
* or the original input's failure (if not)
* @since 11.0
*/
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
AsyncFunction<? super I, ? extends O> function) {
return transform(input, function, MoreExecutors.sameThreadExecutor());
}
/**
* Returns a new {@code ListenableFuture} whose result is asynchronously
* derived from the result of the given {@code Future}. More precisely, the
* returned {@code Future} takes its result from a {@code Future} produced by
* applying the given {@code AsyncFunction} to the result of the original
* {@code Future}. Example:
*
* <pre> {@code
* ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
* AsyncFunction<RowKey, QueryResult> queryFunction =
* new AsyncFunction<RowKey, QueryResult>() {
* public ListenableFuture<QueryResult> apply(RowKey rowKey) {
* return dataService.read(rowKey);
* }
* };
* ListenableFuture<QueryResult> queryFuture =
* transform(rowKeyFuture, queryFunction, executor);
* }</pre>
*
* <p>The returned {@code Future} attempts to keep its cancellation state in
* sync with that of the input future and that of the future returned by the
* chain function. That is, if the returned {@code Future} is cancelled, it
* will attempt to cancel the other two, and if either of the other two is
* cancelled, the returned {@code Future} will receive a callback in which it
* will attempt to cancel itself.
*
* <p>Note: For cases in which the work of creating the derived future is
* fast and lightweight, consider {@linkplain
* Futures#transform(ListenableFuture, Function) the other overload} or
* explicit use of {@code sameThreadExecutor}. For heavier derivations, this
* choice carries some caveats: First, the thread that {@code function.apply}
* runs in depends on whether the input {@code Future} is done at the time
* {@code transform} is called. In particular, if called late, {@code
* transform} will run the operation in the thread that called {@code
* transform}. Second, {@code function.apply} may run in an internal thread
* of the system responsible for the input {@code Future}, such as an RPC
* network thread. Finally, during the execution of a {@code
* sameThreadExecutor} {@code function.apply}, all other registered but
* unexecuted listeners are prevented from running, even if those listeners
* are to run in other executors.
*
* @param input The future to transform
* @param function A function to transform the result of the input future
* to the result of the output future
* @param executor Executor to run the function in.
* @return A future that holds result of the function (if the input succeeded)
* or the original input's failure (if not)
* @since 11.0
*/
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
AsyncFunction<? super I, ? extends O> function,
Executor executor) {
ChainingListenableFuture<I, O> output =
new ChainingListenableFuture<I, O>(function, input);
input.addListener(output, executor);
return output;
}
/**
* Returns a new {@code ListenableFuture} whose result is the product of
* applying the given {@code Function} to the result of the given {@code
* Future}. Example:
*
* <pre> {@code
* ListenableFuture<QueryResult> queryFuture = ...;
* Function<QueryResult, List<Row>> rowsFunction =
* new Function<QueryResult, List<Row>>() {
* public List<Row> apply(QueryResult queryResult) {
* return queryResult.getRows();
* }
* };
* ListenableFuture<List<Row>> rowsFuture =
* transform(queryFuture, rowsFunction);
* }</pre>
*
* <p>Note: This overload of {@code transform} is designed for cases in which
* the transformation is fast and lightweight, as the method does not accept
* an {@code Executor} in which to perform the the work. For heavier
* transformations, this overload carries some caveats: First, the thread
* that the transformation runs in depends on whether the input {@code
* Future} is done at the time {@code transform} is called. In particular, if
* called late, {@code transform} will perform the transformation in the
* thread that called {@code transform}. Second, transformations may run in
* an internal thread of the system responsible for the input {@code Future},
* such as an RPC network thread. Finally, during the execution of a {@code
* sameThreadExecutor} transformation, all other registered but unexecuted
* listeners are prevented from running, even if those listeners are to run
* in other executors.
*
* <p>The returned {@code Future} attempts to keep its cancellation state in
* sync with that of the input future. That is, if the returned {@code Future}
* is cancelled, it will attempt to cancel the input, and if the input is
* cancelled, the returned {@code Future} will receive a callback in which it
* will attempt to cancel itself.
*
* <p>An example use of this method is to convert a serializable object
* returned from an RPC into a POJO.
*
* @param input The future to transform
* @param function A Function to transform the results of the provided future
* to the results of the returned future. This will be run in the thread
* that notifies input it is complete.
* @return A future that holds result of the transformation.
* @since 9.0 (in 1.0 as {@code compose})
*/
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
final Function<? super I, ? extends O> function) {
return transform(input, function, MoreExecutors.sameThreadExecutor());
}
/**
* Returns a new {@code ListenableFuture} whose result is the product of
* applying the given {@code Function} to the result of the given {@code
* Future}. Example:
*
* <pre> {@code
* ListenableFuture<QueryResult> queryFuture = ...;
* Function<QueryResult, List<Row>> rowsFunction =
* new Function<QueryResult, List<Row>>() {
* public List<Row> apply(QueryResult queryResult) {
* return queryResult.getRows();
* }
* };
* ListenableFuture<List<Row>> rowsFuture =
* transform(queryFuture, rowsFunction, executor);
* }</pre>
*
* <p>The returned {@code Future} attempts to keep its cancellation state in
* sync with that of the input future. That is, if the returned {@code Future}
* is cancelled, it will attempt to cancel the input, and if the input is
* cancelled, the returned {@code Future} will receive a callback in which it
* will attempt to cancel itself.
*
* <p>An example use of this method is to convert a serializable object
* returned from an RPC into a POJO.
*
* <p>Note: For cases in which the transformation is fast and lightweight,
* consider {@linkplain Futures#transform(ListenableFuture, Function) the
* other overload} or explicit use of {@link
* MoreExecutors#sameThreadExecutor}. For heavier transformations, this
* choice carries some caveats: First, the thread that the transformation
* runs in depends on whether the input {@code Future} is done at the time
* {@code transform} is called. In particular, if called late, {@code
* transform} will perform the transformation in the thread that called
* {@code transform}. Second, transformations may run in an internal thread
* of the system responsible for the input {@code Future}, such as an RPC
* network thread. Finally, during the execution of a {@code
* sameThreadExecutor} transformation, all other registered but unexecuted
* listeners are prevented from running, even if those listeners are to run
* in other executors.
*
* @param input The future to transform
* @param function A Function to transform the results of the provided future
* to the results of the returned future.
* @param executor Executor to run the function in.
* @return A future that holds result of the transformation.
* @since 9.0 (in 2.0 as {@code compose})
*/
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
final Function<? super I, ? extends O> function, Executor executor) {
checkNotNull(function);
AsyncFunction<I, O> wrapperFunction
= new AsyncFunction<I, O>() {
@Override public ListenableFuture<O> apply(I input) {
O output = function.apply(input);
return immediateFuture(output);
}
};
return transform(input, wrapperFunction, executor);
}
/**
* Like {@link #transform(ListenableFuture, Function)} except that the
* transformation {@code function} is invoked on each call to
* {@link Future#get() get()} on the returned future.
*
* <p>The returned {@code Future} reflects the input's cancellation
* state directly, and any attempt to cancel the returned Future is likewise
* passed through to the input Future.
*
* <p>Note that calls to {@linkplain Future#get(long, TimeUnit) timed get}
* only apply the timeout to the execution of the underlying {@code Future},
* <em>not</em> to the execution of the transformation function.
*
* <p>The primary audience of this method is callers of {@code transform}
* who don't have a {@code ListenableFuture} available and
* do not mind repeated, lazy function evaluation.
*
* @param input The future to transform
* @param function A Function to transform the results of the provided future
* to the results of the returned future.
* @return A future that returns the result of the transformation.
* @since 10.0
*/
@Beta
public static <I, O> Future<O> lazyTransform(final Future<I> input,
final Function<? super I, ? extends O> function) {
checkNotNull(input);
checkNotNull(function);
return new Future<O>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return input.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return input.isCancelled();
}
@Override
public boolean isDone() {
return input.isDone();
}
@Override
public O get() throws InterruptedException, ExecutionException {
return applyTransformation(input.get());
}
@Override
public O get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return applyTransformation(input.get(timeout, unit));
}
private O applyTransformation(I input) throws ExecutionException {
try {
return function.apply(input);
} catch (Throwable t) {
throw new ExecutionException(t);
}
}
};
}
/**
* An implementation of {@code ListenableFuture} that also implements
* {@code Runnable} so that it can be used to nest ListenableFutures.
* Once the passed-in {@code ListenableFuture} is complete, it calls the
* passed-in {@code Function} to generate the result.
*
* <p>If the function throws any checked exceptions, they should be wrapped
* in a {@code UndeclaredThrowableException} so that this class can get
* access to the cause.
*/
private static class ChainingListenableFuture<I, O>
extends AbstractFuture<O> implements Runnable {
private AsyncFunction<? super I, ? extends O> function;
private ListenableFuture<? extends I> inputFuture;
private volatile ListenableFuture<? extends O> outputFuture;
private final BlockingQueue<Boolean> mayInterruptIfRunningChannel =
new LinkedBlockingQueue<Boolean>(1);
private final CountDownLatch outputCreated = new CountDownLatch(1);
private ChainingListenableFuture(
AsyncFunction<? super I, ? extends O> function,
ListenableFuture<? extends I> inputFuture) {
this.function = checkNotNull(function);
this.inputFuture = checkNotNull(inputFuture);
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
/*
* Our additional cancellation work needs to occur even if
* !mayInterruptIfRunning, so we can't move it into interruptTask().
*/
if (super.cancel(mayInterruptIfRunning)) {
// This should never block since only one thread is allowed to cancel
// this Future.
putUninterruptibly(mayInterruptIfRunningChannel, mayInterruptIfRunning);
cancel(inputFuture, mayInterruptIfRunning);
cancel(outputFuture, mayInterruptIfRunning);
return true;
}
return false;
}
private void cancel(@Nullable Future<?> future,
boolean mayInterruptIfRunning) {
if (future != null) {
future.cancel(mayInterruptIfRunning);
}
}
@Override
public void run() {
try {
I sourceResult;
try {
sourceResult = getUninterruptibly(inputFuture);
} catch (CancellationException e) {
// Cancel this future and return.
// At this point, inputFuture is cancelled and outputFuture doesn't
// exist, so the value of mayInterruptIfRunning is irrelevant.
cancel(false);
return;
} catch (ExecutionException e) {
// Set the cause of the exception as this future's exception
setException(e.getCause());
return;
}
final ListenableFuture<? extends O> outputFuture = this.outputFuture =
function.apply(sourceResult);
if (isCancelled()) {
// Handles the case where cancel was called while the function was
// being applied.
// There is a gap in cancel(boolean) between calling sync.cancel()
// and storing the value of mayInterruptIfRunning, so this thread
// needs to block, waiting for that value.
outputFuture.cancel(
takeUninterruptibly(mayInterruptIfRunningChannel));
this.outputFuture = null;
return;
}
outputFuture.addListener(new Runnable() {
@Override
public void run() {
try {
// Here it would have been nice to have had an
// UninterruptibleListenableFuture, but we don't want to start a
// combinatorial explosion of interfaces, so we have to make do.
set(getUninterruptibly(outputFuture));
} catch (CancellationException e) {
// Cancel this future and return.
// At this point, inputFuture and outputFuture are done, so the
// value of mayInterruptIfRunning is irrelevant.
cancel(false);
return;
} catch (ExecutionException e) {
// Set the cause of the exception as this future's exception
setException(e.getCause());
} finally {
// Don't pin inputs beyond completion
ChainingListenableFuture.this.outputFuture = null;
}
}
}, MoreExecutors.sameThreadExecutor());
} catch (UndeclaredThrowableException e) {
// Set the cause of the exception as this future's exception
setException(e.getCause());
} catch (Exception e) {
// This exception is irrelevant in this thread, but useful for the
// client
setException(e);
} catch (Error e) {
// Propagate errors up ASAP - our superclass will rethrow the error
setException(e);
} finally {
// Don't pin inputs beyond completion
function = null;
inputFuture = null;
// Allow our get routines to examine outputFuture now.
outputCreated.countDown();
}
}
}
/**
* Creates a new {@code ListenableFuture} whose value is a list containing the
* values of all its input futures, if all succeed. If any input fails, the
* returned future fails.
*
* <p>The list of results is in the same order as the input list.
*
* <p>Canceling this future does not cancel any of the component futures;
* however, if any of the provided futures fails or is canceled, this one is,
* too.
*
* @param futures futures to combine
* @return a future that provides a list of the results of the component
* futures
* @since 10.0
*/
@Beta
public static <V> ListenableFuture<List<V>> allAsList(
ListenableFuture<? extends V>... futures) {
return new ListFuture<V>(ImmutableList.copyOf(futures), true,
MoreExecutors.sameThreadExecutor());
}
/**
* Creates a new {@code ListenableFuture} whose value is a list containing the
* values of all its input futures, if all succeed. If any input fails, the
* returned future fails.
*
* <p>The list of results is in the same order as the input list.
*
* <p>Canceling this future does not cancel any of the component futures;
* however, if any of the provided futures fails or is canceled, this one is,
* too.
*
* @param futures futures to combine
* @return a future that provides a list of the results of the component
* futures
* @since 10.0
*/
@Beta
public static <V> ListenableFuture<List<V>> allAsList(
Iterable<? extends ListenableFuture<? extends V>> futures) {
return new ListFuture<V>(ImmutableList.copyOf(futures), true,
MoreExecutors.sameThreadExecutor());
}
/**
* Creates a new {@code ListenableFuture} whose value is a list containing the
* values of all its successful input futures. The list of results is in the
* same order as the input list, and if any of the provided futures fails or
* is canceled, its corresponding position will contain {@code null} (which is
* indistinguishable from the future having a successful value of
* {@code null}).
*
* @param futures futures to combine
* @return a future that provides a list of the results of the component
* futures
* @since 10.0
*/
@Beta
public static <V> ListenableFuture<List<V>> successfulAsList(
ListenableFuture<? extends V>... futures) {
return new ListFuture<V>(ImmutableList.copyOf(futures), false,
MoreExecutors.sameThreadExecutor());
}
/**
* Creates a new {@code ListenableFuture} whose value is a list containing the
* values of all its successful input futures. The list of results is in the
* same order as the input list, and if any of the provided futures fails or
* is canceled, its corresponding position will contain {@code null} (which is
* indistinguishable from the future having a successful value of
* {@code null}).
*
* @param futures futures to combine
* @return a future that provides a list of the results of the component
* futures
* @since 10.0
*/
@Beta
public static <V> ListenableFuture<List<V>> successfulAsList(
Iterable<? extends ListenableFuture<? extends V>> futures) {
return new ListFuture<V>(ImmutableList.copyOf(futures), false,
MoreExecutors.sameThreadExecutor());
}
/**
* Registers separate success and failure callbacks to be run when the {@code
* Future}'s computation is {@linkplain java.util.concurrent.Future#isDone()
* complete} or, if the computation is already complete, immediately.
*
* <p>There is no guaranteed ordering of execution of callbacks, but any
* callback added through this method is guaranteed to be called once the
* computation is complete.
*
* Example: <pre> {@code
* ListenableFuture<QueryResult> future = ...;
* addCallback(future,
* new FutureCallback<QueryResult> {
* public void onSuccess(QueryResult result) {
* storeInCache(result);
* }
* public void onFailure(Throwable t) {
* reportError(t);
* }
* });}</pre>
*
* <p>Note: This overload of {@code addCallback} is designed for cases in
* which the callack is fast and lightweight, as the method does not accept
* an {@code Executor} in which to perform the the work. For heavier
* callbacks, this overload carries some caveats: First, the thread that the
* callback runs in depends on whether the input {@code Future} is done at the
* time {@code addCallback} is called and on whether the input {@code Future}
* is ever cancelled. In particular, {@code addCallback} may execute the
* callback in the thread that calls {@code addCallback} or {@code
* Future.cancel}. Second, callbacks may run in an internal thread of the
* system responsible for the input {@code Future}, such as an RPC network
* thread. Finally, during the execution of a {@code sameThreadExecutor}
* callback, all other registered but unexecuted listeners are prevented from
* running, even if those listeners are to run in other executors.
*
* <p>For a more general interface to attach a completion listener to a
* {@code Future}, see {@link ListenableFuture#addListener addListener}.
*
* @param future The future attach the callback to.
* @param callback The callback to invoke when {@code future} is completed.
* @since 10.0
*/
public static <V> void addCallback(ListenableFuture<V> future,
FutureCallback<? super V> callback) {
addCallback(future, callback, MoreExecutors.sameThreadExecutor());
}
/**
* Registers separate success and failure callbacks to be run when the {@code
* Future}'s computation is {@linkplain java.util.concurrent.Future#isDone()
* complete} or, if the computation is already complete, immediately.
*
* <p>The callback is run in {@code executor}.
* There is no guaranteed ordering of execution of callbacks, but any
* callback added through this method is guaranteed to be called once the
* computation is complete.
*
* Example: <pre> {@code
* ListenableFuture<QueryResult> future = ...;
* Executor e = ...
* addCallback(future, e,
* new FutureCallback<QueryResult> {
* public void onSuccess(QueryResult result) {
* storeInCache(result);
* }
* public void onFailure(Throwable t) {
* reportError(t);
* }
* });}</pre>
*
* When the callback is fast and lightweight consider {@linkplain
* Futures#addCallback(ListenableFuture, FutureCallback) the other overload}
* or explicit use of {@link MoreExecutors#sameThreadExecutor
* sameThreadExecutor}. For heavier callbacks, this choice carries some
* caveats: First, the thread that the callback runs in depends on whether
* the input {@code Future} is done at the time {@code addCallback} is called
* and on whether the input {@code Future} is ever cancelled. In particular,
* {@code addCallback} may execute the callback in the thread that calls
* {@code addCallback} or {@code Future.cancel}. Second, callbacks may run in
* an internal thread of the system responsible for the input {@code Future},
* such as an RPC network thread. Finally, during the execution of a {@code
* sameThreadExecutor} callback, all other registered but unexecuted
* listeners are prevented from running, even if those listeners are to run
* in other executors.
*
* <p>For a more general interface to attach a completion listener to a
* {@code Future}, see {@link ListenableFuture#addListener addListener}.
*
* @param future The future attach the callback to.
* @param callback The callback to invoke when {@code future} is completed.
* @param executor The executor to run {@code callback} when the future
* completes.
* @since 10.0
*/
public static <V> void addCallback(final ListenableFuture<V> future,
final FutureCallback<? super V> callback, Executor executor) {
Preconditions.checkNotNull(callback);
Runnable callbackListener = new Runnable() {
@Override
public void run() {
try {
// TODO(user): (Before Guava release), validate that this
// is the thing for IE.
V value = getUninterruptibly(future);
callback.onSuccess(value);
} catch (ExecutionException e) {
callback.onFailure(e.getCause());
} catch (RuntimeException e) {
callback.onFailure(e);
} catch (Error e) {
callback.onFailure(e);
}
}
};
future.addListener(callbackListener, executor);
}
/**
* Returns the result of {@link Future#get()}, converting most exceptions to a
* new instance of the given checked exception type. This reduces boilerplate
* for a common use of {@code Future} in which it is unnecessary to
* programmatically distinguish between exception types or to extract other
* information from the exception instance.
*
* <p>Exceptions from {@code Future.get} are treated as follows:
* <ul>
* <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an
* {@code X} if the cause is a checked exception, an {@link
* UncheckedExecutionException} if the cause is a {@code
* RuntimeException}, or an {@link ExecutionError} if the cause is an
* {@code Error}.
* <li>Any {@link InterruptedException} is wrapped in an {@code X} (after
* restoring the interrupt).
* <li>Any {@link CancellationException} is propagated untouched, as is any
* other {@link RuntimeException} (though {@code get} implementations are
* discouraged from throwing such exceptions).
* </ul>
*
* The overall principle is to continue to treat every checked exception as a
* checked exception, every unchecked exception as an unchecked exception, and
* every error as an error. In addition, the cause of any {@code
* ExecutionException} is wrapped in order to ensure that the new stack trace
* matches that of the current thread.
*
* <p>Instances of {@code exceptionClass} are created by choosing an arbitrary
* public constructor that accepts zero or more arguments, all of type {@code
* String} or {@code Throwable} (preferring constructors with at least one
* {@code String}) and calling the constructor via reflection. If the
* exception did not already have a cause, one is set by calling {@link
* Throwable#initCause(Throwable)} on it. If no such constructor exists, an
* {@code IllegalArgumentException} is thrown.
*
* @throws X if {@code get} throws any checked exception except for an {@code
* ExecutionException} whose cause is not itself a checked exception
* @throws UncheckedExecutionException if {@code get} throws an {@code
* ExecutionException} with a {@code RuntimeException} as its cause
* @throws ExecutionError if {@code get} throws an {@code ExecutionException}
* with an {@code Error} as its cause
* @throws CancellationException if {@code get} throws a {@code
* CancellationException}
* @throws IllegalArgumentException if {@code exceptionClass} extends {@code
* RuntimeException} or does not have a suitable constructor
* @since 10.0
*/
@Beta
public static <V, X extends Exception> V get(
Future<V> future, Class<X> exceptionClass) throws X {
checkNotNull(future);
checkArgument(!RuntimeException.class.isAssignableFrom(exceptionClass),
"Futures.get exception type (%s) must not be a RuntimeException",
exceptionClass);
try {
return future.get();
} catch (InterruptedException e) {
currentThread().interrupt();
throw newWithCause(exceptionClass, e);
} catch (ExecutionException e) {
wrapAndThrowExceptionOrError(e.getCause(), exceptionClass);
throw new AssertionError();
}
}
/**
* Returns the result of {@link Future#get(long, TimeUnit)}, converting most
* exceptions to a new instance of the given checked exception type. This
* reduces boilerplate for a common use of {@code Future} in which it is
* unnecessary to programmatically distinguish between exception types or to
* extract other information from the exception instance.
*
* <p>Exceptions from {@code Future.get} are treated as follows:
* <ul>
* <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an
* {@code X} if the cause is a checked exception, an {@link
* UncheckedExecutionException} if the cause is a {@code
* RuntimeException}, or an {@link ExecutionError} if the cause is an
* {@code Error}.
* <li>Any {@link InterruptedException} is wrapped in an {@code X} (after
* restoring the interrupt).
* <li>Any {@link TimeoutException} is wrapped in an {@code X}.
* <li>Any {@link CancellationException} is propagated untouched, as is any
* other {@link RuntimeException} (though {@code get} implementations are
* discouraged from throwing such exceptions).
* </ul>
*
* The overall principle is to continue to treat every checked exception as a
* checked exception, every unchecked exception as an unchecked exception, and
* every error as an error. In addition, the cause of any {@code
* ExecutionException} is wrapped in order to ensure that the new stack trace
* matches that of the current thread.
*
* <p>Instances of {@code exceptionClass} are created by choosing an arbitrary
* public constructor that accepts zero or more arguments, all of type {@code
* String} or {@code Throwable} (preferring constructors with at least one
* {@code String}) and calling the constructor via reflection. If the
* exception did not already have a cause, one is set by calling {@link
* Throwable#initCause(Throwable)} on it. If no such constructor exists, an
* {@code IllegalArgumentException} is thrown.
*
* @throws X if {@code get} throws any checked exception except for an {@code
* ExecutionException} whose cause is not itself a checked exception
* @throws UncheckedExecutionException if {@code get} throws an {@code
* ExecutionException} with a {@code RuntimeException} as its cause
* @throws ExecutionError if {@code get} throws an {@code ExecutionException}
* with an {@code Error} as its cause
* @throws CancellationException if {@code get} throws a {@code
* CancellationException}
* @throws IllegalArgumentException if {@code exceptionClass} extends {@code
* RuntimeException} or does not have a suitable constructor
* @since 10.0
*/
@Beta
public static <V, X extends Exception> V get(
Future<V> future, long timeout, TimeUnit unit, Class<X> exceptionClass)
throws X {
checkNotNull(future);
checkNotNull(unit);
checkArgument(!RuntimeException.class.isAssignableFrom(exceptionClass),
"Futures.get exception type (%s) must not be a RuntimeException",
exceptionClass);
try {
return future.get(timeout, unit);
} catch (InterruptedException e) {
currentThread().interrupt();
throw newWithCause(exceptionClass, e);
} catch (TimeoutException e) {
throw newWithCause(exceptionClass, e);
} catch (ExecutionException e) {
wrapAndThrowExceptionOrError(e.getCause(), exceptionClass);
throw new AssertionError();
}
}
private static <X extends Exception> void wrapAndThrowExceptionOrError(
Throwable cause, Class<X> exceptionClass) throws X {
if (cause instanceof Error) {
throw new ExecutionError((Error) cause);
}
if (cause instanceof RuntimeException) {
throw new UncheckedExecutionException(cause);
}
throw newWithCause(exceptionClass, cause);
}
/**
* Returns the result of calling {@link Future#get()} uninterruptibly on a
* task known not to throw a checked exception. This makes {@code Future} more
* suitable for lightweight, fast-running tasks that, barring bugs in the
* code, will not fail. This gives it exception-handling behavior similar to
* that of {@code ForkJoinTask.join}.
*
* <p>Exceptions from {@code Future.get} are treated as follows:
* <ul>
* <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an
* {@link UncheckedExecutionException} (if the cause is an {@code
* Exception}) or {@link ExecutionError} (if the cause is an {@code
* Error}).
* <li>Any {@link InterruptedException} causes a retry of the {@code get}
* call. The interrupt is restored before {@code getUnchecked} returns.
* <li>Any {@link CancellationException} is propagated untouched. So is any
* other {@link RuntimeException} ({@code get} implementations are
* discouraged from throwing such exceptions).
* </ul>
*
* The overall principle is to eliminate all checked exceptions: to loop to
* avoid {@code InterruptedException}, to pass through {@code
* CancellationException}, and to wrap any exception from the underlying
* computation in an {@code UncheckedExecutionException} or {@code
* ExecutionError}.
*
* <p>For an uninterruptible {@code get} that preserves other exceptions, see
* {@link Uninterruptibles#getUninterruptibly(Future)}.
*
* @throws UncheckedExecutionException if {@code get} throws an {@code
* ExecutionException} with an {@code Exception} as its cause
* @throws ExecutionError if {@code get} throws an {@code ExecutionException}
* with an {@code Error} as its cause
* @throws CancellationException if {@code get} throws a {@code
* CancellationException}
* @since 10.0
*/
@Beta
public static <V> V getUnchecked(Future<V> future) {
checkNotNull(future);
try {
return getUninterruptibly(future);
} catch (ExecutionException e) {
wrapAndThrowUnchecked(e.getCause());
throw new AssertionError();
}
}
private static void wrapAndThrowUnchecked(Throwable cause) {
if (cause instanceof Error) {
throw new ExecutionError((Error) cause);
}
/*
* It's a non-Error, non-Exception Throwable. From my survey of such
* classes, I believe that most users intended to extend Exception, so we'll
* treat it like an Exception.
*/
throw new UncheckedExecutionException(cause);
}
/*
* TODO(user): FutureChecker interface for these to be static methods on? If
* so, refer to it in the (static-method) Futures.get documentation
*/
/*
* Arguably we don't need a timed getUnchecked because any operation slow
* enough to require a timeout is heavyweight enough to throw a checked
* exception and therefore be inappropriate to use with getUnchecked. Further,
* it's not clear that converting the checked TimeoutException to a
* RuntimeException -- especially to an UncheckedExecutionException, since it
* wasn't thrown by the computation -- makes sense, and if we don't convert
* it, the user still has to write a try-catch block.
*
* If you think you would use this method, let us know.
*/
private static <X extends Exception> X newWithCause(
Class<X> exceptionClass, Throwable cause) {
// getConstructors() guarantees this as long as we don't modify the array.
@SuppressWarnings("unchecked")
List<Constructor<X>> constructors =
(List) Arrays.asList(exceptionClass.getConstructors());
for (Constructor<X> constructor : preferringStrings(constructors)) {
@Nullable X instance = newFromConstructor(constructor, cause);
if (instance != null) {
if (instance.getCause() == null) {
instance.initCause(cause);
}
return instance;
}
}
throw new IllegalArgumentException(
"No appropriate constructor for exception of type " + exceptionClass
+ " in response to chained exception", cause);
}
private static <X extends Exception> List<Constructor<X>>
preferringStrings(List<Constructor<X>> constructors) {
return WITH_STRING_PARAM_FIRST.sortedCopy(constructors);
}
private static final Ordering<Constructor<?>> WITH_STRING_PARAM_FIRST =
Ordering.natural().onResultOf(new Function<Constructor<?>, Boolean>() {
@Override public Boolean apply(Constructor<?> input) {
return asList(input.getParameterTypes()).contains(String.class);
}
}).reverse();
@Nullable private static <X> X newFromConstructor(
Constructor<X> constructor, Throwable cause) {
Class<?>[] paramTypes = constructor.getParameterTypes();
Object[] params = new Object[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
Class<?> paramType = paramTypes[i];
if (paramType.equals(String.class)) {
params[i] = cause.toString();
} else if (paramType.equals(Throwable.class)) {
params[i] = cause;
} else {
return null;
}
}
try {
return constructor.newInstance(params);
} catch (IllegalArgumentException e) {
return null;
} catch (InstantiationException e) {
return null;
} catch (IllegalAccessException e) {
return null;
} catch (InvocationTargetException e) {
return null;
}
}
/**
* Class that implements {@link #allAsList} and {@link #successfulAsList}.
* The idea is to create a (null-filled) List and register a listener with
* each component future to fill out the value in the List when that future
* completes.
*/
private static class ListFuture<V> extends AbstractFuture<List<V>> {
ImmutableList<? extends ListenableFuture<? extends V>> futures;
final boolean allMustSucceed;
final AtomicInteger remaining;
List<V> values;
/**
* Constructor.
*
* @param futures all the futures to build the list from
* @param allMustSucceed whether a single failure or cancellation should
* propagate to this future
* @param listenerExecutor used to run listeners on all the passed in
* futures.
*/
ListFuture(
final ImmutableList<? extends ListenableFuture<? extends V>> futures,
final boolean allMustSucceed, final Executor listenerExecutor) {
this.futures = futures;
this.values = Lists.newArrayListWithCapacity(futures.size());
this.allMustSucceed = allMustSucceed;
this.remaining = new AtomicInteger(futures.size());
init(listenerExecutor);
}
private void init(final Executor listenerExecutor) {
// First, schedule cleanup to execute when the Future is done.
addListener(new Runnable() {
@Override
public void run() {
// By now the values array has either been set as the Future's value,
// or (in case of failure) is no longer useful.
ListFuture.this.values = null;
// Let go of the memory held by other futures
ListFuture.this.futures = null;
}
}, MoreExecutors.sameThreadExecutor());
// Now begin the "real" initialization.
// Corner case: List is empty.
if (futures.isEmpty()) {
set(Lists.newArrayList(values));
return;
}
// Populate the results list with null initially.
for (int i = 0; i < futures.size(); ++i) {
values.add(null);
}
// Register a listener on each Future in the list to update
// the state of this future.
// Note that if all the futures on the list are done prior to completing
// this loop, the last call to addListener() will callback to
// setOneValue(), transitively call our cleanup listener, and set
// this.futures to null.
// We store a reference to futures to avoid the NPE.
ImmutableList<? extends ListenableFuture<? extends V>> localFutures = futures;
for (int i = 0; i < localFutures.size(); i++) {
final ListenableFuture<? extends V> listenable = localFutures.get(i);
final int index = i;
listenable.addListener(new Runnable() {
@Override
public void run() {
setOneValue(index, listenable);
}
}, listenerExecutor);
}
}
/**
* Sets the value at the given index to that of the given future.
*/
private void setOneValue(int index, Future<? extends V> future) {
List<V> localValues = values;
if (isDone() || localValues == null) {
// Some other future failed or has been cancelled, causing this one to
// also be cancelled or have an exception set. This should only happen
// if allMustSucceed is true.
checkState(allMustSucceed,
"Future was done before all dependencies completed");
return;
}
try {
checkState(future.isDone(),
"Tried to set value from future which is not done");
localValues.set(index, getUninterruptibly(future));
} catch (CancellationException e) {
if (allMustSucceed) {
// Set ourselves as cancelled. Let the input futures keep running
// as some of them may be used elsewhere.
// (Currently we don't override interruptTask, so
// mayInterruptIfRunning==false isn't technically necessary.)
cancel(false);
}
} catch (ExecutionException e) {
if (allMustSucceed) {
// As soon as the first one fails, throw the exception up.
// The result of all other inputs is then ignored.
setException(e.getCause());
}
} catch (RuntimeException e) {
if (allMustSucceed) {
setException(e);
}
} catch (Error e) {
// Propagate errors up ASAP - our superclass will rethrow the error
setException(e);
} finally {
int newRemaining = remaining.decrementAndGet();
checkState(newRemaining >= 0, "Less than 0 remaining futures");
if (newRemaining == 0) {
localValues = values;
if (localValues != null) {
set(Lists.newArrayList(localValues));
} else {
checkState(isDone());
}
}
}
}
}
/**
* A checked future that uses a function to map from exceptions to the
* appropriate checked type.
*/
private static class MappingCheckedFuture<V, X extends Exception> extends
AbstractCheckedFuture<V, X> {
final Function<Exception, X> mapper;
MappingCheckedFuture(ListenableFuture<V> delegate,
Function<Exception, X> mapper) {
super(delegate);
this.mapper = checkNotNull(mapper);
}
@Override
protected X mapException(Exception e) {
return mapper.apply(e);
}
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* A {@code CheckedFuture} is a {@link ListenableFuture} that includes versions
* of the {@code get} methods that can throw a checked exception. This makes it
* easier to create a future that executes logic which can throw an exception.
*
* <p>A common implementation is {@link Futures#immediateCheckedFuture}.
*
* <p>Implementations of this interface must adapt the exceptions thrown by
* {@code Future#get()}: {@link CancellationException},
* {@link ExecutionException} and {@link InterruptedException} into the type
* specified by the {@code E} type parameter.
*
* <p>This interface also extends the ListenableFuture interface to allow
* listeners to be added. This allows the future to be used as a normal
* {@link Future} or as an asynchronous callback mechanism as needed. This
* allows multiple callbacks to be registered for a particular task, and the
* future will guarantee execution of all listeners when the task completes.
*
* <p>For a simpler alternative to CheckedFuture, consider accessing Future
* values with {@link Futures#get(Future, Class) Futures.get()}.
*
* @author Sven Mawson
* @since 1.0
*/
@Beta
public interface CheckedFuture<V, X extends Exception>
extends ListenableFuture<V> {
/**
* Exception checking version of {@link Future#get()} that will translate
* {@link InterruptedException}, {@link CancellationException} and
* {@link ExecutionException} into application-specific exceptions.
*
* @return the result of executing the future.
* @throws X on interruption, cancellation or execution exceptions.
*/
V checkedGet() throws X;
/**
* Exception checking version of {@link Future#get(long, TimeUnit)} that will
* translate {@link InterruptedException}, {@link CancellationException} and
* {@link ExecutionException} into application-specific exceptions. On
* timeout this method throws a normal {@link TimeoutException}.
*
* @return the result of executing the future.
* @throws TimeoutException if retrieving the result timed out.
* @throws X on interruption, cancellation or execution exceptions.
*/
V checkedGet(long timeout, TimeUnit unit) throws TimeoutException, X;
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* 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.google.common.util.concurrent;
import static java.util.logging.Level.SEVERE;
import com.google.common.annotations.VisibleForTesting;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.logging.Logger;
/**
* Factories for {@link UncaughtExceptionHandler} instances.
*
* @author Gregory Kick
* @since 8.0
*/
public final class UncaughtExceptionHandlers {
private UncaughtExceptionHandlers() {}
/**
* Returns an exception handler that exits the system. This is particularly useful for the main
* thread, which may start up other, non-daemon threads, but fail to fully initialize the
* application successfully.
*
* <p>Example usage:
* <pre>public static void main(String[] args) {
* Thread.currentThread().setUncaughtExceptionHandler(UncaughtExceptionHandlers.systemExit());
* ...
* </pre>
*/
public static UncaughtExceptionHandler systemExit() {
return new Exiter(Runtime.getRuntime());
}
@VisibleForTesting static final class Exiter implements UncaughtExceptionHandler {
private static final Logger logger = Logger.getLogger(Exiter.class.getName());
private final Runtime runtime;
Exiter(Runtime runtime) {
this.runtime = runtime;
}
@Override public void uncaughtException(Thread t, Throwable e) {
// cannot use FormattingLogger due to a dependency loop
logger.log(SEVERE, String.format("Caught an exception in %s. Shutting down.", t), e);
runtime.exit(1);
}
}
}
| Java |
/*
* Copyright (C) 2006 The Guava Authors
*
* 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.google.common.util.concurrent;
/**
* Unchecked version of {@link java.util.concurrent.TimeoutException}.
*
* @author Kevin Bourrillion
* @since 1.0
*/
public class UncheckedTimeoutException extends RuntimeException {
public UncheckedTimeoutException() {}
public UncheckedTimeoutException(String message) {
super(message);
}
public UncheckedTimeoutException(Throwable cause) {
super(cause);
}
public UncheckedTimeoutException(String message, Throwable cause) {
super(message, cause);
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.util.concurrent;
import java.util.concurrent.Callable;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to the {@link Callable} interface.
*
* @author Isaac Shum
* @since 1.0
*/
public final class Callables {
private Callables() {}
/**
* Creates a {@code Callable} which immediately returns a preset value each
* time it is called.
*/
public static <T> Callable<T> returning(final @Nullable T value) {
return new Callable<T>() {
@Override public T call() {
return value;
}
};
}
}
| Java |
// Copyright 2011 Google Inc. All Rights Reserved.
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
/**
* A map containing {@code long} values that can be atomically updated. While writes to a
* traditional {@code Map} rely on {@code put(K, V)}, the typical mechanism for writing to this map
* is {@code addAndGet(K, long)}, which adds a {@code long} to the value currently associated with
* {@code K}. If a key has not yet been associated with a value, its implicit value is zero.
*
* <p>Most methods in this class treat absent values and zero values identically, as individually
* documented. Exceptions to this are {@link #containsKey}, {@link #size}, {@link #isEmpty},
* {@link #asMap}, and {@link #toString}.
*
* <p>Instances of this class may be used by multiple threads concurrently. All operations are
* atomic unless otherwise noted.
*
* <p><b>Note:</b> If your values are always positive and less than 2^31, you may wish to use a
* {@link com.google.common.collect.Multiset} such as
* {@link com.google.common.collect.ConcurrentHashMultiset} instead.
*
* <b>Warning:</b> Unlike {@code Multiset}, entries whose values are zero are not automatically
* removed from the map. Instead they must be removed manually with {@link #removeAllZeros}.
*
* @author Charles Fry
* @since 11.0
*/
@Beta
public final class AtomicLongMap<K> {
private final ConcurrentHashMap<K, AtomicLong> map;
private AtomicLongMap(ConcurrentHashMap<K, AtomicLong> map) {
this.map = checkNotNull(map);
}
/**
* Creates an {@code AtomicLongMap}.
*/
public static <K> AtomicLongMap<K> create() {
return new AtomicLongMap<K>(new ConcurrentHashMap<K, AtomicLong>());
}
/**
* Creates an {@code AtomicLongMap} with the same mappings as the specified {@code Map}.
*/
public static <K> AtomicLongMap<K> create(Map<? extends K, ? extends Long> m) {
AtomicLongMap<K> result = create();
result.putAll(m);
return result;
}
/**
* Returns the value associated with {@code key}, or zero if there is no value associated with
* {@code key}.
*/
public long get(K key) {
AtomicLong atomic = map.get(key);
return atomic == null ? 0L : atomic.get();
}
/**
* Increments by one the value currently associated with {@code key}, and returns the new value.
*/
public long incrementAndGet(K key) {
return addAndGet(key, 1);
}
/**
* Decrements by one the value currently associated with {@code key}, and returns the new value.
*/
public long decrementAndGet(K key) {
return addAndGet(key, -1);
}
/**
* Adds {@code delta} to the value currently associated with {@code key}, and returns the new
* value.
*/
public long addAndGet(K key, long delta) {
outer: for (;;) {
AtomicLong atomic = map.get(key);
if (atomic == null) {
atomic = map.putIfAbsent(key, new AtomicLong(delta));
if (atomic == null) {
return delta;
}
// atomic is now non-null; fall through
}
for (;;) {
long oldValue = atomic.get();
if (oldValue == 0L) {
// don't compareAndSet a zero
if (map.replace(key, atomic, new AtomicLong(delta))) {
return delta;
}
// atomic replaced
continue outer;
}
long newValue = oldValue + delta;
if (atomic.compareAndSet(oldValue, newValue)) {
return newValue;
}
// value changed
}
}
}
/**
* Increments by one the value currently associated with {@code key}, and returns the old value.
*/
public long getAndIncrement(K key) {
return getAndAdd(key, 1);
}
/**
* Decrements by one the value currently associated with {@code key}, and returns the old value.
*/
public long getAndDecrement(K key) {
return getAndAdd(key, -1);
}
/**
* Adds {@code delta} to the value currently associated with {@code key}, and returns the old
* value.
*/
public long getAndAdd(K key, long delta) {
outer: for (;;) {
AtomicLong atomic = map.get(key);
if (atomic == null) {
atomic = map.putIfAbsent(key, new AtomicLong(delta));
if (atomic == null) {
return 0L;
}
// atomic is now non-null; fall through
}
for (;;) {
long oldValue = atomic.get();
if (oldValue == 0L) {
// don't compareAndSet a zero
if (map.replace(key, atomic, new AtomicLong(delta))) {
return 0L;
}
// atomic replaced
continue outer;
}
long newValue = oldValue + delta;
if (atomic.compareAndSet(oldValue, newValue)) {
return oldValue;
}
// value changed
}
}
}
/**
* Associates {@code newValue} with {@code key} in this map, and returns the value previously
* associated with {@code key}, or zero if there was no such value.
*/
public long put(K key, long newValue) {
outer: for (;;) {
AtomicLong atomic = map.get(key);
if (atomic == null) {
atomic = map.putIfAbsent(key, new AtomicLong(newValue));
if (atomic == null) {
return 0L;
}
// atomic is now non-null; fall through
}
for (;;) {
long oldValue = atomic.get();
if (oldValue == 0L) {
// don't compareAndSet a zero
if (map.replace(key, atomic, new AtomicLong(newValue))) {
return 0L;
}
// atomic replaced
continue outer;
}
if (atomic.compareAndSet(oldValue, newValue)) {
return oldValue;
}
// value changed
}
}
}
/**
* Copies all of the mappings from the specified map to this map. The effect of this call is
* equivalent to that of calling {@code put(k, v)} on this map once for each mapping from key
* {@code k} to value {@code v} in the specified map. The behavior of this operation is undefined
* if the specified map is modified while the operation is in progress.
*/
public void putAll(Map<? extends K, ? extends Long> m) {
for (Map.Entry<? extends K, ? extends Long> entry : m.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
/**
* Removes and returns the value associated with {@code key}. If {@code key} is not
* in the map, this method has no effect and returns zero.
*/
public long remove(K key) {
AtomicLong atomic = map.get(key);
if (atomic == null) {
return 0L;
}
for (;;) {
long oldValue = atomic.get();
if (oldValue == 0L || atomic.compareAndSet(oldValue, 0L)) {
// only remove after setting to zero, to avoid concurrent updates
map.remove(key, atomic);
// succeed even if the remove fails, since the value was already adjusted
return oldValue;
}
}
}
/**
* Removes all mappings from this map whose values are zero.
*
* <p>This method is not atomic: the map may be visible in intermediate states, where some
* of the zero values have been removed and others have not.
*/
public void removeAllZeros() {
for (K key : map.keySet()) {
AtomicLong atomic = map.get(key);
if (atomic != null && atomic.get() == 0L) {
map.remove(key, atomic);
}
}
}
/**
* Returns the sum of all values in this map.
*
* <p>This method is not atomic: the sum may or may not include other concurrent operations.
*/
public long sum() {
long sum = 0L;
for (AtomicLong value : map.values()) {
sum = sum + value.get();
}
return sum;
}
private transient Map<K, Long> asMap;
/**
* Returns a live, read-only view of the map backing this {@code AtomicLongMap}.
*/
public Map<K, Long> asMap() {
Map<K, Long> result = asMap;
return (result == null) ? asMap = createAsMap() : result;
}
private Map<K, Long> createAsMap() {
return Collections.unmodifiableMap(
Maps.transformValues(map, new Function<AtomicLong, Long>() {
@Override
public Long apply(AtomicLong atomic) {
return atomic.get();
}
}));
}
/**
* Returns true if this map contains a mapping for the specified key.
*/
public boolean containsKey(Object key) {
return map.containsKey(key);
}
/**
* Returns the number of key-value mappings in this map. If the map contains more than
* {@code Integer.MAX_VALUE} elements, returns {@code Integer.MAX_VALUE}.
*/
public int size() {
return map.size();
}
/**
* Returns {@code true} if this map contains no key-value mappings.
*/
public boolean isEmpty() {
return map.isEmpty();
}
/**
* Removes all of the mappings from this map. The map will be empty after this call returns.
*
* <p>This method is not atomic: the map may not be empty after returning if there were concurrent
* writes.
*/
public void clear() {
map.clear();
}
@Override
public String toString() {
return map.toString();
}
/*
* ConcurrentMap operations which we may eventually add.
*
* The problem with these is that remove(K, long) has to be done in two phases by definition ---
* first decrementing to zero, and then removing. putIfAbsent or replace could observe the
* intermediate zero-state. Ways we could deal with this are:
*
* - Don't define any of the ConcurrentMap operations. This is the current state of affairs.
*
* - Define putIfAbsent and replace as treating zero and absent identically (as currently
* implemented below). This is a bit surprising with putIfAbsent, which really becomes
* putIfZero.
*
* - Allow putIfAbsent and replace to distinguish between zero and absent, but don't implement
* remove(K, long). Without any two-phase operations it becomes feasible for all remaining
* operations to distinguish between zero and absent. If we do this, then perhaps we should add
* replace(key, long).
*
* - Introduce a special-value private static final AtomicLong that would have the meaning of
* removal-in-progress, and rework all operations to properly distinguish between zero and
* absent.
*/
/**
* If {@code key} is not already associated with a value or if {@code key} is associated with
* zero, associate it with {@code newValue}. Returns the previous value associated with
* {@code key}, or zero if there was no mapping for {@code key}.
*/
long putIfAbsent(K key, long newValue) {
for (;;) {
AtomicLong atomic = map.get(key);
if (atomic == null) {
atomic = map.putIfAbsent(key, new AtomicLong(newValue));
if (atomic == null) {
return 0L;
}
// atomic is now non-null; fall through
}
long oldValue = atomic.get();
if (oldValue == 0L) {
// don't compareAndSet a zero
if (map.replace(key, atomic, new AtomicLong(newValue))) {
return 0L;
}
// atomic replaced
continue;
}
return oldValue;
}
}
/**
* If {@code (key, expectedOldValue)} is currently in the map, this method replaces
* {@code expectedOldValue} with {@code newValue} and returns true; otherwise, this method
* returns false.
*
* <p>If {@code expectedOldValue} is zero, this method will succeed if {@code (key, zero)}
* is currently in the map, or if {@code key} is not in the map at all.
*/
boolean replace(K key, long expectedOldValue, long newValue) {
if (expectedOldValue == 0L) {
return putIfAbsent(key, newValue) == 0L;
} else {
AtomicLong atomic = map.get(key);
return (atomic == null) ? false : atomic.compareAndSet(expectedOldValue, newValue);
}
}
/**
* If {@code (key, value)} is currently in the map, this method removes it and returns
* true; otherwise, this method returns false.
*/
boolean remove(K key, long value) {
AtomicLong atomic = map.get(key);
if (atomic == null) {
return false;
}
long oldValue = atomic.get();
if (oldValue != value) {
return false;
}
if (oldValue == 0L || atomic.compareAndSet(oldValue, 0L)) {
// only remove after setting to zero, to avoid concurrent updates
map.remove(key, atomic);
// succeed even if the remove fails, since the value was already adjusted
return true;
}
// value changed
return false;
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* 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.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/**
* A synchronization abstraction supporting waiting on arbitrary boolean conditions.
*
* <p>This class is intended as a replacement for {@link ReentrantLock}. Code using {@code Monitor}
* is less error-prone and more readable than code using {@code ReentrantLock}, without significant
* performance loss. {@code Monitor} even has the potential for performance gain by optimizing the
* evaluation and signaling of conditions. Signaling is entirely
* <a href="http://en.wikipedia.org/wiki/Monitor_(synchronization)#Implicit_signaling">
* implicit</a>.
* By eliminating explicit signaling, this class can guarantee that only one thread is awakened
* when a condition becomes true (no "signaling storms" due to use of {@link
* java.util.concurrent.locks.Condition#signalAll Condition.signalAll}) and that no signals are lost
* (no "hangs" due to incorrect use of {@link java.util.concurrent.locks.Condition#signal
* Condition.signal}).
*
* <p>A thread is said to <i>occupy</i> a monitor if it has <i>entered</i> the monitor but not yet
* <i>left</i>. Only one thread may occupy a given monitor at any moment. A monitor is also
* reentrant, so a thread may enter a monitor any number of times, and then must leave the same
* number of times. The <i>enter</i> and <i>leave</i> operations have the same synchronization
* semantics as the built-in Java language synchronization primitives.
*
* <p>A call to any of the <i>enter</i> methods with <b>void</b> return type should always be
* followed immediately by a <i>try/finally</i> block to ensure that the current thread leaves the
* monitor cleanly: <pre> {@code
*
* monitor.enter();
* try {
* // do things while occupying the monitor
* } finally {
* monitor.leave();
* }}</pre>
*
* A call to any of the <i>enter</i> methods with <b>boolean</b> return type should always appear as
* the condition of an <i>if</i> statement containing a <i>try/finally</i> block to ensure that the
* current thread leaves the monitor cleanly: <pre> {@code
*
* if (monitor.tryEnter()) {
* try {
* // do things while occupying the monitor
* } finally {
* monitor.leave();
* }
* } else {
* // do other things since the monitor was not available
* }}</pre>
*
* <h2>Comparison with {@code synchronized} and {@code ReentrantLock}</h2>
*
* <p>The following examples show a simple threadsafe holder expressed using {@code synchronized},
* {@link ReentrantLock}, and {@code Monitor}.
*
* <h3>{@code synchronized}</h3>
*
* <p>This version is the fewest lines of code, largely because the synchronization mechanism used
* is built into the language and runtime. But the programmer has to remember to avoid a couple of
* common bugs: The {@code wait()} must be inside a {@code while} instead of an {@code if}, and
* {@code notifyAll()} must be used instead of {@code notify()} because there are two different
* logical conditions being awaited. <pre> {@code
*
* public class SafeBox<V> {
* private V value;
*
* public synchronized V get() throws InterruptedException {
* while (value == null) {
* wait();
* }
* V result = value;
* value = null;
* notifyAll();
* return result;
* }
*
* public synchronized void set(V newValue) throws InterruptedException {
* while (value != null) {
* wait();
* }
* value = newValue;
* notifyAll();
* }
* }}</pre>
*
* <h3>{@code ReentrantLock}</h3>
*
* <p>This version is much more verbose than the {@code synchronized} version, and still suffers
* from the need for the programmer to remember to use {@code while} instead of {@code if}.
* However, one advantage is that we can introduce two separate {@code Condition} objects, which
* allows us to use {@code signal()} instead of {@code signalAll()}, which may be a performance
* benefit. <pre> {@code
*
* public class SafeBox<V> {
* private final ReentrantLock lock = new ReentrantLock();
* private final Condition valuePresent = lock.newCondition();
* private final Condition valueAbsent = lock.newCondition();
* private V value;
*
* public V get() throws InterruptedException {
* lock.lock();
* try {
* while (value == null) {
* valuePresent.await();
* }
* V result = value;
* value = null;
* valueAbsent.signal();
* return result;
* } finally {
* lock.unlock();
* }
* }
*
* public void set(V newValue) throws InterruptedException {
* lock.lock();
* try {
* while (value != null) {
* valueAbsent.await();
* }
* value = newValue;
* valuePresent.signal();
* } finally {
* lock.unlock();
* }
* }
* }}</pre>
*
* <h3>{@code Monitor}</h3>
*
* <p>This version adds some verbosity around the {@code Guard} objects, but removes that same
* verbosity, and more, from the {@code get} and {@code set} methods. {@code Monitor} implements the
* same efficient signaling as we had to hand-code in the {@code ReentrantLock} version above.
* Finally, the programmer no longer has to hand-code the wait loop, and therefore doesn't have to
* remember to use {@code while} instead of {@code if}. <pre> {@code
*
* public class SafeBox<V> {
* private final Monitor monitor = new Monitor();
* private final Monitor.Guard valuePresent = new Monitor.Guard(monitor) {
* public boolean isSatisfied() {
* return value != null;
* }
* };
* private final Monitor.Guard valueAbsent = new Monitor.Guard(monitor) {
* public boolean isSatisfied() {
* return value == null;
* }
* };
* private V value;
*
* public V get() throws InterruptedException {
* monitor.enterWhen(valuePresent);
* try {
* V result = value;
* value = null;
* return result;
* } finally {
* monitor.leave();
* }
* }
*
* public void set(V newValue) throws InterruptedException {
* monitor.enterWhen(valueAbsent);
* try {
* value = newValue;
* } finally {
* monitor.leave();
* }
* }
* }}</pre>
*
* @author Justin T. Sampson
* @since 10.0
*/
@Beta
public final class Monitor {
// TODO: Use raw LockSupport or AbstractQueuedSynchronizer instead of ReentrantLock.
/**
* A boolean condition for which a thread may wait. A {@code Guard} is associated with a single
* {@code Monitor}. The monitor may check the guard at arbitrary times from any thread occupying
* the monitor, so code should not be written to rely on how often a guard might or might not be
* checked.
*
* <p>If a {@code Guard} is passed into any method of a {@code Monitor} other than the one it is
* associated with, an {@link IllegalMonitorStateException} is thrown.
*
* @since 10.0
*/
@Beta
public abstract static class Guard {
final Monitor monitor;
final Condition condition;
@GuardedBy("monitor.lock")
int waiterCount = 0;
protected Guard(Monitor monitor) {
this.monitor = checkNotNull(monitor, "monitor");
this.condition = monitor.lock.newCondition();
}
/**
* Evaluates this guard's boolean condition. This method is always called with the associated
* monitor already occupied. Implementations of this method must depend only on state protected
* by the associated monitor, and must not modify that state.
*/
public abstract boolean isSatisfied();
@Override
public final boolean equals(Object other) {
// Overridden as final to ensure identity semantics in Monitor.activeGuards.
return this == other;
}
@Override
public final int hashCode() {
// Overridden as final to ensure identity semantics in Monitor.activeGuards.
return super.hashCode();
}
}
/**
* Whether this monitor is fair.
*/
private final boolean fair;
/**
* The lock underlying this monitor.
*/
private final ReentrantLock lock;
/**
* The guards associated with this monitor that currently have waiters ({@code waiterCount > 0}).
* This is an ArrayList rather than, say, a HashSet so that iteration and almost all adds don't
* incur any object allocation overhead.
*/
@GuardedBy("lock")
private final ArrayList<Guard> activeGuards = Lists.newArrayListWithCapacity(1);
/**
* Creates a monitor with a non-fair (but fast) ordering policy. Equivalent to {@code
* Monitor(false)}.
*/
public Monitor() {
this(false);
}
/**
* Creates a monitor with the given ordering policy.
*
* @param fair whether this monitor should use a fair ordering policy rather than a non-fair (but
* fast) one
*/
public Monitor(boolean fair) {
this.fair = fair;
this.lock = new ReentrantLock(fair);
}
/**
* Enters this monitor. Blocks indefinitely.
*/
public void enter() {
lock.lock();
}
/**
* Enters this monitor. Blocks indefinitely, but may be interrupted.
*/
public void enterInterruptibly() throws InterruptedException {
lock.lockInterruptibly();
}
/**
* Enters this monitor. Blocks at most the given time.
*
* @return whether the monitor was entered
*/
public boolean enter(long time, TimeUnit unit) {
final ReentrantLock lock = this.lock;
if (!fair && lock.tryLock()) {
return true;
}
long startNanos = System.nanoTime();
long timeoutNanos = unit.toNanos(time);
long remainingNanos = timeoutNanos;
boolean interruptIgnored = false;
try {
while (true) {
try {
return lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS);
} catch (InterruptedException ignored) {
interruptIgnored = true;
remainingNanos = (timeoutNanos - (System.nanoTime() - startNanos));
}
}
} finally {
if (interruptIgnored) {
Thread.currentThread().interrupt();
}
}
}
/**
* Enters this monitor. Blocks at most the given time, and may be interrupted.
*
* @return whether the monitor was entered
*/
public boolean enterInterruptibly(long time, TimeUnit unit) throws InterruptedException {
return lock.tryLock(time, unit);
}
/**
* Enters this monitor if it is possible to do so immediately. Does not block.
*
* <p><b>Note:</b> This method disregards the fairness setting of this monitor.
*
* @return whether the monitor was entered
*/
public boolean tryEnter() {
return lock.tryLock();
}
/**
* Enters this monitor when the guard is satisfied. Blocks indefinitely, but may be interrupted.
*/
public void enterWhen(Guard guard) throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
boolean reentrant = lock.isHeldByCurrentThread();
boolean success = false;
lock.lockInterruptibly();
try {
waitInterruptibly(guard, reentrant);
success = true;
} finally {
if (!success) {
lock.unlock();
}
}
}
/**
* Enters this monitor when the guard is satisfied. Blocks indefinitely.
*/
public void enterWhenUninterruptibly(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
boolean reentrant = lock.isHeldByCurrentThread();
boolean success = false;
lock.lock();
try {
waitUninterruptibly(guard, reentrant);
success = true;
} finally {
if (!success) {
lock.unlock();
}
}
}
/**
* Enters this monitor when the guard is satisfied. Blocks at most the given time, including both
* the time to acquire the lock and the time to wait for the guard to be satisfied, and may be
* interrupted.
*
* @return whether the monitor was entered
*/
public boolean enterWhen(Guard guard, long time, TimeUnit unit) throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
boolean reentrant = lock.isHeldByCurrentThread();
long remainingNanos;
if (!fair && lock.tryLock()) {
remainingNanos = unit.toNanos(time);
} else {
long startNanos = System.nanoTime();
if (!lock.tryLock(time, unit)) {
return false;
}
remainingNanos = unit.toNanos(time) - (System.nanoTime() - startNanos);
}
boolean satisfied = false;
try {
satisfied = waitInterruptibly(guard, remainingNanos, reentrant);
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Enters this monitor when the guard is satisfied. Blocks at most the given time, including
* both the time to acquire the lock and the time to wait for the guard to be satisfied.
*
* @return whether the monitor was entered
*/
public boolean enterWhenUninterruptibly(Guard guard, long time, TimeUnit unit) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
boolean reentrant = lock.isHeldByCurrentThread();
boolean interruptIgnored = false;
try {
long remainingNanos;
if (!fair && lock.tryLock()) {
remainingNanos = unit.toNanos(time);
} else {
long startNanos = System.nanoTime();
long timeoutNanos = unit.toNanos(time);
remainingNanos = timeoutNanos;
while (true) {
try {
if (lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS)) {
break;
} else {
return false;
}
} catch (InterruptedException ignored) {
interruptIgnored = true;
} finally {
remainingNanos = (timeoutNanos - (System.nanoTime() - startNanos));
}
}
}
boolean satisfied = false;
try {
satisfied = waitUninterruptibly(guard, remainingNanos, reentrant);
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
} finally {
if (interruptIgnored) {
Thread.currentThread().interrupt();
}
}
}
/**
* Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but
* does not wait for the guard to be satisfied.
*
* @return whether the monitor was entered
*/
public boolean enterIf(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
lock.lock();
boolean satisfied = false;
try {
satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but does
* not wait for the guard to be satisfied, and may be interrupted.
*
* @return whether the monitor was entered
*/
public boolean enterIfInterruptibly(Guard guard) throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
boolean satisfied = false;
try {
satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the
* lock, but does not wait for the guard to be satisfied.
*
* @return whether the monitor was entered
*/
public boolean enterIf(Guard guard, long time, TimeUnit unit) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
if (!enter(time, unit)) {
return false;
}
boolean satisfied = false;
try {
satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the
* lock, but does not wait for the guard to be satisfied, and may be interrupted.
*
* @return whether the monitor was entered
*/
public boolean enterIfInterruptibly(Guard guard, long time, TimeUnit unit)
throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
if (!lock.tryLock(time, unit)) {
return false;
}
boolean satisfied = false;
try {
satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Enters this monitor if it is possible to do so immediately and the guard is satisfied. Does not
* block acquiring the lock and does not wait for the guard to be satisfied.
*
* <p><b>Note:</b> This method disregards the fairness setting of this monitor.
*
* @return whether the monitor was entered
*/
public boolean tryEnterIf(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
final ReentrantLock lock = this.lock;
if (!lock.tryLock()) {
return false;
}
boolean satisfied = false;
try {
satisfied = guard.isSatisfied();
} finally {
if (!satisfied) {
lock.unlock();
}
}
return satisfied;
}
/**
* Waits for the guard to be satisfied. Waits indefinitely, but may be interrupted. May be
* called only by a thread currently occupying this monitor.
*/
public void waitFor(Guard guard) throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
if (!lock.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
}
waitInterruptibly(guard, true);
}
/**
* Waits for the guard to be satisfied. Waits indefinitely. May be called only by a thread
* currently occupying this monitor.
*/
public void waitForUninterruptibly(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
if (!lock.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
}
waitUninterruptibly(guard, true);
}
/**
* Waits for the guard to be satisfied. Waits at most the given time, and may be interrupted.
* May be called only by a thread currently occupying this monitor.
*
* @return whether the guard is now satisfied
*/
public boolean waitFor(Guard guard, long time, TimeUnit unit) throws InterruptedException {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
if (!lock.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
}
return waitInterruptibly(guard, unit.toNanos(time), true);
}
/**
* Waits for the guard to be satisfied. Waits at most the given time. May be called only by a
* thread currently occupying this monitor.
*
* @return whether the guard is now satisfied
*/
public boolean waitForUninterruptibly(Guard guard, long time, TimeUnit unit) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
if (!lock.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
}
return waitUninterruptibly(guard, unit.toNanos(time), true);
}
/**
* Leaves this monitor. May be called only by a thread currently occupying this monitor.
*/
public void leave() {
final ReentrantLock lock = this.lock;
if (!lock.isHeldByCurrentThread()) {
throw new IllegalMonitorStateException();
}
try {
signalConditionsOfSatisfiedGuards(null);
} finally {
lock.unlock();
}
}
/**
* Returns whether this monitor is using a fair ordering policy.
*/
public boolean isFair() {
return lock.isFair();
}
/**
* Returns whether this monitor is occupied by any thread. This method is designed for use in
* monitoring of the system state, not for synchronization control.
*/
public boolean isOccupied() {
return lock.isLocked();
}
/**
* Returns whether the current thread is occupying this monitor (has entered more times than it
* has left).
*/
public boolean isOccupiedByCurrentThread() {
return lock.isHeldByCurrentThread();
}
/**
* Returns the number of times the current thread has entered this monitor in excess of the number
* of times it has left. Returns 0 if the current thread is not occupying this monitor.
*/
public int getOccupiedDepth() {
return lock.getHoldCount();
}
/**
* Returns an estimate of the number of threads waiting to enter this monitor. The value is only
* an estimate because the number of threads may change dynamically while this method traverses
* internal data structures. This method is designed for use in monitoring of the system state,
* not for synchronization control.
*/
public int getQueueLength() {
return lock.getQueueLength();
}
/**
* Returns whether any threads are waiting to enter this monitor. Note that because cancellations
* may occur at any time, a {@code true} return does not guarantee that any other thread will ever
* enter this monitor. This method is designed primarily for use in monitoring of the system
* state.
*/
public boolean hasQueuedThreads() {
return lock.hasQueuedThreads();
}
/**
* Queries whether the given thread is waiting to enter this monitor. Note that because
* cancellations may occur at any time, a {@code true} return does not guarantee that this thread
* will ever enter this monitor. This method is designed primarily for use in monitoring of the
* system state.
*/
public boolean hasQueuedThread(Thread thread) {
return lock.hasQueuedThread(thread);
}
/**
* Queries whether any threads are waiting for the given guard to become satisfied. Note that
* because timeouts and interrupts may occur at any time, a {@code true} return does not guarantee
* that the guard becoming satisfied in the future will awaken any threads. This method is
* designed primarily for use in monitoring of the system state.
*/
public boolean hasWaiters(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
lock.lock();
try {
return guard.waiterCount > 0;
} finally {
lock.unlock();
}
}
/**
* Returns an estimate of the number of threads waiting for the given guard to become satisfied.
* Note that because timeouts and interrupts may occur at any time, the estimate serves only as an
* upper bound on the actual number of waiters. This method is designed for use in monitoring of
* the system state, not for synchronization control.
*/
public int getWaitQueueLength(Guard guard) {
if (guard.monitor != this) {
throw new IllegalMonitorStateException();
}
lock.lock();
try {
return guard.waiterCount;
} finally {
lock.unlock();
}
}
@GuardedBy("lock")
private void signalConditionsOfSatisfiedGuards(@Nullable Guard interruptedGuard) {
final ArrayList<Guard> guards = this.activeGuards;
final int guardCount = guards.size();
try {
for (int i = 0; i < guardCount; i++) {
Guard guard = guards.get(i);
if ((guard == interruptedGuard) && (guard.waiterCount == 1)) {
// That one waiter was just interrupted and is throwing InterruptedException rather than
// paying attention to the guard being satisfied, so find another waiter on another guard.
continue;
}
if (guard.isSatisfied()) {
guard.condition.signal();
return;
}
}
} catch (Throwable throwable) {
for (int i = 0; i < guardCount; i++) {
Guard guard = guards.get(i);
guard.condition.signalAll();
}
throw Throwables.propagate(throwable);
}
}
@GuardedBy("lock")
private void incrementWaiters(Guard guard) {
int waiters = guard.waiterCount++;
if (waiters == 0) {
activeGuards.add(guard);
}
}
@GuardedBy("lock")
private void decrementWaiters(Guard guard) {
int waiters = --guard.waiterCount;
if (waiters == 0) {
activeGuards.remove(guard);
}
}
@GuardedBy("lock")
private void waitInterruptibly(Guard guard, boolean signalBeforeWaiting)
throws InterruptedException {
if (!guard.isSatisfied()) {
if (signalBeforeWaiting) {
signalConditionsOfSatisfiedGuards(null);
}
incrementWaiters(guard);
try {
final Condition condition = guard.condition;
do {
try {
condition.await();
} catch (InterruptedException interrupt) {
try {
signalConditionsOfSatisfiedGuards(guard);
} catch (Throwable throwable) {
Thread.currentThread().interrupt();
throw Throwables.propagate(throwable);
}
throw interrupt;
}
} while (!guard.isSatisfied());
} finally {
decrementWaiters(guard);
}
}
}
@GuardedBy("lock")
private void waitUninterruptibly(Guard guard, boolean signalBeforeWaiting) {
if (!guard.isSatisfied()) {
if (signalBeforeWaiting) {
signalConditionsOfSatisfiedGuards(null);
}
incrementWaiters(guard);
try {
final Condition condition = guard.condition;
do {
condition.awaitUninterruptibly();
} while (!guard.isSatisfied());
} finally {
decrementWaiters(guard);
}
}
}
@GuardedBy("lock")
private boolean waitInterruptibly(Guard guard, long remainingNanos, boolean signalBeforeWaiting)
throws InterruptedException {
if (!guard.isSatisfied()) {
if (signalBeforeWaiting) {
signalConditionsOfSatisfiedGuards(null);
}
incrementWaiters(guard);
try {
final Condition condition = guard.condition;
do {
if (remainingNanos <= 0) {
return false;
}
try {
remainingNanos = condition.awaitNanos(remainingNanos);
} catch (InterruptedException interrupt) {
try {
signalConditionsOfSatisfiedGuards(guard);
} catch (Throwable throwable) {
Thread.currentThread().interrupt();
throw Throwables.propagate(throwable);
}
throw interrupt;
}
} while (!guard.isSatisfied());
} finally {
decrementWaiters(guard);
}
}
return true;
}
@GuardedBy("lock")
private boolean waitUninterruptibly(Guard guard, long timeoutNanos,
boolean signalBeforeWaiting) {
if (!guard.isSatisfied()) {
long startNanos = System.nanoTime();
if (signalBeforeWaiting) {
signalConditionsOfSatisfiedGuards(null);
}
boolean interruptIgnored = false;
try {
incrementWaiters(guard);
try {
final Condition condition = guard.condition;
long remainingNanos = timeoutNanos;
do {
if (remainingNanos <= 0) {
return false;
}
try {
remainingNanos = condition.awaitNanos(remainingNanos);
} catch (InterruptedException ignored) {
try {
signalConditionsOfSatisfiedGuards(guard);
} catch (Throwable throwable) {
Thread.currentThread().interrupt();
throw Throwables.propagate(throwable);
}
interruptIgnored = true;
remainingNanos = (timeoutNanos - (System.nanoTime() - startNanos));
}
} while (!guard.isSatisfied());
} finally {
decrementWaiters(guard);
}
} finally {
if (interruptIgnored) {
Thread.currentThread().interrupt();
}
}
}
return true;
}
}
| Java |
/*
* Written by Doug Lea and Martin Buchholz with assistance from
* members of JCP JSR-166 Expert Group and released to the public
* domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
/*
* Source:
* http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/extra/AtomicDouble.java?revision=1.13
* (Modified to adapt to guava coding conventions and
* to use AtomicLongFieldUpdater instead of sun.misc.Unsafe)
*/
package com.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import static java.lang.Double.doubleToRawLongBits;
import static java.lang.Double.longBitsToDouble;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
/**
* A {@code double} value that may be updated atomically. See the
* {@link java.util.concurrent.atomic} package specification for
* description of the properties of atomic variables. An {@code
* AtomicDouble} is used in applications such as atomic accumulation,
* and cannot be used as a replacement for a {@link Double}. However,
* this class does extend {@code Number} to allow uniform access by
* tools and utilities that deal with numerically-based classes.
*
* <p><a name="bitEquals">This class compares primitive {@code double}
* values in methods such as {@link #compareAndSet} by comparing their
* bitwise representation using {@link Double#doubleToRawLongBits},
* which differs from both the primitive double {@code ==} operator
* and from {@link Double#equals}, as if implemented by:
* <pre> {@code
* static boolean bitEquals(double x, double y) {
* long xBits = Double.doubleToRawLongBits(x);
* long yBits = Double.doubleToRawLongBits(y);
* return xBits == yBits;
* }}</pre>
*
* <p>It is possible to write a more scalable updater, at the cost of
* giving up strict atomicity. See for example
* <a href="http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166edocs/jsr166e/DoubleAdder.html"
* DoubleAdder>
* and
* <a href="http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166edocs/jsr166e/DoubleMaxUpdater.html"
* DoubleMaxUpdater>.
*
* @author Doug Lea
* @author Martin Buchholz
* @since 11.0
*/
@Beta
public class AtomicDouble extends Number implements java.io.Serializable {
private static final long serialVersionUID = 0L;
private transient volatile long value;
private static final AtomicLongFieldUpdater<AtomicDouble> updater =
AtomicLongFieldUpdater.newUpdater(AtomicDouble.class, "value");
/**
* Creates a new {@code AtomicDouble} with the given initial value.
*
* @param initialValue the initial value
*/
public AtomicDouble(double initialValue) {
value = doubleToRawLongBits(initialValue);
}
/**
* Creates a new {@code AtomicDouble} with initial value {@code 0.0}.
*/
public AtomicDouble() {
// assert doubleToRawLongBits(0.0) == 0L;
}
/**
* Gets the current value.
*
* @return the current value
*/
public final double get() {
return longBitsToDouble(value);
}
/**
* Sets to the given value.
*
* @param newValue the new value
*/
public final void set(double newValue) {
long next = doubleToRawLongBits(newValue);
value = next;
}
/**
* Eventually sets to the given value.
*
* @param newValue the new value
*/
public final void lazySet(double newValue) {
set(newValue);
// TODO(user): replace with code below when jdk5 support is dropped.
// long next = doubleToRawLongBits(newValue);
// updater.lazySet(this, next);
}
/**
* Atomically sets to the given value and returns the old value.
*
* @param newValue the new value
* @return the previous value
*/
public final double getAndSet(double newValue) {
long next = doubleToRawLongBits(newValue);
return longBitsToDouble(updater.getAndSet(this, next));
}
/**
* Atomically sets the value to the given updated value
* if the current value is <a href="#bitEquals">bitwise equal</a>
* to the expected value.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that
* the actual value was not bitwise equal to the expected value.
*/
public final boolean compareAndSet(double expect, double update) {
return updater.compareAndSet(this,
doubleToRawLongBits(expect),
doubleToRawLongBits(update));
}
/**
* Atomically sets the value to the given updated value
* if the current value is <a href="#bitEquals">bitwise equal</a>
* to the expected value.
*
* <p>May <a
* href="http://download.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html#Spurious">
* fail spuriously</a>
* and does not provide ordering guarantees, so is only rarely an
* appropriate alternative to {@code compareAndSet}.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful
*/
public final boolean weakCompareAndSet(double expect, double update) {
return updater.weakCompareAndSet(this,
doubleToRawLongBits(expect),
doubleToRawLongBits(update));
}
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the previous value
*/
public final double getAndAdd(double delta) {
while (true) {
long current = value;
double currentVal = longBitsToDouble(current);
double nextVal = currentVal + delta;
long next = doubleToRawLongBits(nextVal);
if (updater.compareAndSet(this, current, next)) {
return currentVal;
}
}
}
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the updated value
*/
public final double addAndGet(double delta) {
while (true) {
long current = value;
double currentVal = longBitsToDouble(current);
double nextVal = currentVal + delta;
long next = doubleToRawLongBits(nextVal);
if (updater.compareAndSet(this, current, next)) {
return nextVal;
}
}
}
/**
* Returns the String representation of the current value.
* @return the String representation of the current value
*/
public String toString() {
return Double.toString(get());
}
/**
* Returns the value of this {@code AtomicDouble} as an {@code int}
* after a narrowing primitive conversion.
*/
public int intValue() {
return (int) get();
}
/**
* Returns the value of this {@code AtomicDouble} as a {@code long}
* after a narrowing primitive conversion.
*/
public long longValue() {
return (long) get();
}
/**
* Returns the value of this {@code AtomicDouble} as a {@code float}
* after a narrowing primitive conversion.
*/
public float floatValue() {
return (float) get();
}
/**
* Returns the value of this {@code AtomicDouble} as a {@code double}.
*/
public double doubleValue() {
return get();
}
/**
* Saves the state to a stream (that is, serializes it).
*
* @serialData The current value is emitted (a {@code double}).
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
s.defaultWriteObject();
s.writeDouble(get());
}
/**
* Reconstitutes the instance from a stream (that is, deserializes it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
set(s.readDouble());
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.
*/
/**
* Concurrency utilities.
*
* <p>Commonly used types include {@link
* com.google.common.util.concurrent.ListenableFuture} and {@link
* com.google.common.util.concurrent.Service}.
*
* <p>Commonly used utilities include {@link
* com.google.common.util.concurrent.Futures}, {@link
* com.google.common.util.concurrent.MoreExecutors}, and {@link
* com.google.common.util.concurrent.ThreadFactoryBuilder}.
*
* <p>This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*/
@ParametersAreNonnullByDefault
package com.google.common.util.concurrent;
import javax.annotation.ParametersAreNonnullByDefault;
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.collect.ForwardingQueue;
import java.util.Collection;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* A {@link BlockingQueue} which forwards all its method calls to another
* {@link BlockingQueue}. Subclasses should override one or more methods to
* modify the behavior of the backing collection as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Raimundo Mirisola
*
* @param <E> the type of elements held in this collection
* @since 4.0
*/
public abstract class ForwardingBlockingQueue<E> extends ForwardingQueue<E>
implements BlockingQueue<E> {
/** Constructor for use by subclasses. */
protected ForwardingBlockingQueue() {}
@Override protected abstract BlockingQueue<E> delegate();
@Override public int drainTo(
Collection<? super E> c, int maxElements) {
return delegate().drainTo(c, maxElements);
}
@Override public int drainTo(Collection<? super E> c) {
return delegate().drainTo(c);
}
@Override public boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException {
return delegate().offer(e, timeout, unit);
}
@Override public E poll(long timeout, TimeUnit unit)
throws InterruptedException {
return delegate().poll(timeout, unit);
}
@Override public void put(E e) throws InterruptedException {
delegate().put(e);
}
@Override public int remainingCapacity() {
return delegate().remainingCapacity();
}
@Override public E take() throws InterruptedException {
return delegate().take();
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import com.google.common.base.Throwables;
import java.util.concurrent.Executor;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Base class for services that can implement {@link #startUp}, {@link #run} and
* {@link #shutDown} methods. This class uses a single thread to execute the
* service; consider {@link AbstractService} if you would like to manage any
* threading manually.
*
* @author Jesse Wilson
* @since 1.0
*/
@Beta
public abstract class AbstractExecutionThreadService implements Service {
private static final Logger logger = Logger.getLogger(
AbstractExecutionThreadService.class.getName());
/* use AbstractService for state management */
private final Service delegate = new AbstractService() {
@Override protected final void doStart() {
executor().execute(new Runnable() {
@Override
public void run() {
try {
startUp();
notifyStarted();
if (isRunning()) {
try {
AbstractExecutionThreadService.this.run();
} catch (Throwable t) {
try {
shutDown();
} catch (Exception ignored) {
logger.log(Level.WARNING,
"Error while attempting to shut down the service after failure.", ignored);
}
throw t;
}
}
shutDown();
notifyStopped();
} catch (Throwable t) {
notifyFailed(t);
throw Throwables.propagate(t);
}
}
});
}
@Override protected void doStop() {
triggerShutdown();
}
};
/**
* Start the service. This method is invoked on the execution thread.
*/
protected void startUp() throws Exception {}
/**
* Run the service. This method is invoked on the execution thread.
* Implementations must respond to stop requests. You could poll for lifecycle
* changes in a work loop:
* <pre>
* public void run() {
* while ({@link #isRunning()}) {
* // perform a unit of work
* }
* }
* </pre>
* ...or you could respond to stop requests by implementing {@link
* #triggerShutdown()}, which should cause {@link #run()} to return.
*/
protected abstract void run() throws Exception;
/**
* Stop the service. This method is invoked on the execution thread.
*/
// TODO: consider supporting a TearDownTestCase-like API
protected void shutDown() throws Exception {}
/**
* Invoked to request the service to stop.
*/
protected void triggerShutdown() {}
/**
* Returns the {@link Executor} that will be used to run this service.
* Subclasses may override this method to use a custom {@link Executor}, which
* may configure its worker thread with a specific name, thread group or
* priority. The returned executor's {@link Executor#execute(Runnable)
* execute()} method is called when this service is started, and should return
* promptly.
*
* <p>The default implementation returns a new {@link Executor} that sets the
* name of its threads to the string returned by {@link #getServiceName}
*/
protected Executor executor() {
return new Executor() {
@Override
public void execute(Runnable command) {
new Thread(command, getServiceName()).start();
}
};
}
@Override public String toString() {
return getServiceName() + " [" + state() + "]";
}
// We override instead of using ForwardingService so that these can be final.
@Override public final ListenableFuture<State> start() {
return delegate.start();
}
@Override public final State startAndWait() {
return delegate.startAndWait();
}
@Override public final boolean isRunning() {
return delegate.isRunning();
}
@Override public final State state() {
return delegate.state();
}
@Override public final ListenableFuture<State> stop() {
return delegate.stop();
}
@Override public final State stopAndWait() {
return delegate.stopAndWait();
}
/**
* Returns the name of this service. {@link AbstractExecutionThreadService} may include the name
* in debugging output.
*
* <p>Subclasses may override this method.
*
* @since 10.0
*/
protected String getServiceName() {
return getClass().getSimpleName();
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.base.Preconditions;
import com.google.common.collect.ForwardingObject;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* A {@link Future} which forwards all its method calls to another future.
* Subclasses should override one or more methods to modify the behavior of
* the backing future as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p>Most subclasses can just use {@link SimpleForwardingFuture}.
*
* @author Sven Mawson
* @since 1.0
*/
public abstract class ForwardingFuture<V> extends ForwardingObject
implements Future<V> {
/** Constructor for use by subclasses. */
protected ForwardingFuture() {}
@Override protected abstract Future<V> delegate();
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return delegate().cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return delegate().isCancelled();
}
@Override
public boolean isDone() {
return delegate().isDone();
}
@Override
public V get() throws InterruptedException, ExecutionException {
return delegate().get();
}
@Override
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return delegate().get(timeout, unit);
}
/*
* TODO(cpovirk): Use standard Javadoc form for SimpleForwarding* class and
* constructor
*/
/**
* A simplified version of {@link ForwardingFuture} where subclasses
* can pass in an already constructed {@link Future} as the delegate.
*
* @since 9.0
*/
public abstract static class SimpleForwardingFuture<V>
extends ForwardingFuture<V> {
private final Future<V> delegate;
protected SimpleForwardingFuture(Future<V> delegate) {
this.delegate = Preconditions.checkNotNull(delegate);
}
@Override
protected final Future<V> delegate() {
return delegate;
}
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* 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.google.common.util.concurrent;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
/**
* An {@link ExecutorService} that returns {@link ListenableFuture} instances. To create an instance
* from an existing {@link ExecutorService}, call
* {@link MoreExecutors#listeningDecorator(ExecutorService)}.
*
* @author Chris Povirk
* @since 10.0
*/
public interface ListeningExecutorService extends ExecutorService {
/**
* @return a {@code ListenableFuture} representing pending completion of the task
* @throws RejectedExecutionException {@inheritDoc}
*/
@Override
<T> ListenableFuture<T> submit(Callable<T> task);
/**
* @return a {@code ListenableFuture} representing pending completion of the task
* @throws RejectedExecutionException {@inheritDoc}
*/
@Override
ListenableFuture<?> submit(Runnable task);
/**
* @return a {@code ListenableFuture} representing pending completion of the task
* @throws RejectedExecutionException {@inheritDoc}
*/
@Override
<T> ListenableFuture<T> submit(Runnable task, T result);
/**
* {@inheritDoc}
*
* <p>All elements in the returned list must be {@link ListenableFuture} instances.
*
* @return A list of {@code ListenableFuture} instances representing the tasks, in the same
* sequential order as produced by the iterator for the given task list, each of which has
* completed.
* @throws RejectedExecutionException {@inheritDoc}
* @throws NullPointerException if any task is null
*/
@Override
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
/**
* {@inheritDoc}
*
* <p>All elements in the returned list must be {@link ListenableFuture} instances.
*
* @return a list of {@code ListenableFuture} instances representing the tasks, in the same
* sequential order as produced by the iterator for the given task list. If the operation
* did not time out, each task will have completed. If it did time out, some of these
* tasks will not have completed.
* @throws RejectedExecutionException {@inheritDoc}
* @throws NullPointerException if any task is null
*/
@Override
<T> List<Future<T>> invokeAll(
Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException;
}
| Java |
/*
* Copyright (C) 2006 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
/**
* A TimeLimiter implementation which actually does not attempt to limit time
* at all. This may be desirable to use in some unit tests. More importantly,
* attempting to debug a call which is time-limited would be extremely annoying,
* so this gives you a time-limiter you can easily swap in for your real
* time-limiter while you're debugging.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@Beta
public final class FakeTimeLimiter implements TimeLimiter {
@Override
public <T> T newProxy(T target, Class<T> interfaceType, long timeoutDuration,
TimeUnit timeoutUnit) {
return target; // ha ha
}
@Override
public <T> T callWithTimeout(Callable<T> callable, long timeoutDuration,
TimeUnit timeoutUnit, boolean amInterruptible) throws Exception {
return callable.call(); // fooled you
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* 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.google.common.util.concurrent;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.FutureTask;
import javax.annotation.Nullable;
/**
* A {@link FutureTask} that also implements the {@link ListenableFuture}
* interface. Unlike {@code FutureTask}, {@code ListenableFutureTask} does not
* provide an overrideable {@link FutureTask#done() done()} method. For similar
* functionality, call {@link #addListener}.
*
* <p>
*
* @author Sven Mawson
* @since 1.0
*/
public final class ListenableFutureTask<V> extends FutureTask<V>
implements ListenableFuture<V> {
// The execution list to hold our listeners.
private final ExecutionList executionList = new ExecutionList();
/**
* Creates a {@code ListenableFutureTask} that will upon running, execute the
* given {@code Callable}.
*
* @param callable the callable task
* @since 10.0
*/
public static <V> ListenableFutureTask<V> create(Callable<V> callable) {
return new ListenableFutureTask<V>(callable);
}
/**
* Creates a {@code ListenableFutureTask} that will upon running, execute the
* given {@code Runnable}, and arrange that {@code get} will return the
* given result on successful completion.
*
* @param runnable the runnable task
* @param result the result to return on successful completion. If you don't
* need a particular result, consider using constructions of the form:
* {@code ListenableFuture<?> f = ListenableFutureTask.create(runnable,
* null)}
* @since 10.0
*/
public static <V> ListenableFutureTask<V> create(
Runnable runnable, @Nullable V result) {
return new ListenableFutureTask<V>(runnable, result);
}
private ListenableFutureTask(Callable<V> callable) {
super(callable);
}
private ListenableFutureTask(Runnable runnable, @Nullable V result) {
super(runnable, result);
}
@Override
public void addListener(Runnable listener, Executor exec) {
executionList.add(listener, exec);
}
/**
* Internal implementation detail used to invoke the listeners.
*/
@Override
protected void done() {
executionList.execute();
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* 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.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
/**
* A ThreadFactory builder, providing any combination of these features:
* <ul>
* <li> whether threads should be marked as {@linkplain Thread#setDaemon daemon}
* threads
* <li> a {@linkplain ThreadFactoryBuilder#setNameFormat naming format}
* <li> a {@linkplain Thread#setPriority thread priority}
* <li> an {@linkplain Thread#setUncaughtExceptionHandler uncaught exception
* handler}
* <li> a {@linkplain ThreadFactory#newThread backing thread factory}
* </ul>
* If no backing thread factory is provided, a default backing thread factory is
* used as if by calling {@code setThreadFactory(}{@link
* Executors#defaultThreadFactory()}{@code )}.
*
* @author Kurt Alfred Kluever
* @since 4.0
*/
public final class ThreadFactoryBuilder {
private String nameFormat = null;
private Boolean daemon = null;
private Integer priority = null;
private UncaughtExceptionHandler uncaughtExceptionHandler = null;
private ThreadFactory backingThreadFactory = null;
/**
* Creates a new {@link ThreadFactory} builder.
*/
public ThreadFactoryBuilder() {}
/**
* Sets the naming format to use when naming threads ({@link Thread#setName})
* which are created with this ThreadFactory.
*
* @param nameFormat a {@link String#format(String, Object...)}-compatible
* format String, to which a unique integer (0, 1, etc.) will be supplied
* as the single parameter. This integer will be unique to the built
* instance of the ThreadFactory and will be assigned sequentially.
* @return this for the builder pattern
*/
public ThreadFactoryBuilder setNameFormat(String nameFormat) {
String.format(nameFormat, 0); // fail fast if the format is bad or null
this.nameFormat = nameFormat;
return this;
}
/**
* Sets daemon or not for new threads created with this ThreadFactory.
*
* @param daemon whether or not new Threads created with this ThreadFactory
* will be daemon threads
* @return this for the builder pattern
*/
public ThreadFactoryBuilder setDaemon(boolean daemon) {
this.daemon = daemon;
return this;
}
/**
* Sets the priority for new threads created with this ThreadFactory.
*
* @param priority the priority for new Threads created with this
* ThreadFactory
* @return this for the builder pattern
*/
public ThreadFactoryBuilder setPriority(int priority) {
// Thread#setPriority() already checks for validity. These error messages
// are nicer though and will fail-fast.
checkArgument(priority >= Thread.MIN_PRIORITY,
"Thread priority (%s) must be >= %s", priority, Thread.MIN_PRIORITY);
checkArgument(priority <= Thread.MAX_PRIORITY,
"Thread priority (%s) must be <= %s", priority, Thread.MAX_PRIORITY);
this.priority = priority;
return this;
}
/**
* Sets the {@link UncaughtExceptionHandler} for new threads created with this
* ThreadFactory.
*
* @param uncaughtExceptionHandler the uncaught exception handler for new
* Threads created with this ThreadFactory
* @return this for the builder pattern
*/
public ThreadFactoryBuilder setUncaughtExceptionHandler(
UncaughtExceptionHandler uncaughtExceptionHandler) {
this.uncaughtExceptionHandler = checkNotNull(uncaughtExceptionHandler);
return this;
}
/**
* Sets the backing {@link ThreadFactory} for new threads created with this
* ThreadFactory. Threads will be created by invoking #newThread(Runnable) on
* this backing {@link ThreadFactory}.
*
* @param backingThreadFactory the backing {@link ThreadFactory} which will
* be delegated to during thread creation.
* @return this for the builder pattern
*
* @see MoreExecutors
*/
public ThreadFactoryBuilder setThreadFactory(
ThreadFactory backingThreadFactory) {
this.backingThreadFactory = checkNotNull(backingThreadFactory);
return this;
}
/**
* Returns a new thread factory using the options supplied during the building
* process. After building, it is still possible to change the options used to
* build the ThreadFactory and/or build again. State is not shared amongst
* built instances.
*
* @return the fully constructed {@link ThreadFactory}
*/
public ThreadFactory build() {
return build(this);
}
private static ThreadFactory build(ThreadFactoryBuilder builder) {
final String nameFormat = builder.nameFormat;
final Boolean daemon = builder.daemon;
final Integer priority = builder.priority;
final UncaughtExceptionHandler uncaughtExceptionHandler =
builder.uncaughtExceptionHandler;
final ThreadFactory backingThreadFactory =
(builder.backingThreadFactory != null)
? builder.backingThreadFactory
: Executors.defaultThreadFactory();
final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null;
return new ThreadFactory() {
@Override public Thread newThread(Runnable runnable) {
Thread thread = backingThreadFactory.newThread(runnable);
if (nameFormat != null) {
thread.setName(String.format(nameFormat, count.getAndIncrement()));
}
if (daemon != null) {
thread.setDaemon(daemon);
}
if (priority != null) {
thread.setPriority(priority);
}
if (uncaughtExceptionHandler != null) {
thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
}
return thread;
}
};
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.util.concurrent;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RejectedExecutionException;
/**
* A {@link Future} that accepts completion listeners. Each listener has an
* associated executor, and it is invoked using this executor once the future's
* computation is {@linkplain Future#isDone() complete}. If the computation has
* already completed when the listener is added, the listener will execute
* immediately.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained">
* {@code ListenableFuture}</a>.
*
* <h3>Purpose</h3>
*
* Most commonly, {@code ListenableFuture} is used as an input to another
* derived {@code Future}, as in {@link Futures#allAsList(Iterable)
* Futures.allAsList}. Many such methods are impossible to implement efficiently
* without listener support.
*
* <p>It is possible to call {@link #addListener addListener} directly, but this
* is uncommon because the {@code Runnable} interface does not provide direct
* access to the {@code Future} result. (Users who want such access may prefer
* {@link Futures#addCallback Futures.addCallback}.) Still, direct {@code
* addListener} calls are occasionally useful:<pre> {@code
* final String name = ...;
* inFlight.add(name);
* ListenableFuture<Result> future = service.query(name);
* future.addListener(new Runnable() {
* public void run() {
* processedCount.incrementAndGet();
* inFlight.remove(name);
* lastProcessed.set(name);
* logger.info("Done with {0}", name);
* }
* }, executor);}</pre>
*
* <h3>How to get an instance</h3>
*
* Developers are encouraged to return {@code ListenableFuture} from their
* methods so that users can take advantages of the utilities built atop the
* class. The way that they will create {@code ListenableFuture} instances
* depends on how they currently create {@code Future} instances:
* <ul>
* <li>If they are returned from an {@code ExecutorService}, convert that
* service to a {@link ListeningExecutorService}, usually by calling {@link
* MoreExecutors#listeningDecorator(ExecutorService)
* MoreExecutors.listeningDecorator}. (Custom executors may find it more
* convenient to use {@link ListenableFutureTask} directly.)
* <li>If they are manually filled in by a call to {@link FutureTask#set} or a
* similar method, create a {@link SettableFuture} instead. (Users with more
* complex needs may prefer {@link AbstractFuture}.)
* </ul>
*
* Occasionally, an API will return a plain {@code Future} and it will be
* impossible to change the return type. For this case, we provide a more
* expensive workaround in {@code JdkFutureAdapters}. However, when possible, it
* is more efficient and reliable to create a {@code ListenableFuture} directly.
*
* @author Sven Mawson
* @author Nishant Thakkar
* @since 1.0
*/
public interface ListenableFuture<V> extends Future<V> {
/**
* Registers a listener to be {@linkplain Executor#execute(Runnable) run} on
* the given executor. The listener will run when the {@code Future}'s
* computation is {@linkplain Future#isDone() complete} or, if the computation
* is already complete, immediately.
*
* <p>There is no guaranteed ordering of execution of listeners, but any
* listener added through this method is guaranteed to be called once the
* computation is complete.
*
* <p>Exceptions thrown by a listener will be propagated up to the executor.
* Any exception thrown during {@code Executor.execute} (e.g., a {@code
* RejectedExecutionException} or an exception thrown by {@linkplain
* MoreExecutors#sameThreadExecutor inline execution}) will be caught and
* logged.
*
* <p>Note: For fast, lightweight listeners that would be safe to execute in
* any thread, consider {@link MoreExecutors#sameThreadExecutor}. For heavier
* listeners, {@code sameThreadExecutor()} carries some caveats: First, the
* thread that the listener runs in depends on whether the {@code Future} is
* done at the time it is added and on whether it is ever canclled. In
* particular, listeners may run in the thread that calls {@code addListener}
* or the thread that calls {@code cancel}. Second, listeners may run in an
* internal thread of the system responsible for the input {@code Future},
* such as an RPC network thread. Finally, during the execution of a {@code
* sameThreadExecutor()} listener, all other registered but unexecuted
* listeners are prevented from running, even if those listeners are to run
* in other executors.
*
* <p>This is the most general listener interface.
* For common operations performed using listeners,
* see {@link com.google.common.util.concurrent.Futures}
*
* @param listener the listener to run when the computation is complete
* @param executor the executor to run the listener in
* @throws NullPointerException if the executor or listener was null
* @throws RejectedExecutionException if we tried to execute the listener
* immediately but the executor rejected it.
*/
void addListener(Runnable listener, Executor executor);
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* A delegating wrapper around a {@link ListenableFuture} that adds support for
* the {@link #checkedGet()} and {@link #checkedGet(long, TimeUnit)} methods.
*
* @author Sven Mawson
* @since 1.0
*/
@Beta
public abstract class AbstractCheckedFuture<V, X extends Exception>
extends ForwardingListenableFuture.SimpleForwardingListenableFuture<V>
implements CheckedFuture<V, X> {
/**
* Constructs an {@code AbstractCheckedFuture} that wraps a delegate.
*/
protected AbstractCheckedFuture(ListenableFuture<V> delegate) {
super(delegate);
}
/**
* Translates from an {@link InterruptedException},
* {@link CancellationException} or {@link ExecutionException} thrown by
* {@code get} to an exception of type {@code X} to be thrown by
* {@code checkedGet}. Subclasses must implement this method.
*
* <p>If {@code e} is an {@code InterruptedException}, the calling
* {@code checkedGet} method has already restored the interrupt after catching
* the exception. If an implementation of {@link #mapException(Exception)}
* wishes to swallow the interrupt, it can do so by calling
* {@link Thread#interrupted()}.
*
* <p>Subclasses may choose to throw, rather than return, a subclass of
* {@code RuntimeException} to allow creating a CheckedFuture that throws
* both checked and unchecked exceptions.
*/
protected abstract X mapException(Exception e);
/**
* {@inheritDoc}
*
* <p>This implementation calls {@link #get()} and maps that method's standard
* exceptions to instances of type {@code X} using {@link #mapException}.
*
* <p>In addition, if {@code get} throws an {@link InterruptedException}, this
* implementation will set the current thread's interrupt status before
* calling {@code mapException}.
*
* @throws X if {@link #get()} throws an {@link InterruptedException},
* {@link CancellationException}, or {@link ExecutionException}
*/
@Override
public V checkedGet() throws X {
try {
return get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw mapException(e);
} catch (CancellationException e) {
throw mapException(e);
} catch (ExecutionException e) {
throw mapException(e);
}
}
/**
* {@inheritDoc}
*
* <p>This implementation calls {@link #get(long, TimeUnit)} and maps that
* method's standard exceptions (excluding {@link TimeoutException}, which is
* propagated) to instances of type {@code X} using {@link #mapException}.
*
* <p>In addition, if {@code get} throws an {@link InterruptedException}, this
* implementation will set the current thread's interrupt status before
* calling {@code mapException}.
*
* @throws X if {@link #get()} throws an {@link InterruptedException},
* {@link CancellationException}, or {@link ExecutionException}
* @throws TimeoutException {@inheritDoc}
*/
@Override
public V checkedGet(long timeout, TimeUnit unit) throws TimeoutException, X {
try {
return get(timeout, unit);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw mapException(e);
} catch (CancellationException e) {
throw mapException(e);
} catch (ExecutionException e) {
throw mapException(e);
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.util.concurrent;
import javax.annotation.Nullable;
/**
* A {@link ListenableFuture} whose result may be set by a {@link #set(Object)}
* or {@link #setException(Throwable)} call. It may also be cancelled.
*
* @author Sven Mawson
* @since 9.0 (in 1.0 as {@code ValueFuture})
*/
public final class SettableFuture<V> extends AbstractFuture<V> {
/**
* Creates a new {@code SettableFuture} in the default state.
*/
public static <V> SettableFuture<V> create() {
return new SettableFuture<V>();
}
/**
* Explicit private constructor, use the {@link #create} factory method to
* create instances of {@code SettableFuture}.
*/
private SettableFuture() {}
/**
* Sets the value of this future. This method will return {@code true} if
* the value was successfully set, or {@code false} if the future has already
* been set or cancelled.
*
* @param value the value the future should hold.
* @return true if the value was successfully set.
*/
@Override
public boolean set(@Nullable V value) {
return super.set(value);
}
/**
* Sets the future to having failed with the given exception. This exception
* will be wrapped in an {@code ExecutionException} and thrown from the {@code
* get} methods. This method will return {@code true} if the exception was
* successfully set, or {@code false} if the future has already been set or
* cancelled.
*
* @param throwable the exception the future should hold.
* @return true if the exception was successfully set.
*/
@Override
public boolean setException(Throwable throwable) {
return super.setException(throwable);
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* A future which forwards all its method calls to another future. Subclasses
* should override one or more methods to modify the behavior of the backing
* future as desired per the <a href=
* "http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p>Most subclasses can simply extend {@link SimpleForwardingCheckedFuture}.
*
* @param <V> The result type returned by this Future's {@code get} method
* @param <X> The type of the Exception thrown by the Future's
* {@code checkedGet} method
*
* @author Anthony Zana
* @since 9.0
*/
@Beta
public abstract class ForwardingCheckedFuture<V, X extends Exception>
extends ForwardingListenableFuture<V> implements CheckedFuture<V, X> {
@Override
public V checkedGet() throws X {
return delegate().checkedGet();
}
@Override
public V checkedGet(long timeout, TimeUnit unit) throws TimeoutException, X {
return delegate().checkedGet(timeout, unit);
}
@Override
protected abstract CheckedFuture<V, X> delegate();
// TODO(cpovirk): Use Standard Javadoc form for SimpleForwarding*
/**
* A simplified version of {@link ForwardingCheckedFuture} where subclasses
* can pass in an already constructed {@link CheckedFuture} as the delegate.
*
* @since 9.0
*/
@Beta
public abstract static class SimpleForwardingCheckedFuture<
V, X extends Exception> extends ForwardingCheckedFuture<V, X> {
private final CheckedFuture<V, X> delegate;
protected SimpleForwardingCheckedFuture(CheckedFuture<V, X> delegate) {
this.delegate = Preconditions.checkNotNull(delegate);
}
@Override
protected final CheckedFuture<V, X> delegate() {
return delegate;
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
* Unchecked variant of {@link java.util.concurrent.ExecutionException}. As with
* {@code ExecutionException}, the exception's {@linkplain #getCause() cause}
* comes from a failed task, possibly run in another thread.
*
* <p>{@code UncheckedExecutionException} is intended as an alternative to
* {@code ExecutionException} when the exception thrown by a task is an
* unchecked exception. This allows the client code to continue to distinguish
* between checked and unchecked exceptions, even when they come from other
* threads.
*
* <p>When wrapping an {@code Error} from another thread, prefer {@link
* ExecutionError}.
*
* @author Charles Fry
* @since 10.0
*/
@Beta
@GwtCompatible
public class UncheckedExecutionException extends RuntimeException {
/**
* Creates a new instance with {@code null} as its detail message.
*/
protected UncheckedExecutionException() {}
/**
* Creates a new instance with the given detail message.
*/
protected UncheckedExecutionException(String message) {
super(message);
}
/**
* Creates a new instance with the given detail message and cause.
*/
public UncheckedExecutionException(String message, Throwable cause) {
super(message, cause);
}
/**
* Creates a new instance with the given cause.
*/
public UncheckedExecutionException(Throwable cause) {
super(cause);
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.concurrent.GuardedBy;
/**
* Base class for services that can implement {@link #startUp} and {@link #shutDown} but while in
* the "running" state need to perform a periodic task. Subclasses can implement {@link #startUp},
* {@link #shutDown} and also a {@link #runOneIteration} method that will be executed periodically.
*
* <p>This class uses the {@link ScheduledExecutorService} returned from {@link #executor} to run
* the {@link #startUp} and {@link #shutDown} methods and also uses that service to schedule the
* {@link #runOneIteration} that will be executed periodically as specified by its
* {@link Scheduler}. When this service is asked to stop via {@link #stop} or {@link #stopAndWait},
* it will cancel the periodic task (but not interrupt it) and wait for it to stop before running
* the {@link #shutDown} method.
*
* <p>Subclasses are guaranteed that the life cycle methods ({@link #runOneIteration}, {@link
* #startUp} and {@link #shutDown}) will never run concurrently. Notably, if any execution of {@link
* #runOneIteration} takes longer than its schedule defines, then subsequent executions may start
* late. Also, all life cycle methods are executed with a lock held, so subclasses can safely
* modify shared state without additional synchronization necessary for visibility to later
* executions of the life cycle methods.
*
* <h3>Usage Example</h3>
*
* Here is a sketch of a service which crawls a website and uses the scheduling capabilities to
* rate limit itself. <pre> {@code
* class CrawlingService extends AbstractScheduledService {
* private Set<Uri> visited;
* private Queue<Uri> toCrawl;
* protected void startUp() throws Exception {
* toCrawl = readStartingUris();
* }
*
* protected void runOneIteration() throws Exception {
* Uri uri = toCrawl.remove();
* Collection<Uri> newUris = crawl(uri);
* visited.add(uri);
* for (Uri newUri : newUris) {
* if (!visited.contains(newUri)) { toCrawl.add(newUri); }
* }
* }
*
* protected void shutDown() throws Exception {
* saveUris(toCrawl);
* }
*
* protected Scheduler scheduler() {
* return Scheduler.newFixedRateSchedule(0, 1, TimeUnit.SECONDS);
* }
* }}</pre>
*
* This class uses the life cycle methods to read in a list of starting URIs and save the set of
* outstanding URIs when shutting down. Also, it takes advantage of the scheduling functionality to
* rate limit the number of queries we perform.
*
* @author Luke Sandberg
* @since 11.0
*/
@Beta
public abstract class AbstractScheduledService implements Service {
private static final Logger logger = Logger.getLogger(AbstractScheduledService.class.getName());
/**
* A scheduler defines the policy for how the {@link AbstractScheduledService} should run its
* task.
*
* <p>Consider using the {@link #newFixedDelaySchedule} and {@link #newFixedRateSchedule} factory
* methods, these provide {@link Scheduler} instances for the common use case of running the
* service with a fixed schedule. If more flexibility is needed then consider subclassing the
* {@link CustomScheduler} abstract class in preference to creating your own {@link Scheduler}
* implementation.
*
* @author Luke Sandberg
* @since 11.0
*/
public abstract static class Scheduler {
/**
* Returns a {@link Scheduler} that schedules the task using the
* {@link ScheduledExecutorService#scheduleWithFixedDelay} method.
*
* @param initialDelay the time to delay first execution
* @param delay the delay between the termination of one execution and the commencement of the
* next
* @param unit the time unit of the initialDelay and delay parameters
*/
public static Scheduler newFixedDelaySchedule(final long initialDelay, final long delay,
final TimeUnit unit) {
return new Scheduler() {
@Override
public Future<?> schedule(AbstractService service, ScheduledExecutorService executor,
Runnable task) {
return executor.scheduleWithFixedDelay(task, initialDelay, delay, unit);
}
};
}
/**
* Returns a {@link Scheduler} that schedules the task using the
* {@link ScheduledExecutorService#scheduleAtFixedRate} method.
*
* @param initialDelay the time to delay first execution
* @param period the period between successive executions of the task
* @param unit the time unit of the initialDelay and period parameters
*/
public static Scheduler newFixedRateSchedule(final long initialDelay, final long period,
final TimeUnit unit) {
return new Scheduler() {
@Override
public Future<?> schedule(AbstractService service, ScheduledExecutorService executor,
Runnable task) {
return executor.scheduleAtFixedRate(task, initialDelay, period, unit);
}
};
}
/** Schedules the task to run on the provided executor on behalf of the service. */
abstract Future<?> schedule(AbstractService service, ScheduledExecutorService executor,
Runnable runnable);
private Scheduler() {}
}
/* use AbstractService for state management */
private final AbstractService delegate = new AbstractService() {
// A handle to the running task so that we can stop it when a shutdown has been requested.
// These two fields are volatile because their values will be accessed from multiple threads.
private volatile Future<?> runningTask;
private volatile ScheduledExecutorService executorService;
// This lock protects the task so we can ensure that none of the template methods (startUp,
// shutDown or runOneIteration) run concurrently with one another.
private final ReentrantLock lock = new ReentrantLock();
private final Runnable task = new Runnable() {
@Override public void run() {
lock.lock();
try {
AbstractScheduledService.this.runOneIteration();
} catch (Throwable t) {
try {
shutDown();
} catch (Exception ignored) {
logger.log(Level.WARNING,
"Error while attempting to shut down the service after failure.", ignored);
}
notifyFailed(t);
throw Throwables.propagate(t);
} finally {
lock.unlock();
}
}
};
@Override protected final void doStart() {
executorService = executor();
executorService.execute(new Runnable() {
@Override public void run() {
lock.lock();
try {
startUp();
runningTask = scheduler().schedule(delegate, executorService, task);
notifyStarted();
} catch (Throwable t) {
notifyFailed(t);
throw Throwables.propagate(t);
} finally {
lock.unlock();
}
}
});
}
@Override protected final void doStop() {
runningTask.cancel(false);
executorService.execute(new Runnable() {
@Override public void run() {
try {
lock.lock();
try {
if (state() != State.STOPPING) {
// This means that the state has changed since we were scheduled. This implies that
// an execution of runOneIteration has thrown an exception and we have transitioned
// to a failed state, also this means that shutDown has already been called, so we
// do not want to call it again.
return;
}
shutDown();
} finally {
lock.unlock();
}
notifyStopped();
} catch (Throwable t) {
notifyFailed(t);
throw Throwables.propagate(t);
}
}
});
}
};
/**
* Run one iteration of the scheduled task. If any invocation of this method throws an exception,
* the service will transition to the {@link Service.State#FAILED} state and this method will no
* longer be called.
*/
protected abstract void runOneIteration() throws Exception;
/** Start the service. */
protected abstract void startUp() throws Exception;
/** Stop the service. This is guaranteed not to run concurrently with {@link #runOneIteration}. */
protected abstract void shutDown() throws Exception;
/**
* Returns the {@link Scheduler} object used to configure this service. This method will only be
* called once.
*/
protected abstract Scheduler scheduler();
/**
* Returns the {@link ScheduledExecutorService} that will be used to execute the {@link #startUp},
* {@link #runOneIteration} and {@link #shutDown} methods. The executor will not be
* {@link ScheduledExecutorService#shutdown} when this service stops. Subclasses may override this
* method to use a custom {@link ScheduledExecutorService} instance.
*
* <p>By default this returns a new {@link ScheduledExecutorService} with a single thread thread
* pool. This method will only be called once.
*/
protected ScheduledExecutorService executor() {
return Executors.newSingleThreadScheduledExecutor();
}
@Override public String toString() {
return getClass().getSimpleName() + " [" + state() + "]";
}
// We override instead of using ForwardingService so that these can be final.
@Override public final ListenableFuture<State> start() {
return delegate.start();
}
@Override public final State startAndWait() {
return delegate.startAndWait();
}
@Override public final boolean isRunning() {
return delegate.isRunning();
}
@Override public final State state() {
return delegate.state();
}
@Override public final ListenableFuture<State> stop() {
return delegate.stop();
}
@Override public final State stopAndWait() {
return delegate.stopAndWait();
}
/**
* A {@link Scheduler} that provides a convenient way for the {@link AbstractScheduledService} to
* use a dynamically changing schedule. After every execution of the task, assuming it hasn't
* been cancelled, the {@link #getNextSchedule} method will be called.
*
* @author Luke Sandberg
* @since 11.0
*/
@Beta
public abstract static class CustomScheduler extends Scheduler {
/**
* A callable class that can reschedule itself using a {@link CustomScheduler}.
*/
private class ReschedulableCallable extends ForwardingFuture<Void> implements Callable<Void> {
/** The underlying task. */
private final Runnable wrappedRunnable;
/** The executor on which this Callable will be scheduled. */
private final ScheduledExecutorService executor;
/**
* The service that is managing this callable. This is used so that failure can be
* reported properly.
*/
private final AbstractService service;
/**
* This lock is used to ensure safe and correct cancellation, it ensures that a new task is
* not scheduled while a cancel is ongoing. Also it protects the currentFuture variable to
* ensure that it is assigned atomically with being scheduled.
*/
private final ReentrantLock lock = new ReentrantLock();
/** The future that represents the next execution of this task.*/
@GuardedBy("lock")
private Future<Void> currentFuture;
ReschedulableCallable(AbstractService service, ScheduledExecutorService executor,
Runnable runnable) {
this.wrappedRunnable = runnable;
this.executor = executor;
this.service = service;
}
@Override
public Void call() throws Exception {
wrappedRunnable.run();
reschedule();
return null;
}
/**
* Atomically reschedules this task and assigns the new future to {@link #currentFuture}.
*/
public void reschedule() {
// We reschedule ourselves with a lock held for two reasons. 1. we want to make sure that
// cancel calls cancel on the correct future. 2. we want to make sure that the assignment
// to currentFuture doesn't race with itself so that currentFuture is assigned in the
// correct order.
lock.lock();
try {
if (currentFuture == null || !currentFuture.isCancelled()) {
final Schedule schedule = CustomScheduler.this.getNextSchedule();
currentFuture = executor.schedule(this, schedule.delay, schedule.unit);
}
} catch (Throwable e) {
// If an exception is thrown by the subclass then we need to make sure that the service
// notices and transitions to the FAILED state. We do it by calling notifyFailed directly
// because the service does not monitor the state of the future so if the exception is not
// caught and forwarded to the service the task would stop executing but the service would
// have no idea.
service.notifyFailed(e);
} finally {
lock.unlock();
}
}
// N.B. Only protect cancel and isCancelled because those are the only methods that are
// invoked by the AbstractScheduledService.
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
// Ensure that a task cannot be rescheduled while a cancel is ongoing.
lock.lock();
try {
return currentFuture.cancel(mayInterruptIfRunning);
} finally {
lock.unlock();
}
}
@Override
protected Future<Void> delegate() {
throw new UnsupportedOperationException("Only cancel is supported by this future");
}
}
@Override
final Future<?> schedule(AbstractService service, ScheduledExecutorService executor,
Runnable runnable) {
ReschedulableCallable task = new ReschedulableCallable(service, executor, runnable);
task.reschedule();
return task;
}
/**
* A value object that represents an absolute delay until a task should be invoked.
*
* @author Luke Sandberg
* @since 11.0
*/
@Beta
protected static final class Schedule {
private final long delay;
private final TimeUnit unit;
/**
* @param delay the time from now to delay execution
* @param unit the time unit of the delay parameter
*/
public Schedule(long delay, TimeUnit unit) {
this.delay = delay;
this.unit = Preconditions.checkNotNull(unit);
}
}
/**
* Calculates the time at which to next invoke the task.
*
* <p>This is guaranteed to be called immediately after the task has completed an iteration and
* on the same thread as the previous execution of {@link
* AbstractScheduledService#runOneIteration}.
*
* @return a schedule that defines the delay before the next execution.
*/
protected abstract Schedule getNextSchedule() throws Exception;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <p>A list of listeners, each with an associated {@code Executor}, that
* guarantees that every {@code Runnable} that is {@linkplain #add added} will
* be executed after {@link #execute()} is called. Any {@code Runnable} added
* after the call to {@code execute} is still guaranteed to execute. There is no
* guarantee, however, that listeners will be executed in the order that they
* are added.
*
* <p>Exceptions thrown by a listener will be propagated up to the executor.
* Any exception thrown during {@code Executor.execute} (e.g., a {@code
* RejectedExecutionException} or an exception thrown by {@linkplain
* MoreExecutors#sameThreadExecutor inline execution}) will be caught and
* logged.
*
* @author Nishant Thakkar
* @author Sven Mawson
* @since 1.0
*/
public final class ExecutionList {
// Logger to log exceptions caught when running runnables.
private static final Logger log =
Logger.getLogger(ExecutionList.class.getName());
// The runnable,executor pairs to execute.
private final Queue<RunnableExecutorPair> runnables = Lists.newLinkedList();
// Boolean we use mark when execution has started. Only accessed from within
// synchronized blocks.
private boolean executed = false;
/** Creates a new, empty {@link ExecutionList}. */
public ExecutionList() {
}
/**
* Adds the {@code Runnable} and accompanying {@code Executor} to the list of
* listeners to execute. If execution has already begun, the listener is
* executed immediately.
*
* <p>Note: For fast, lightweight listeners that would be safe to execute in
* any thread, consider {@link MoreExecutors#sameThreadExecutor}. For heavier
* listeners, {@code sameThreadExecutor()} carries some caveats: First, the
* thread that the listener runs in depends on whether the {@code
* ExecutionList} has been executed at the time it is added. In particular,
* listeners may run in the thread that calls {@code add}. Second, the thread
* that calls {@link #execute} may be an internal implementation thread, such
* as an RPC network thread, and {@code sameThreadExecutor()} listeners may
* run in this thread. Finally, during the execution of a {@code
* sameThreadExecutor} listener, all other registered but unexecuted
* listeners are prevented from running, even if those listeners are to run
* in other executors.
*/
public void add(Runnable runnable, Executor executor) {
// Fail fast on a null. We throw NPE here because the contract of
// Executor states that it throws NPE on null listener, so we propagate
// that contract up into the add method as well.
Preconditions.checkNotNull(runnable, "Runnable was null.");
Preconditions.checkNotNull(executor, "Executor was null.");
boolean executeImmediate = false;
// Lock while we check state. We must maintain the lock while adding the
// new pair so that another thread can't run the list out from under us.
// We only add to the list if we have not yet started execution.
synchronized (runnables) {
if (!executed) {
runnables.add(new RunnableExecutorPair(runnable, executor));
} else {
executeImmediate = true;
}
}
// Execute the runnable immediately. Because of scheduling this may end up
// getting called before some of the previously added runnables, but we're
// OK with that. If we want to change the contract to guarantee ordering
// among runnables we'd have to modify the logic here to allow it.
if (executeImmediate) {
new RunnableExecutorPair(runnable, executor).execute();
}
}
/**
* Runs this execution list, executing all existing pairs in the order they
* were added. However, note that listeners added after this point may be
* executed before those previously added, and note that the execution order
* of all listeners is ultimately chosen by the implementations of the
* supplied executors.
*
* <p>This method is idempotent. Calling it several times in parallel is
* semantically equivalent to calling it exactly once.
*
* @since 10.0 (present in 1.0 as {@code run})
*/
public void execute() {
// Lock while we update our state so the add method above will finish adding
// any listeners before we start to run them.
synchronized (runnables) {
if (executed) {
return;
}
executed = true;
}
// At this point the runnables will never be modified by another
// thread, so we are safe using it outside of the synchronized block.
while (!runnables.isEmpty()) {
runnables.poll().execute();
}
}
private static class RunnableExecutorPair {
final Runnable runnable;
final Executor executor;
RunnableExecutorPair(Runnable runnable, Executor executor) {
this.runnable = runnable;
this.executor = executor;
}
void execute() {
try {
executor.execute(runnable);
} catch (RuntimeException e) {
// Log it and keep going, bad runnable and/or executor. Don't
// punish the other runnables if we're given a bad one. We only
// catch RuntimeException because we want Errors to propagate up.
log.log(Level.SEVERE, "RuntimeException while executing runnable "
+ runnable + " with executor " + executor, e);
}
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Utilities necessary for working with libraries that supply plain {@link
* Future} instances. Note that, whenver possible, it is strongly preferred to
* modify those libraries to return {@code ListenableFuture} directly.
*
* @author Sven Mawson
* @since 10.0 (replacing {@code Futures.makeListenable}, which
* existed in 1.0)
*/
@Beta
public final class JdkFutureAdapters {
/**
* Assigns a thread to the given {@link Future} to provide {@link
* ListenableFuture} functionality.
*
* <p><b>Warning:</b> If the input future does not already implement {@link
* ListenableFuture}, the returned future will emulate {@link
* ListenableFuture#addListener} by taking a thread from an internal,
* unbounded pool at the first call to {@code addListener} and holding it
* until the future is {@linkplain Future#isDone() done}.
*
* <p>Prefer to create {@code ListenableFuture} instances with {@link
* SettableFuture}, {@link MoreExecutors#listeningDecorator(
* java.util.concurrent.ExecutorService)}, {@link ListenableFutureTask},
* {@link AbstractFuture}, and other utilities over creating plain {@code
* Future} instances to be upgraded to {@code ListenableFuture} after the
* fact.
*/
public static <V> ListenableFuture<V> listenInPoolThread(
Future<V> future) {
if (future instanceof ListenableFuture<?>) {
return (ListenableFuture<V>) future;
}
return new ListenableFutureAdapter<V>(future);
}
@VisibleForTesting
static <V> ListenableFuture<V> listenInPoolThread(
Future<V> future, Executor executor) {
checkNotNull(executor);
if (future instanceof ListenableFuture<?>) {
return (ListenableFuture<V>) future;
}
return new ListenableFutureAdapter<V>(future, executor);
}
/**
* An adapter to turn a {@link Future} into a {@link ListenableFuture}. This
* will wait on the future to finish, and when it completes, run the
* listeners. This implementation will wait on the source future
* indefinitely, so if the source future never completes, the adapter will
* never complete either.
*
* <p>If the delegate future is interrupted or throws an unexpected unchecked
* exception, the listeners will not be invoked.
*/
private static class ListenableFutureAdapter<V> extends ForwardingFuture<V>
implements ListenableFuture<V> {
private static final ThreadFactory threadFactory =
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("ListenableFutureAdapter-thread-%d")
.build();
private static final Executor defaultAdapterExecutor =
Executors.newCachedThreadPool(threadFactory);
private final Executor adapterExecutor;
// The execution list to hold our listeners.
private final ExecutionList executionList = new ExecutionList();
// This allows us to only start up a thread waiting on the delegate future
// when the first listener is added.
private final AtomicBoolean hasListeners = new AtomicBoolean(false);
// The delegate future.
private final Future<V> delegate;
ListenableFutureAdapter(Future<V> delegate) {
this(delegate, defaultAdapterExecutor);
}
ListenableFutureAdapter(Future<V> delegate, Executor adapterExecutor) {
this.delegate = checkNotNull(delegate);
this.adapterExecutor = checkNotNull(adapterExecutor);
}
@Override
protected Future<V> delegate() {
return delegate;
}
@Override
public void addListener(Runnable listener, Executor exec) {
executionList.add(listener, exec);
// When a listener is first added, we run a task that will wait for
// the delegate to finish, and when it is done will run the listeners.
if (hasListeners.compareAndSet(false, true)) {
if (delegate.isDone()) {
// If the delegate is already done, run the execution list
// immediately on the current thread.
executionList.execute();
return;
}
adapterExecutor.execute(new Runnable() {
@Override
public void run() {
try {
delegate.get();
} catch (Error e) {
throw e;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// Threads from our private pool are never interrupted.
throw new AssertionError(e);
} catch (Throwable e) {
// ExecutionException / CancellationException / RuntimeException
// The task is done, run the listeners.
}
executionList.execute();
}
});
}
}
}
private JdkFutureAdapters() {}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.Beta;
/**
* {@link Error} variant of {@link java.util.concurrent.ExecutionException}. As
* with {@code ExecutionException}, the error's {@linkplain #getCause() cause}
* comes from a failed task, possibly run in another thread. That cause should
* itself be an {@code Error}; if not, use {@code ExecutionException} or {@link
* UncheckedExecutionException}. This allows the client code to continue to
* distinguish between exceptions and errors, even when they come from other
* threads.
*
* @author Chris Povirk
* @since 10.0
*/
@Beta
@GwtCompatible
public class ExecutionError extends Error {
/**
* Creates a new instance with {@code null} as its detail message.
*/
protected ExecutionError() {}
/**
* Creates a new instance with the given detail message.
*/
protected ExecutionError(String message) {
super(message);
}
/**
* Creates a new instance with the given detail message and cause.
*/
public ExecutionError(String message, Error cause) {
super(message, cause);
}
/**
* Creates a new instance with the given cause.
*/
public ExecutionError(Error cause) {
super(cause);
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import java.util.concurrent.Future;
/**
* Transforms a value, possibly asynchronously. For an example usage and more
* information, see {@link Futures#transform(ListenableFuture, AsyncFunction)}.
*
* @author Chris Povirk
* @since 11.0
*/
@Beta
public interface AsyncFunction<I, O> {
/**
* Returns an output {@code Future} to use in place of the given {@code
* input}. The output {@code Future} need not be {@linkplain Future#isDone
* done}, making {@code AsyncFunction} suitable for asynchronous derivations.
*
* <p>Throwing an exception from this method is equivalent to returning a
* failing {@code Future}.
*/
ListenableFuture<O> apply(I input) throws Exception;
}
| Java |
/*
* This file is a modified version of
* http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/AbstractExecutorService.java?revision=1.35
* which contained the following notice:
*
* Written by Doug Lea with assistance from members of JCP JSR-166 Expert Group and released to the
* public domain, as explained at http://creativecommons.org/publicdomain/zero/1.0/
*
* Rationale for copying:
* Guava targets JDK5, whose AbstractExecutorService class lacks the newTaskFor protected
* customization methods needed by MoreExecutors.listeningDecorator. This class is a copy of
* AbstractExecutorService from the JSR166 CVS repository. It contains the desired methods.
*/
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Implements {@link ListeningExecutorService} execution methods atop the abstract {@link #execute}
* method. More concretely, the {@code submit}, {@code invokeAny} and {@code invokeAll} methods
* create {@link ListenableFutureTask} instances and pass them to {@link #execute}.
*
* <p>In addition to {@link #execute}, subclasses must implement all methods related to shutdown and
* termination.
*
* @author Doug Lea
*/
abstract class AbstractListeningExecutorService implements ListeningExecutorService {
@Override public ListenableFuture<?> submit(Runnable task) {
ListenableFutureTask<Void> ftask = ListenableFutureTask.create(task, null);
execute(ftask);
return ftask;
}
@Override public <T> ListenableFuture<T> submit(Runnable task, T result) {
ListenableFutureTask<T> ftask = ListenableFutureTask.create(task, result);
execute(ftask);
return ftask;
}
@Override public <T> ListenableFuture<T> submit(Callable<T> task) {
ListenableFutureTask<T> ftask = ListenableFutureTask.create(task);
execute(ftask);
return ftask;
}
/**
* the main mechanics of invokeAny.
*/
private <T> T doInvokeAny(Collection<? extends Callable<T>> tasks, boolean timed, long nanos)
throws InterruptedException, ExecutionException, TimeoutException {
int ntasks = tasks.size();
checkArgument(ntasks > 0);
List<Future<T>> futures = new ArrayList<Future<T>>(ntasks);
ExecutorCompletionService<T> ecs = new ExecutorCompletionService<T>(this);
// For efficiency, especially in executors with limited
// parallelism, check to see if previously submitted tasks are
// done before submitting more of them. This interleaving
// plus the exception mechanics account for messiness of main
// loop.
try {
// Record exceptions so that if we fail to obtain any
// result, we can throw the last exception we got.
ExecutionException ee = null;
long lastTime = timed ? System.nanoTime() : 0;
Iterator<? extends Callable<T>> it = tasks.iterator();
// Start one task for sure; the rest incrementally
futures.add(ecs.submit(it.next()));
--ntasks;
int active = 1;
for (;;) {
Future<T> f = ecs.poll();
if (f == null) {
if (ntasks > 0) {
--ntasks;
futures.add(ecs.submit(it.next()));
++active;
} else if (active == 0) {
break;
} else if (timed) {
f = ecs.poll(nanos, TimeUnit.NANOSECONDS);
if (f == null) {
throw new TimeoutException();
}
long now = System.nanoTime();
nanos -= now - lastTime;
lastTime = now;
} else {
f = ecs.take();
}
}
if (f != null) {
--active;
try {
return f.get();
} catch (ExecutionException eex) {
ee = eex;
} catch (RuntimeException rex) {
ee = new ExecutionException(rex);
}
}
}
if (ee == null) {
ee = new ExecutionException(null);
}
throw ee;
} finally {
for (Future<T> f : futures) {
f.cancel(true);
}
}
}
@Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException {
try {
return doInvokeAny(tasks, false, 0);
} catch (TimeoutException cannotHappen) {
throw new AssertionError();
}
}
@Override public <T> T invokeAny(
Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return doInvokeAny(tasks, true, unit.toNanos(timeout));
}
@Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException {
if (tasks == null) {
throw new NullPointerException();
}
List<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
boolean done = false;
try {
for (Callable<T> t : tasks) {
ListenableFutureTask<T> f = ListenableFutureTask.create(t);
futures.add(f);
execute(f);
}
for (Future<T> f : futures) {
if (!f.isDone()) {
try {
f.get();
} catch (CancellationException ignore) {
} catch (ExecutionException ignore) {
}
}
}
done = true;
return futures;
} finally {
if (!done) {
for (Future<T> f : futures) {
f.cancel(true);
}
}
}
}
@Override public <T> List<Future<T>> invokeAll(
Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException {
if (tasks == null || unit == null) {
throw new NullPointerException();
}
long nanos = unit.toNanos(timeout);
List<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
boolean done = false;
try {
for (Callable<T> t : tasks) {
futures.add(ListenableFutureTask.create(t));
}
long lastTime = System.nanoTime();
// Interleave time checks and calls to execute in case
// executor doesn't have any/much parallelism.
Iterator<Future<T>> it = futures.iterator();
while (it.hasNext()) {
execute((Runnable) (it.next()));
long now = System.nanoTime();
nanos -= now - lastTime;
lastTime = now;
if (nanos <= 0) {
return futures;
}
}
for (Future<T> f : futures) {
if (!f.isDone()) {
if (nanos <= 0) {
return futures;
}
try {
f.get(nanos, TimeUnit.NANOSECONDS);
} catch (CancellationException ignore) {
} catch (ExecutionException ignore) {
} catch (TimeoutException toe) {
return futures;
}
long now = System.nanoTime();
nanos -= now - lastTime;
lastTime = now;
}
}
done = true;
return futures;
} finally {
if (!done) {
for (Future<T> f : futures) {
f.cancel(true);
}
}
}
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import java.util.concurrent.ScheduledExecutorService;
/**
* A {@link ScheduledExecutorService} that returns {@link ListenableFuture}
* instances from its {@code ExecutorService} methods. Futures returned by the
* {@code schedule*} methods, by contrast, need not implement {@code
* ListenableFuture}. (To create an instance from an existing {@link
* ScheduledExecutorService}, call {@link
* MoreExecutors#listeningDecorator(ScheduledExecutorService)}.
*
* <p>TODO(cpovirk): make at least the one-time schedule() methods return a
* ListenableFuture, too? But then we'll need ListenableScheduledFuture...
*
* @author Chris Povirk
* @since 10.0
*/
@Beta
public interface ListeningScheduledExecutorService
extends ScheduledExecutorService, ListeningExecutorService {
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import com.google.common.base.Throwables;
import java.util.concurrent.Executor;
/**
* Base class for services that do not need a thread while "running"
* but may need one during startup and shutdown. Subclasses can
* implement {@link #startUp} and {@link #shutDown} methods, each
* which run in a executor which by default uses a separate thread
* for each method.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public abstract class AbstractIdleService implements Service {
/* use AbstractService for state management */
private final Service delegate = new AbstractService() {
@Override protected final void doStart() {
executor(State.STARTING).execute(new Runnable() {
@Override public void run() {
try {
startUp();
notifyStarted();
} catch (Throwable t) {
notifyFailed(t);
throw Throwables.propagate(t);
}
}
});
}
@Override protected final void doStop() {
executor(State.STOPPING).execute(new Runnable() {
@Override public void run() {
try {
shutDown();
notifyStopped();
} catch (Throwable t) {
notifyFailed(t);
throw Throwables.propagate(t);
}
}
});
}
};
/** Start the service. */
protected abstract void startUp() throws Exception;
/** Stop the service. */
protected abstract void shutDown() throws Exception;
/**
* Returns the {@link Executor} that will be used to run this service.
* Subclasses may override this method to use a custom {@link Executor}, which
* may configure its worker thread with a specific name, thread group or
* priority. The returned executor's {@link Executor#execute(Runnable)
* execute()} method is called when this service is started and stopped,
* and should return promptly.
*
* @param state {@link Service.State#STARTING} or
* {@link Service.State#STOPPING}, used by the default implementation for
* naming the thread
*/
protected Executor executor(final State state) {
return new Executor() {
@Override
public void execute(Runnable command) {
new Thread(command, getServiceName() + " " + state).start();
}
};
}
@Override public String toString() {
return getServiceName() + " [" + state() + "]";
}
// We override instead of using ForwardingService so that these can be final.
@Override public final ListenableFuture<State> start() {
return delegate.start();
}
@Override public final State startAndWait() {
return delegate.startAndWait();
}
@Override public final boolean isRunning() {
return delegate.isRunning();
}
@Override public final State state() {
return delegate.state();
}
@Override public final ListenableFuture<State> stop() {
return delegate.stop();
}
@Override public final State stopAndWait() {
return delegate.stopAndWait();
}
private String getServiceName() {
return getClass().getSimpleName();
}
}
| Java |
/*
* Copyright (C) 2011 The Guava Authors
*
* 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.google.common.util.concurrent;
import java.util.concurrent.Callable;
/**
* A listening executor service which forwards all its method calls to another
* listening executor service. Subclasses should override one or more methods to
* modify the behavior of the backing executor service as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* @author Isaac Shum
* @since 10.0
*/
public abstract class ForwardingListeningExecutorService
extends ForwardingExecutorService implements ListeningExecutorService {
/** Constructor for use by subclasses. */
protected ForwardingListeningExecutorService() {}
@Override
protected abstract ListeningExecutorService delegate();
@Override
public <T> ListenableFuture<T> submit(Callable<T> task) {
return delegate().submit(task);
}
@Override
public ListenableFuture<?> submit(Runnable task) {
return delegate().submit(task);
}
@Override
public <T> ListenableFuture<T> submit(Runnable task, T result) {
return delegate().submit(task, result);
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* 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.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceArray;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to classes in the
* {@code java.util.concurrent.atomic} package.
*
* @author Kurt Alfred Kluever
* @since 10.0
*/
@Beta
public final class Atomics {
private Atomics() {}
/**
* Creates an {@code AtomicReference} instance with no initial value.
*
* @return a new {@code AtomicReference} with no initial value
*/
public static <V> AtomicReference<V> newReference() {
return new AtomicReference<V>();
}
/**
* Creates an {@code AtomicReference} instance with the given initial value.
*
* @param initialValue the initial value
* @return a new {@code AtomicReference} with the given initial value
*/
public static <V> AtomicReference<V> newReference(@Nullable V initialValue) {
return new AtomicReference<V>(initialValue);
}
/**
* Creates an {@code AtomicReferenceArray} instance of given length.
*
* @param length the length of the array
* @return a new {@code AtomicReferenceArray} with the given length
*/
public static <E> AtomicReferenceArray<E> newReferenceArray(int length) {
return new AtomicReferenceArray<E>(length);
}
/**
* Creates an {@code AtomicReferenceArray} instance with the same length as,
* and all elements copied from, the given array.
*
* @param array the array to copy elements from
* @return a new {@code AtomicReferenceArray} copied from the given array
*/
public static <E> AtomicReferenceArray<E> newReferenceArray(E[] array) {
return new AtomicReferenceArray<E>(array);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.util.concurrent.Service.State; // javadoc needs this
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.ReentrantLock;
/**
* Base class for implementing services that can handle {@link #doStart} and
* {@link #doStop} requests, responding to them with {@link #notifyStarted()}
* and {@link #notifyStopped()} callbacks. Its subclasses must manage threads
* manually; consider {@link AbstractExecutionThreadService} if you need only a
* single execution thread.
*
* @author Jesse Wilson
* @since 1.0
*/
@Beta
public abstract class AbstractService implements Service {
private final ReentrantLock lock = new ReentrantLock();
private final Transition startup = new Transition();
private final Transition shutdown = new Transition();
/**
* The internal state, which equals external state unless
* shutdownWhenStartupFinishes is true. Guarded by {@code lock}.
*/
private State state = State.NEW;
/**
* If true, the user requested a shutdown while the service was still starting
* up. Guarded by {@code lock}.
*/
private boolean shutdownWhenStartupFinishes = false;
/**
* This method is called by {@link #start} to initiate service startup. The
* invocation of this method should cause a call to {@link #notifyStarted()},
* either during this method's run, or after it has returned. If startup
* fails, the invocation should cause a call to {@link
* #notifyFailed(Throwable)} instead.
*
* <p>This method should return promptly; prefer to do work on a different
* thread where it is convenient. It is invoked exactly once on service
* startup, even when {@link #start} is called multiple times.
*/
protected abstract void doStart();
/**
* This method should be used to initiate service shutdown. The invocation
* of this method should cause a call to {@link #notifyStopped()}, either
* during this method's run, or after it has returned. If shutdown fails, the
* invocation should cause a call to {@link #notifyFailed(Throwable)} instead.
*
* <p>This method should return promptly; prefer to do work on a different
* thread where it is convenient. It is invoked exactly once on service
* shutdown, even when {@link #stop} is called multiple times.
*/
protected abstract void doStop();
@Override
public final ListenableFuture<State> start() {
lock.lock();
try {
if (state == State.NEW) {
state = State.STARTING;
doStart();
}
} catch (Throwable startupFailure) {
// put the exception in the future, the user can get it via Future.get()
notifyFailed(startupFailure);
} finally {
lock.unlock();
}
return startup;
}
@Override
public final ListenableFuture<State> stop() {
lock.lock();
try {
if (state == State.NEW) {
state = State.TERMINATED;
startup.set(State.TERMINATED);
shutdown.set(State.TERMINATED);
} else if (state == State.STARTING) {
shutdownWhenStartupFinishes = true;
startup.set(State.STOPPING);
} else if (state == State.RUNNING) {
state = State.STOPPING;
doStop();
}
} catch (Throwable shutdownFailure) {
// put the exception in the future, the user can get it via Future.get()
notifyFailed(shutdownFailure);
} finally {
lock.unlock();
}
return shutdown;
}
@Override
public State startAndWait() {
return Futures.getUnchecked(start());
}
@Override
public State stopAndWait() {
return Futures.getUnchecked(stop());
}
/**
* Implementing classes should invoke this method once their service has
* started. It will cause the service to transition from {@link
* State#STARTING} to {@link State#RUNNING}.
*
* @throws IllegalStateException if the service is not
* {@link State#STARTING}.
*/
protected final void notifyStarted() {
lock.lock();
try {
if (state != State.STARTING) {
IllegalStateException failure = new IllegalStateException(
"Cannot notifyStarted() when the service is " + state);
notifyFailed(failure);
throw failure;
}
state = State.RUNNING;
if (shutdownWhenStartupFinishes) {
stop();
} else {
startup.set(State.RUNNING);
}
} finally {
lock.unlock();
}
}
/**
* Implementing classes should invoke this method once their service has
* stopped. It will cause the service to transition from {@link
* State#STOPPING} to {@link State#TERMINATED}.
*
* @throws IllegalStateException if the service is neither {@link
* State#STOPPING} nor {@link State#RUNNING}.
*/
protected final void notifyStopped() {
lock.lock();
try {
if (state != State.STOPPING && state != State.RUNNING) {
IllegalStateException failure = new IllegalStateException(
"Cannot notifyStopped() when the service is " + state);
notifyFailed(failure);
throw failure;
}
state = State.TERMINATED;
shutdown.set(State.TERMINATED);
} finally {
lock.unlock();
}
}
/**
* Invoke this method to transition the service to the
* {@link State#FAILED}. The service will <b>not be stopped</b> if it
* is running. Invoke this method when a service has failed critically or
* otherwise cannot be started nor stopped.
*/
protected final void notifyFailed(Throwable cause) {
checkNotNull(cause);
lock.lock();
try {
if (state == State.STARTING) {
startup.setException(cause);
shutdown.setException(new Exception(
"Service failed to start.", cause));
} else if (state == State.STOPPING) {
shutdown.setException(cause);
} else if (state == State.RUNNING) {
shutdown.setException(new Exception("Service failed while running", cause));
} else if (state == State.NEW || state == State.TERMINATED) {
throw new IllegalStateException("Failed while in state:" + state, cause);
}
state = State.FAILED;
} finally {
lock.unlock();
}
}
@Override
public final boolean isRunning() {
return state() == State.RUNNING;
}
@Override
public final State state() {
lock.lock();
try {
if (shutdownWhenStartupFinishes && state == State.STARTING) {
return State.STOPPING;
} else {
return state;
}
} finally {
lock.unlock();
}
}
@Override public String toString() {
return getClass().getSimpleName() + " [" + state() + "]";
}
/**
* A change from one service state to another, plus the result of the change.
*/
private class Transition extends AbstractFuture<State> {
@Override
public State get(long timeout, TimeUnit unit)
throws InterruptedException, TimeoutException, ExecutionException {
try {
return super.get(timeout, unit);
} catch (TimeoutException e) {
throw new TimeoutException(AbstractService.this.toString());
}
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Factory and utility methods for {@link java.util.concurrent.Executor}, {@link
* ExecutorService}, and {@link ThreadFactory}.
*
* @author Eric Fellheimer
* @author Kyle Littlefield
* @author Justin Mahoney
* @since 3.0
*/
public final class MoreExecutors {
private MoreExecutors() {}
/**
* Converts the given ThreadPoolExecutor into an ExecutorService that exits
* when the application is complete. It does so by using daemon threads and
* adding a shutdown hook to wait for their completion.
*
* <p>This is mainly for fixed thread pools.
* See {@link Executors#newFixedThreadPool(int)}.
*
* @param executor the executor to modify to make sure it exits when the
* application is finished
* @param terminationTimeout how long to wait for the executor to
* finish before terminating the JVM
* @param timeUnit unit of time for the time parameter
* @return an unmodifiable version of the input which will not hang the JVM
*/
@Beta
public static ExecutorService getExitingExecutorService(
ThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
executor.setThreadFactory(new ThreadFactoryBuilder()
.setDaemon(true)
.setThreadFactory(executor.getThreadFactory())
.build());
ExecutorService service = Executors.unconfigurableExecutorService(executor);
addDelayedShutdownHook(service, terminationTimeout, timeUnit);
return service;
}
/**
* Converts the given ScheduledThreadPoolExecutor into a
* ScheduledExecutorService that exits when the application is complete. It
* does so by using daemon threads and adding a shutdown hook to wait for
* their completion.
*
* <p>This is mainly for fixed thread pools.
* See {@link Executors#newScheduledThreadPool(int)}.
*
* @param executor the executor to modify to make sure it exits when the
* application is finished
* @param terminationTimeout how long to wait for the executor to
* finish before terminating the JVM
* @param timeUnit unit of time for the time parameter
* @return an unmodifiable version of the input which will not hang the JVM
*/
@Beta
public static ScheduledExecutorService getExitingScheduledExecutorService(
ScheduledThreadPoolExecutor executor, long terminationTimeout,
TimeUnit timeUnit) {
executor.setThreadFactory(new ThreadFactoryBuilder()
.setDaemon(true)
.setThreadFactory(executor.getThreadFactory())
.build());
ScheduledExecutorService service =
Executors.unconfigurableScheduledExecutorService(executor);
addDelayedShutdownHook(service, terminationTimeout, timeUnit);
return service;
}
/**
* Add a shutdown hook to wait for thread completion in the given
* {@link ExecutorService service}. This is useful if the given service uses
* daemon threads, and we want to keep the JVM from exiting immediately on
* shutdown, instead giving these daemon threads a chance to terminate
* normally.
* @param service ExecutorService which uses daemon threads
* @param terminationTimeout how long to wait for the executor to finish
* before terminating the JVM
* @param timeUnit unit of time for the time parameter
*/
@Beta
public static void addDelayedShutdownHook(
final ExecutorService service, final long terminationTimeout,
final TimeUnit timeUnit) {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
try {
// We'd like to log progress and failures that may arise in the
// following code, but unfortunately the behavior of logging
// is undefined in shutdown hooks.
// This is because the logging code installs a shutdown hook of its
// own. See Cleaner class inside {@link LogManager}.
service.shutdown();
service.awaitTermination(terminationTimeout, timeUnit);
} catch (InterruptedException ignored) {
// We're shutting down anyway, so just ignore.
}
}
}));
}
/**
* Converts the given ThreadPoolExecutor into an ExecutorService that exits
* when the application is complete. It does so by using daemon threads and
* adding a shutdown hook to wait for their completion.
*
* <p>This method waits 120 seconds before continuing with JVM termination,
* even if the executor has not finished its work.
*
* <p>This is mainly for fixed thread pools.
* See {@link Executors#newFixedThreadPool(int)}.
*
* @param executor the executor to modify to make sure it exits when the
* application is finished
* @return an unmodifiable version of the input which will not hang the JVM
*/
@Beta
public static ExecutorService getExitingExecutorService(
ThreadPoolExecutor executor) {
return getExitingExecutorService(executor, 120, TimeUnit.SECONDS);
}
/**
* Converts the given ThreadPoolExecutor into a ScheduledExecutorService that
* exits when the application is complete. It does so by using daemon threads
* and adding a shutdown hook to wait for their completion.
*
* <p>This method waits 120 seconds before continuing with JVM termination,
* even if the executor has not finished its work.
*
* <p>This is mainly for fixed thread pools.
* See {@link Executors#newScheduledThreadPool(int)}.
*
* @param executor the executor to modify to make sure it exits when the
* application is finished
* @return an unmodifiable version of the input which will not hang the JVM
*/
@Beta
public static ScheduledExecutorService getExitingScheduledExecutorService(
ScheduledThreadPoolExecutor executor) {
return getExitingScheduledExecutorService(executor, 120, TimeUnit.SECONDS);
}
/**
* Creates an executor service that runs each task in the thread
* that invokes {@code execute/submit}, as in {@link CallerRunsPolicy} This
* applies both to individually submitted tasks and to collections of tasks
* submitted via {@code invokeAll} or {@code invokeAny}. In the latter case,
* tasks will run serially on the calling thread. Tasks are run to
* completion before a {@code Future} is returned to the caller (unless the
* executor has been shutdown).
*
* <p>Although all tasks are immediately executed in the thread that
* submitted the task, this {@code ExecutorService} imposes a small
* locking overhead on each task submission in order to implement shutdown
* and termination behavior.
*
* <p>The implementation deviates from the {@code ExecutorService}
* specification with regards to the {@code shutdownNow} method. First,
* "best-effort" with regards to canceling running tasks is implemented
* as "no-effort". No interrupts or other attempts are made to stop
* threads executing tasks. Second, the returned list will always be empty,
* as any submitted task is considered to have started execution.
* This applies also to tasks given to {@code invokeAll} or {@code invokeAny}
* which are pending serial execution, even the subset of the tasks that
* have not yet started execution. It is unclear from the
* {@code ExecutorService} specification if these should be included, and
* it's much easier to implement the interpretation that they not be.
* Finally, a call to {@code shutdown} or {@code shutdownNow} may result
* in concurrent calls to {@code invokeAll/invokeAny} throwing
* RejectedExecutionException, although a subset of the tasks may already
* have been executed.
*
* @since 10.0 (<a href="http://code.google.com/p/guava-libraries/wiki/Compatibility"
* >mostly source-compatible</a> since 3.0)
*/
public static ListeningExecutorService sameThreadExecutor() {
return new SameThreadExecutorService();
}
// See sameThreadExecutor javadoc for behavioral notes.
private static class SameThreadExecutorService
extends AbstractListeningExecutorService {
/**
* Lock used whenever accessing the state variables
* (runningTasks, shutdown, terminationCondition) of the executor
*/
private final Lock lock = new ReentrantLock();
/** Signaled after the executor is shutdown and running tasks are done */
private final Condition termination = lock.newCondition();
/*
* Conceptually, these two variables describe the executor being in
* one of three states:
* - Active: shutdown == false
* - Shutdown: runningTasks > 0 and shutdown == true
* - Terminated: runningTasks == 0 and shutdown == true
*/
private int runningTasks = 0;
private boolean shutdown = false;
@Override
public void execute(Runnable command) {
startTask();
try {
command.run();
} finally {
endTask();
}
}
@Override
public boolean isShutdown() {
lock.lock();
try {
return shutdown;
} finally {
lock.unlock();
}
}
@Override
public void shutdown() {
lock.lock();
try {
shutdown = true;
} finally {
lock.unlock();
}
}
// See sameThreadExecutor javadoc for unusual behavior of this method.
@Override
public List<Runnable> shutdownNow() {
shutdown();
return Collections.emptyList();
}
@Override
public boolean isTerminated() {
lock.lock();
try {
return shutdown && runningTasks == 0;
} finally {
lock.unlock();
}
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
long nanos = unit.toNanos(timeout);
lock.lock();
try {
for (;;) {
if (isTerminated()) {
return true;
} else if (nanos <= 0) {
return false;
} else {
nanos = termination.awaitNanos(nanos);
}
}
} finally {
lock.unlock();
}
}
/**
* Checks if the executor has been shut down and increments the running
* task count.
*
* @throws RejectedExecutionException if the executor has been previously
* shutdown
*/
private void startTask() {
lock.lock();
try {
if (isShutdown()) {
throw new RejectedExecutionException("Executor already shutdown");
}
runningTasks++;
} finally {
lock.unlock();
}
}
/**
* Decrements the running task count.
*/
private void endTask() {
lock.lock();
try {
runningTasks--;
if (isTerminated()) {
termination.signalAll();
}
} finally {
lock.unlock();
}
}
}
/**
* Creates an {@link ExecutorService} whose {@code submit} and {@code
* invokeAll} methods submit {@link ListenableFutureTask} instances to the
* given delegate executor. Those methods, as well as {@code execute} and
* {@code invokeAny}, are implemented in terms of calls to {@code
* delegate.execute}. All other methods are forwarded unchanged to the
* delegate. This implies that the returned {@code ListeningExecutorService}
* never calls the delegate's {@code submit}, {@code invokeAll}, and {@code
* invokeAny} methods, so any special handling of tasks must be implemented in
* the delegate's {@code execute} method or by wrapping the returned {@code
* ListeningExecutorService}.
*
* <p>If the delegate executor was already an instance of {@code
* ListeningExecutorService}, it is returned untouched, and the rest of this
* documentation does not apply.
*
* @since 10.0
*/
public static ListeningExecutorService listeningDecorator(
ExecutorService delegate) {
return (delegate instanceof ListeningExecutorService)
? (ListeningExecutorService) delegate
: (delegate instanceof ScheduledExecutorService)
? new ScheduledListeningDecorator((ScheduledExecutorService) delegate)
: new ListeningDecorator(delegate);
}
/**
* Creates a {@link ScheduledExecutorService} whose {@code submit} and {@code
* invokeAll} methods submit {@link ListenableFutureTask} instances to the
* given delegate executor. Those methods, as well as {@code execute} and
* {@code invokeAny}, are implemented in terms of calls to {@code
* delegate.execute}. All other methods are forwarded unchanged to the
* delegate. This implies that the returned {@code
* SchedulingListeningExecutorService} never calls the delegate's {@code
* submit}, {@code invokeAll}, and {@code invokeAny} methods, so any special
* handling of tasks must be implemented in the delegate's {@code execute}
* method or by wrapping the returned {@code
* SchedulingListeningExecutorService}.
*
* <p>If the delegate executor was already an instance of {@code
* ListeningScheduledExecutorService}, it is returned untouched, and the rest
* of this documentation does not apply.
*
* @since 10.0
*/
public static ListeningScheduledExecutorService listeningDecorator(
ScheduledExecutorService delegate) {
return (delegate instanceof ListeningScheduledExecutorService)
? (ListeningScheduledExecutorService) delegate
: new ScheduledListeningDecorator(delegate);
}
private static class ListeningDecorator
extends AbstractListeningExecutorService {
final ExecutorService delegate;
ListeningDecorator(ExecutorService delegate) {
this.delegate = checkNotNull(delegate);
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
return delegate.awaitTermination(timeout, unit);
}
@Override
public boolean isShutdown() {
return delegate.isShutdown();
}
@Override
public boolean isTerminated() {
return delegate.isTerminated();
}
@Override
public void shutdown() {
delegate.shutdown();
}
@Override
public List<Runnable> shutdownNow() {
return delegate.shutdownNow();
}
@Override
public void execute(Runnable command) {
delegate.execute(command);
}
}
private static class ScheduledListeningDecorator
extends ListeningDecorator implements ListeningScheduledExecutorService {
final ScheduledExecutorService delegate;
ScheduledListeningDecorator(ScheduledExecutorService delegate) {
super(delegate);
this.delegate = checkNotNull(delegate);
}
@Override
public ScheduledFuture<?> schedule(
Runnable command, long delay, TimeUnit unit) {
return delegate.schedule(command, delay, unit);
}
@Override
public <V> ScheduledFuture<V> schedule(
Callable<V> callable, long delay, TimeUnit unit) {
return delegate.schedule(callable, delay, unit);
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(
Runnable command, long initialDelay, long period, TimeUnit unit) {
return delegate.scheduleAtFixedRate(command, initialDelay, period, unit);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(
Runnable command, long initialDelay, long delay, TimeUnit unit) {
return delegate.scheduleWithFixedDelay(
command, initialDelay, delay, unit);
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Checksum;
/**
* Provides utility methods for working with files.
*
* <p>All method parameters must be non-null unless documented otherwise.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public final class Files {
/** Maximum loop count when creating temp directories. */
private static final int TEMP_DIR_ATTEMPTS = 10000;
private Files() {}
/**
* Returns a buffered reader that reads from a file using the given
* character set.
*
* @param file the file to read from
* @param charset the character set used when writing the file
* @return the buffered reader
*/
public static BufferedReader newReader(File file, Charset charset)
throws FileNotFoundException {
return new BufferedReader(
new InputStreamReader(new FileInputStream(file), charset));
}
/**
* Returns a buffered writer that writes to a file using the given
* character set.
*
* @param file the file to write to
* @param charset the character set used when writing the file
* @return the buffered writer
*/
public static BufferedWriter newWriter(File file, Charset charset)
throws FileNotFoundException {
return new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file), charset));
}
/**
* Returns a factory that will supply instances of {@link FileInputStream}
* that read from a file.
*
* @param file the file to read from
* @return the factory
*/
public static InputSupplier<FileInputStream> newInputStreamSupplier(
final File file) {
Preconditions.checkNotNull(file);
return new InputSupplier<FileInputStream>() {
@Override
public FileInputStream getInput() throws IOException {
return new FileInputStream(file);
}
};
}
/**
* Returns a factory that will supply instances of {@link FileOutputStream}
* that write to a file.
*
* @param file the file to write to
* @return the factory
*/
public static OutputSupplier<FileOutputStream> newOutputStreamSupplier(
File file) {
return newOutputStreamSupplier(file, false);
}
/**
* Returns a factory that will supply instances of {@link FileOutputStream}
* that write to or append to a file.
*
* @param file the file to write to
* @param append if true, the encoded characters will be appended to the file;
* otherwise the file is overwritten
* @return the factory
*/
public static OutputSupplier<FileOutputStream> newOutputStreamSupplier(
final File file, final boolean append) {
Preconditions.checkNotNull(file);
return new OutputSupplier<FileOutputStream>() {
@Override
public FileOutputStream getOutput() throws IOException {
return new FileOutputStream(file, append);
}
};
}
/**
* Returns a factory that will supply instances of
* {@link InputStreamReader} that read a file using the given character set.
*
* @param file the file to read from
* @param charset the character set used when reading the file
* @return the factory
*/
public static InputSupplier<InputStreamReader> newReaderSupplier(File file,
Charset charset) {
return CharStreams.newReaderSupplier(newInputStreamSupplier(file), charset);
}
/**
* Returns a factory that will supply instances of {@link OutputStreamWriter}
* that write to a file using the given character set.
*
* @param file the file to write to
* @param charset the character set used when writing the file
* @return the factory
*/
public static OutputSupplier<OutputStreamWriter> newWriterSupplier(File file,
Charset charset) {
return newWriterSupplier(file, charset, false);
}
/**
* Returns a factory that will supply instances of {@link OutputStreamWriter}
* that write to or append to a file using the given character set.
*
* @param file the file to write to
* @param charset the character set used when writing the file
* @param append if true, the encoded characters will be appended to the file;
* otherwise the file is overwritten
* @return the factory
*/
public static OutputSupplier<OutputStreamWriter> newWriterSupplier(File file,
Charset charset, boolean append) {
return CharStreams.newWriterSupplier(newOutputStreamSupplier(file, append),
charset);
}
/**
* Reads all bytes from a file into a byte array.
*
* @param file the file to read from
* @return a byte array containing all the bytes from file
* @throws IllegalArgumentException if the file is bigger than the largest
* possible byte array (2^31 - 1)
* @throws IOException if an I/O error occurs
*/
public static byte[] toByteArray(File file) throws IOException {
Preconditions.checkArgument(file.length() <= Integer.MAX_VALUE);
if (file.length() == 0) {
// Some special files are length 0 but have content nonetheless.
return ByteStreams.toByteArray(newInputStreamSupplier(file));
} else {
// Avoid an extra allocation and copy.
byte[] b = new byte[(int) file.length()];
boolean threw = true;
InputStream in = new FileInputStream(file);
try {
ByteStreams.readFully(in, b);
threw = false;
} finally {
Closeables.close(in, threw);
}
return b;
}
}
/**
* Reads all characters from a file into a {@link String}, using the given
* character set.
*
* @param file the file to read from
* @param charset the character set used when reading the file
* @return a string containing all the characters from the file
* @throws IOException if an I/O error occurs
*/
public static String toString(File file, Charset charset) throws IOException {
return new String(toByteArray(file), charset.name());
}
/**
* Copies to a file all bytes from an {@link InputStream} supplied by a
* factory.
*
* @param from the input factory
* @param to the destination file
* @throws IOException if an I/O error occurs
*/
public static void copy(InputSupplier<? extends InputStream> from, File to)
throws IOException {
ByteStreams.copy(from, newOutputStreamSupplier(to));
}
/**
* Overwrites a file with the contents of a byte array.
*
* @param from the bytes to write
* @param to the destination file
* @throws IOException if an I/O error occurs
*/
public static void write(byte[] from, File to) throws IOException {
ByteStreams.write(from, newOutputStreamSupplier(to));
}
/**
* Copies all bytes from a file to an {@link OutputStream} supplied by
* a factory.
*
* @param from the source file
* @param to the output factory
* @throws IOException if an I/O error occurs
*/
public static void copy(File from, OutputSupplier<? extends OutputStream> to)
throws IOException {
ByteStreams.copy(newInputStreamSupplier(from), to);
}
/**
* Copies all bytes from a file to an output stream.
*
* @param from the source file
* @param to the output stream
* @throws IOException if an I/O error occurs
*/
public static void copy(File from, OutputStream to) throws IOException {
ByteStreams.copy(newInputStreamSupplier(from), to);
}
/**
* Copies all the bytes from one file to another.
*.
* @param from the source file
* @param to the destination file
* @throws IOException if an I/O error occurs
* @throws IllegalArgumentException if {@code from.equals(to)}
*/
public static void copy(File from, File to) throws IOException {
Preconditions.checkArgument(!from.equals(to),
"Source %s and destination %s must be different", from, to);
copy(newInputStreamSupplier(from), to);
}
/**
* Copies to a file all characters from a {@link Readable} and
* {@link Closeable} object supplied by a factory, using the given
* character set.
*
* @param from the readable supplier
* @param to the destination file
* @param charset the character set used when writing the file
* @throws IOException if an I/O error occurs
*/
public static <R extends Readable & Closeable> void copy(
InputSupplier<R> from, File to, Charset charset) throws IOException {
CharStreams.copy(from, newWriterSupplier(to, charset));
}
/**
* Writes a character sequence (such as a string) to a file using the given
* character set.
*
* @param from the character sequence to write
* @param to the destination file
* @param charset the character set used when writing the file
* @throws IOException if an I/O error occurs
*/
public static void write(CharSequence from, File to, Charset charset)
throws IOException {
write(from, to, charset, false);
}
/**
* Appends a character sequence (such as a string) to a file using the given
* character set.
*
* @param from the character sequence to append
* @param to the destination file
* @param charset the character set used when writing the file
* @throws IOException if an I/O error occurs
*/
public static void append(CharSequence from, File to, Charset charset)
throws IOException {
write(from, to, charset, true);
}
/**
* Private helper method. Writes a character sequence to a file,
* optionally appending.
*
* @param from the character sequence to append
* @param to the destination file
* @param charset the character set used when writing the file
* @param append true to append, false to overwrite
* @throws IOException if an I/O error occurs
*/
private static void write(CharSequence from, File to, Charset charset,
boolean append) throws IOException {
CharStreams.write(from, newWriterSupplier(to, charset, append));
}
/**
* Copies all characters from a file to a {@link Appendable} &
* {@link Closeable} object supplied by a factory, using the given
* character set.
*
* @param from the source file
* @param charset the character set used when reading the file
* @param to the appendable supplier
* @throws IOException if an I/O error occurs
*/
public static <W extends Appendable & Closeable> void copy(File from,
Charset charset, OutputSupplier<W> to) throws IOException {
CharStreams.copy(newReaderSupplier(from, charset), to);
}
/**
* Copies all characters from a file to an appendable object,
* using the given character set.
*
* @param from the source file
* @param charset the character set used when reading the file
* @param to the appendable object
* @throws IOException if an I/O error occurs
*/
public static void copy(File from, Charset charset, Appendable to)
throws IOException {
CharStreams.copy(newReaderSupplier(from, charset), to);
}
/**
* Returns true if the files contains the same bytes.
*
* @throws IOException if an I/O error occurs
*/
public static boolean equal(File file1, File file2) throws IOException {
if (file1 == file2 || file1.equals(file2)) {
return true;
}
/*
* Some operating systems may return zero as the length for files
* denoting system-dependent entities such as devices or pipes, in
* which case we must fall back on comparing the bytes directly.
*/
long len1 = file1.length();
long len2 = file2.length();
if (len1 != 0 && len2 != 0 && len1 != len2) {
return false;
}
return ByteStreams.equal(newInputStreamSupplier(file1),
newInputStreamSupplier(file2));
}
/**
* Atomically creates a new directory somewhere beneath the system's
* temporary directory (as defined by the {@code java.io.tmpdir} system
* property), and returns its name.
*
* <p>Use this method instead of {@link File#createTempFile(String, String)}
* when you wish to create a directory, not a regular file. A common pitfall
* is to call {@code createTempFile}, delete the file and create a
* directory in its place, but this leads a race condition which can be
* exploited to create security vulnerabilities, especially when executable
* files are to be written into the directory.
*
* <p>This method assumes that the temporary volume is writable, has free
* inodes and free blocks, and that it will not be called thousands of times
* per second.
*
* @return the newly-created directory
* @throws IllegalStateException if the directory could not be created
*/
public static File createTempDir() {
File baseDir = new File(System.getProperty("java.io.tmpdir"));
String baseName = System.currentTimeMillis() + "-";
for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
File tempDir = new File(baseDir, baseName + counter);
if (tempDir.mkdir()) {
return tempDir;
}
}
throw new IllegalStateException("Failed to create directory within "
+ TEMP_DIR_ATTEMPTS + " attempts (tried "
+ baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')');
}
/**
* Creates an empty file or updates the last updated timestamp on the
* same as the unix command of the same name.
*
* @param file the file to create or update
* @throws IOException if an I/O error occurs
*/
public static void touch(File file) throws IOException {
if (!file.createNewFile()
&& !file.setLastModified(System.currentTimeMillis())) {
throw new IOException("Unable to update modification time of " + file);
}
}
/**
* Creates any necessary but nonexistent parent directories of the specified
* file. Note that if this operation fails it may have succeeded in creating
* some (but not all) of the necessary parent directories.
*
* @throws IOException if an I/O error occurs, or if any necessary but
* nonexistent parent directories of the specified file could not be
* created.
* @since 4.0
*/
public static void createParentDirs(File file) throws IOException {
File parent = file.getCanonicalFile().getParentFile();
if (parent == null) {
/*
* The given directory is a filesystem root. All zero of its ancestors
* exist. This doesn't mean that the root itself exists -- consider x:\ on
* a Windows machine without such a drive -- or even that the caller can
* create it, but this method makes no such guarantees even for non-root
* files.
*/
return;
}
parent.mkdirs();
if (!parent.isDirectory()) {
throw new IOException("Unable to create parent directories of " + file);
}
}
/**
* Moves the file from one path to another. This method can rename a file or
* move it to a different directory, like the Unix {@code mv} command.
*
* @param from the source file
* @param to the destination file
* @throws IOException if an I/O error occurs
* @throws IllegalArgumentException if {@code from.equals(to)}
*/
public static void move(File from, File to) throws IOException {
Preconditions.checkNotNull(to);
Preconditions.checkArgument(!from.equals(to),
"Source %s and destination %s must be different", from, to);
if (!from.renameTo(to)) {
copy(from, to);
if (!from.delete()) {
if (!to.delete()) {
throw new IOException("Unable to delete " + to);
}
throw new IOException("Unable to delete " + from);
}
}
}
/**
* Reads the first line from a file. The line does not include
* line-termination characters, but does include other leading and
* trailing whitespace.
*
* @param file the file to read from
* @param charset the character set used when writing the file
* @return the first line, or null if the file is empty
* @throws IOException if an I/O error occurs
*/
public static String readFirstLine(File file, Charset charset)
throws IOException {
return CharStreams.readFirstLine(Files.newReaderSupplier(file, charset));
}
/**
* Reads all of the lines from a file. The lines do not include
* line-termination characters, but do include other leading and
* trailing whitespace.
*
* @param file the file to read from
* @param charset the character set used when writing the file
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
public static List<String> readLines(File file, Charset charset)
throws IOException {
return CharStreams.readLines(Files.newReaderSupplier(file, charset));
}
/**
* Streams lines from a {@link File}, stopping when our callback returns
* false, or we have read all of the lines.
*
* @param file the file to read from
* @param charset the character set used when writing the file
* @param callback the {@link LineProcessor} to use to handle the lines
* @return the output of processing the lines
* @throws IOException if an I/O error occurs
*/
public static <T> T readLines(File file, Charset charset,
LineProcessor<T> callback) throws IOException {
return CharStreams.readLines(Files.newReaderSupplier(file, charset),
callback);
}
/**
* Process the bytes of a file.
*
* <p>(If this seems too complicated, maybe you're looking for
* {@link #toByteArray}.)
*
* @param file the file to read
* @param processor the object to which the bytes of the file are passed.
* @return the result of the byte processor
* @throws IOException if an I/O error occurs
*/
public static <T> T readBytes(File file, ByteProcessor<T> processor)
throws IOException {
return ByteStreams.readBytes(newInputStreamSupplier(file), processor);
}
/**
* Computes and returns the checksum value for a file.
* The checksum object is reset when this method returns successfully.
*
* @param file the file to read
* @param checksum the checksum object
* @return the result of {@link Checksum#getValue} after updating the
* checksum object with all of the bytes in the file
* @throws IOException if an I/O error occurs
*/
public static long getChecksum(File file, Checksum checksum)
throws IOException {
return ByteStreams.getChecksum(newInputStreamSupplier(file), checksum);
}
/**
* Computes and returns the digest value for a file.
* The digest object is reset when this method returns successfully.
*
* @param file the file to read
* @param md the digest object
* @return the result of {@link MessageDigest#digest()} after updating the
* digest object with all of the bytes in this file
* @throws IOException if an I/O error occurs
*/
public static byte[] getDigest(File file, MessageDigest md)
throws IOException {
return ByteStreams.getDigest(newInputStreamSupplier(file), md);
}
/**
* Fully maps a file read-only in to memory as per
* {@link FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}.
*
* <p>Files are mapped from offset 0 to its length.
*
* <p>This only works for files <= {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @return a read-only buffer reflecting {@code file}
* @throws FileNotFoundException if the {@code file} does not exist
* @throws IOException if an I/O error occurs
*
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
public static MappedByteBuffer map(File file) throws IOException {
return map(file, MapMode.READ_ONLY);
}
/**
* Fully maps a file in to memory as per
* {@link FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}
* using the requested {@link MapMode}.
*
* <p>Files are mapped from offset 0 to its length.
*
* <p>This only works for files <= {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @param mode the mode to use when mapping {@code file}
* @return a buffer reflecting {@code file}
* @throws FileNotFoundException if the {@code file} does not exist
* @throws IOException if an I/O error occurs
*
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
public static MappedByteBuffer map(File file, MapMode mode)
throws IOException {
if (!file.exists()) {
throw new FileNotFoundException(file.toString());
}
return map(file, mode, file.length());
}
/**
* Maps a file in to memory as per
* {@link FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}
* using the requested {@link MapMode}.
*
* <p>Files are mapped from offset 0 to {@code size}.
*
* <p>If the mode is {@link MapMode#READ_WRITE} and the file does not exist,
* it will be created with the requested {@code size}. Thus this method is
* useful for creating memory mapped files which do not yet exist.
*
* <p>This only works for files <= {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @param mode the mode to use when mapping {@code file}
* @return a buffer reflecting {@code file}
* @throws IOException if an I/O error occurs
*
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
public static MappedByteBuffer map(File file, MapMode mode, long size)
throws FileNotFoundException, IOException {
RandomAccessFile raf =
new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw");
boolean threw = true;
try {
MappedByteBuffer mbb = map(raf, mode, size);
threw = false;
return mbb;
} finally {
Closeables.close(raf, threw);
}
}
private static MappedByteBuffer map(RandomAccessFile raf, MapMode mode,
long size) throws IOException {
FileChannel channel = raf.getChannel();
boolean threw = true;
try {
MappedByteBuffer mbb = channel.map(mode, 0, size);
threw = false;
return mbb;
} finally {
Closeables.close(channel, threw);
}
}
/**
* Returns the lexically cleaned form of the path name, <i>usually</i> (but
* not always) equivalent to the original. The following heuristics are used:
*
* <ul>
* <li>empty string becomes .
* <li>. stays as .
* <li>fold out ./
* <li>fold out ../ when possible
* <li>collapse multiple slashes
* <li>delete trailing slashes (unless the path is just "/")
* </ul>
*
* These heuristics do not always match the behavior of the filesystem. In
* particular, consider the path {@code a/../b}, which {@code simplifyPath}
* will change to {@code b}. If {@code a} is a symlink to {@code x}, {@code
* a/../b} may refer to a sibling of {@code x}, rather than the sibling of
* {@code a} referred to by {@code b}.
*
* @since 11.0
*/
public static String simplifyPath(String pathname) {
if (pathname.length() == 0) {
return ".";
}
// split the path apart
Iterable<String> components =
Splitter.on('/').omitEmptyStrings().split(pathname);
List<String> path = new ArrayList<String>();
// resolve ., .., and //
for (String component : components) {
if (component.equals(".")) {
continue;
} else if (component.equals("..")) {
if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) {
path.remove(path.size() - 1);
} else {
path.add("..");
}
} else {
path.add(component);
}
}
// put it back together
String result = Joiner.on('/').join(path);
if (pathname.charAt(0) == '/') {
result = "/" + result;
}
while (result.startsWith("/../")) {
result = result.substring(3);
}
if (result.equals("/..")) {
result = "/";
} else if ("".equals(result)) {
result = ".";
}
return result;
}
/**
* Returns the <a href="http://en.wikipedia.org/wiki/Filename_extension">file
* extension</a> for the given file name, or the empty string if the file has
* no extension. The result does not include the '{@code .}'.
*
* @since 11.0
*/
public static String getFileExtension(String fileName) {
checkNotNull(fileName);
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.io;
import java.io.DataInput;
import java.io.IOException;
/**
* An extension of {@code DataInput} for reading from in-memory byte arrays; its
* methods offer identical functionality but do not throw {@link IOException}.
* If any method encounters the end of the array prematurely, it throws {@link
* IllegalStateException}.
*
* @author Kevin Bourrillion
* @since 1.0
*/
public interface ByteArrayDataInput extends DataInput {
@Override void readFully(byte b[]);
@Override void readFully(byte b[], int off, int len);
@Override int skipBytes(int n);
@Override boolean readBoolean();
@Override byte readByte();
@Override int readUnsignedByte();
@Override short readShort();
@Override int readUnsignedShort();
@Override char readChar();
@Override int readInt();
@Override long readLong();
@Override float readFloat();
@Override double readDouble();
@Override String readLine();
@Override String readUTF();
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* An InputStream that limits the number of bytes which can be read.
*
* @author Charles Fry
* @since 1.0
*/
@Beta
public final class LimitInputStream extends FilterInputStream {
private long left;
private long mark = -1;
/**
* Wraps another input stream, limiting the number of bytes which can be read.
*
* @param in the input stream to be wrapped
* @param limit the maximum number of bytes to be read
*/
public LimitInputStream(InputStream in, long limit) {
super(in);
Preconditions.checkNotNull(in);
Preconditions.checkArgument(limit >= 0, "limit must be non-negative");
left = limit;
}
@Override public int available() throws IOException {
return (int) Math.min(in.available(), left);
}
@Override public synchronized void mark(int readlimit) {
in.mark(readlimit);
mark = left;
// it's okay to mark even if mark isn't supported, as reset won't work
}
@Override public int read() throws IOException {
if (left == 0) {
return -1;
}
int result = in.read();
if (result != -1) {
--left;
}
return result;
}
@Override public int read(byte[] b, int off, int len) throws IOException {
if (left == 0) {
return -1;
}
len = (int) Math.min(len, left);
int result = in.read(b, off, len);
if (result != -1) {
left -= result;
}
return result;
}
@Override public synchronized void reset() throws IOException {
if (!in.markSupported()) {
throw new IOException("Mark not supported");
}
if (mark == -1) {
throw new IOException("Mark not set");
}
in.reset();
left = mark;
}
@Override public long skip(long n) throws IOException {
n = Math.min(n, left);
long skipped = in.skip(n);
left -= skipped;
return skipped;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.zip.Checksum;
/**
* Provides utility methods for working with byte arrays and I/O streams.
*
* <p>All method parameters must be non-null unless documented otherwise.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public final class ByteStreams {
private static final int BUF_SIZE = 0x1000; // 4K
private ByteStreams() {}
/**
* Returns a factory that will supply instances of
* {@link ByteArrayInputStream} that read from the given byte array.
*
* @param b the input buffer
* @return the factory
*/
public static InputSupplier<ByteArrayInputStream> newInputStreamSupplier(
byte[] b) {
return newInputStreamSupplier(b, 0, b.length);
}
/**
* Returns a factory that will supply instances of
* {@link ByteArrayInputStream} that read from the given byte array.
*
* @param b the input buffer
* @param off the offset in the buffer of the first byte to read
* @param len the maximum number of bytes to read from the buffer
* @return the factory
*/
public static InputSupplier<ByteArrayInputStream> newInputStreamSupplier(
final byte[] b, final int off, final int len) {
return new InputSupplier<ByteArrayInputStream>() {
@Override
public ByteArrayInputStream getInput() {
return new ByteArrayInputStream(b, off, len);
}
};
}
/**
* Writes a byte array to an output stream from the given supplier.
*
* @param from the bytes to write
* @param to the output supplier
* @throws IOException if an I/O error occurs
*/
public static void write(byte[] from,
OutputSupplier<? extends OutputStream> to) throws IOException {
Preconditions.checkNotNull(from);
boolean threw = true;
OutputStream out = to.getOutput();
try {
out.write(from);
threw = false;
} finally {
Closeables.close(out, threw);
}
}
/**
* Opens input and output streams from the given suppliers, copies all
* bytes from the input to the output, and closes the streams.
*
* @param from the input factory
* @param to the output factory
* @return the number of bytes copied
* @throws IOException if an I/O error occurs
*/
public static long copy(InputSupplier<? extends InputStream> from,
OutputSupplier<? extends OutputStream> to) throws IOException {
int successfulOps = 0;
InputStream in = from.getInput();
try {
OutputStream out = to.getOutput();
try {
long count = copy(in, out);
successfulOps++;
return count;
} finally {
Closeables.close(out, successfulOps < 1);
successfulOps++;
}
} finally {
Closeables.close(in, successfulOps < 2);
}
}
/**
* Opens an input stream from the supplier, copies all bytes from the
* input to the output, and closes the input stream. Does not close
* or flush the output stream.
*
* @param from the input factory
* @param to the output stream to write to
* @return the number of bytes copied
* @throws IOException if an I/O error occurs
*/
public static long copy(InputSupplier<? extends InputStream> from,
OutputStream to) throws IOException {
boolean threw = true;
InputStream in = from.getInput();
try {
long count = copy(in, to);
threw = false;
return count;
} finally {
Closeables.close(in, threw);
}
}
/**
* Opens an output stream from the supplier, copies all bytes from the input
* to the output, and closes the output stream. Does not close or flush the
* input stream.
*
* @param from the input stream to read from
* @param to the output factory
* @return the number of bytes copied
* @throws IOException if an I/O error occurs
* @since 10.0
*/
public static long copy(InputStream from,
OutputSupplier<? extends OutputStream> to) throws IOException {
boolean threw = true;
OutputStream out = to.getOutput();
try {
long count = copy(from, out);
threw = false;
return count;
} finally {
Closeables.close(out, threw);
}
}
/**
* Copies all bytes from the input stream to the output stream.
* Does not close or flush either stream.
*
* @param from the input stream to read from
* @param to the output stream to write to
* @return the number of bytes copied
* @throws IOException if an I/O error occurs
*/
public static long copy(InputStream from, OutputStream to)
throws IOException {
byte[] buf = new byte[BUF_SIZE];
long total = 0;
while (true) {
int r = from.read(buf);
if (r == -1) {
break;
}
to.write(buf, 0, r);
total += r;
}
return total;
}
/**
* Copies all bytes from the readable channel to the writable channel.
* Does not close or flush either channel.
*
* @param from the readable channel to read from
* @param to the writable channel to write to
* @return the number of bytes copied
* @throws IOException if an I/O error occurs
*/
public static long copy(ReadableByteChannel from,
WritableByteChannel to) throws IOException {
ByteBuffer buf = ByteBuffer.allocate(BUF_SIZE);
long total = 0;
while (from.read(buf) != -1) {
buf.flip();
while (buf.hasRemaining()) {
total += to.write(buf);
}
buf.clear();
}
return total;
}
/**
* Reads all bytes from an input stream into a byte array.
* Does not close the stream.
*
* @param in the input stream to read from
* @return a byte array containing all the bytes from the stream
* @throws IOException if an I/O error occurs
*/
public static byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(in, out);
return out.toByteArray();
}
/**
* Returns the data from a {@link InputStream} factory as a byte array.
*
* @param supplier the factory
* @throws IOException if an I/O error occurs
*/
public static byte[] toByteArray(
InputSupplier<? extends InputStream> supplier) throws IOException {
boolean threw = true;
InputStream in = supplier.getInput();
try {
byte[] result = toByteArray(in);
threw = false;
return result;
} finally {
Closeables.close(in, threw);
}
}
/**
* Returns a new {@link ByteArrayDataInput} instance to read from the {@code
* bytes} array from the beginning.
*/
public static ByteArrayDataInput newDataInput(byte[] bytes) {
return new ByteArrayDataInputStream(bytes);
}
/**
* Returns a new {@link ByteArrayDataInput} instance to read from the {@code
* bytes} array, starting at the given position.
*
* @throws IndexOutOfBoundsException if {@code start} is negative or greater
* than the length of the array
*/
public static ByteArrayDataInput newDataInput(byte[] bytes, int start) {
Preconditions.checkPositionIndex(start, bytes.length);
return new ByteArrayDataInputStream(bytes, start);
}
private static class ByteArrayDataInputStream implements ByteArrayDataInput {
final DataInput input;
ByteArrayDataInputStream(byte[] bytes) {
this.input = new DataInputStream(new ByteArrayInputStream(bytes));
}
ByteArrayDataInputStream(byte[] bytes, int start) {
this.input = new DataInputStream(
new ByteArrayInputStream(bytes, start, bytes.length - start));
}
@Override public void readFully(byte b[]) {
try {
input.readFully(b);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public void readFully(byte b[], int off, int len) {
try {
input.readFully(b, off, len);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public int skipBytes(int n) {
try {
return input.skipBytes(n);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public boolean readBoolean() {
try {
return input.readBoolean();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public byte readByte() {
try {
return input.readByte();
} catch (EOFException e) {
throw new IllegalStateException(e);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public int readUnsignedByte() {
try {
return input.readUnsignedByte();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public short readShort() {
try {
return input.readShort();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public int readUnsignedShort() {
try {
return input.readUnsignedShort();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public char readChar() {
try {
return input.readChar();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public int readInt() {
try {
return input.readInt();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public long readLong() {
try {
return input.readLong();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public float readFloat() {
try {
return input.readFloat();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public double readDouble() {
try {
return input.readDouble();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public String readLine() {
try {
return input.readLine();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public String readUTF() {
try {
return input.readUTF();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
/**
* Returns a new {@link ByteArrayDataOutput} instance with a default size.
*/
public static ByteArrayDataOutput newDataOutput() {
return new ByteArrayDataOutputStream();
}
/**
* Returns a new {@link ByteArrayDataOutput} instance sized to hold
* {@code size} bytes before resizing.
*
* @throws IllegalArgumentException if {@code size} is negative
*/
public static ByteArrayDataOutput newDataOutput(int size) {
Preconditions.checkArgument(size >= 0, "Invalid size: %s", size);
return new ByteArrayDataOutputStream(size);
}
@SuppressWarnings("deprecation") // for writeBytes
private static class ByteArrayDataOutputStream
implements ByteArrayDataOutput {
final DataOutput output;
final ByteArrayOutputStream byteArrayOutputSteam;
ByteArrayDataOutputStream() {
this(new ByteArrayOutputStream());
}
ByteArrayDataOutputStream(int size) {
this(new ByteArrayOutputStream(size));
}
ByteArrayDataOutputStream(ByteArrayOutputStream byteArrayOutputSteam) {
this.byteArrayOutputSteam = byteArrayOutputSteam;
output = new DataOutputStream(byteArrayOutputSteam);
}
@Override public void write(int b) {
try {
output.write(b);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void write(byte[] b) {
try {
output.write(b);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void write(byte[] b, int off, int len) {
try {
output.write(b, off, len);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeBoolean(boolean v) {
try {
output.writeBoolean(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeByte(int v) {
try {
output.writeByte(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeBytes(String s) {
try {
output.writeBytes(s);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeChar(int v) {
try {
output.writeChar(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeChars(String s) {
try {
output.writeChars(s);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeDouble(double v) {
try {
output.writeDouble(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeFloat(float v) {
try {
output.writeFloat(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeInt(int v) {
try {
output.writeInt(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeLong(long v) {
try {
output.writeLong(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeShort(int v) {
try {
output.writeShort(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeUTF(String s) {
try {
output.writeUTF(s);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public byte[] toByteArray() {
return byteArrayOutputSteam.toByteArray();
}
}
// TODO(chrisn): Not all streams support skipping.
/** Returns the length of a supplied input stream, in bytes. */
public static long length(InputSupplier<? extends InputStream> supplier)
throws IOException {
long count = 0;
boolean threw = true;
InputStream in = supplier.getInput();
try {
while (true) {
// We skip only Integer.MAX_VALUE due to JDK overflow bugs.
long amt = in.skip(Integer.MAX_VALUE);
if (amt == 0) {
if (in.read() == -1) {
threw = false;
return count;
}
count++;
} else {
count += amt;
}
}
} finally {
Closeables.close(in, threw);
}
}
/**
* Returns true if the supplied input streams contain the same bytes.
*
* @throws IOException if an I/O error occurs
*/
public static boolean equal(InputSupplier<? extends InputStream> supplier1,
InputSupplier<? extends InputStream> supplier2) throws IOException {
byte[] buf1 = new byte[BUF_SIZE];
byte[] buf2 = new byte[BUF_SIZE];
boolean threw = true;
InputStream in1 = supplier1.getInput();
try {
InputStream in2 = supplier2.getInput();
try {
while (true) {
int read1 = read(in1, buf1, 0, BUF_SIZE);
int read2 = read(in2, buf2, 0, BUF_SIZE);
if (read1 != read2 || !Arrays.equals(buf1, buf2)) {
threw = false;
return false;
} else if (read1 != BUF_SIZE) {
threw = false;
return true;
}
}
} finally {
Closeables.close(in2, threw);
}
} finally {
Closeables.close(in1, threw);
}
}
/**
* Attempts to read enough bytes from the stream to fill the given byte array,
* with the same behavior as {@link DataInput#readFully(byte[])}.
* Does not close the stream.
*
* @param in the input stream to read from.
* @param b the buffer into which the data is read.
* @throws EOFException if this stream reaches the end before reading all
* the bytes.
* @throws IOException if an I/O error occurs.
*/
public static void readFully(InputStream in, byte[] b) throws IOException {
readFully(in, b, 0, b.length);
}
/**
* Attempts to read {@code len} bytes from the stream into the given array
* starting at {@code off}, with the same behavior as
* {@link DataInput#readFully(byte[], int, int)}. Does not close the
* stream.
*
* @param in the input stream to read from.
* @param b the buffer into which the data is read.
* @param off an int specifying the offset into the data.
* @param len an int specifying the number of bytes to read.
* @throws EOFException if this stream reaches the end before reading all
* the bytes.
* @throws IOException if an I/O error occurs.
*/
public static void readFully(InputStream in, byte[] b, int off, int len)
throws IOException {
if (read(in, b, off, len) != len) {
throw new EOFException();
}
}
/**
* Discards {@code n} bytes of data from the input stream. This method
* will block until the full amount has been skipped. Does not close the
* stream.
*
* @param in the input stream to read from
* @param n the number of bytes to skip
* @throws EOFException if this stream reaches the end before skipping all
* the bytes
* @throws IOException if an I/O error occurs, or the stream does not
* support skipping
*/
public static void skipFully(InputStream in, long n) throws IOException {
while (n > 0) {
long amt = in.skip(n);
if (amt == 0) {
// Force a blocking read to avoid infinite loop
if (in.read() == -1) {
throw new EOFException();
}
n--;
} else {
n -= amt;
}
}
}
/**
* Process the bytes of a supplied stream
*
* @param supplier the input stream factory
* @param processor the object to which to pass the bytes of the stream
* @return the result of the byte processor
* @throws IOException if an I/O error occurs
*/
public static <T> T readBytes(InputSupplier<? extends InputStream> supplier,
ByteProcessor<T> processor) throws IOException {
byte[] buf = new byte[BUF_SIZE];
boolean threw = true;
InputStream in = supplier.getInput();
try {
int amt;
do {
amt = in.read(buf);
if (amt == -1) {
threw = false;
break;
}
} while (processor.processBytes(buf, 0, amt));
return processor.getResult();
} finally {
Closeables.close(in, threw);
}
}
/**
* Computes and returns the checksum value for a supplied input stream.
* The checksum object is reset when this method returns successfully.
*
* @param supplier the input stream factory
* @param checksum the checksum object
* @return the result of {@link Checksum#getValue} after updating the
* checksum object with all of the bytes in the stream
* @throws IOException if an I/O error occurs
*/
public static long getChecksum(InputSupplier<? extends InputStream> supplier,
final Checksum checksum) throws IOException {
return readBytes(supplier, new ByteProcessor<Long>() {
@Override
public boolean processBytes(byte[] buf, int off, int len) {
checksum.update(buf, off, len);
return true;
}
@Override
public Long getResult() {
long result = checksum.getValue();
checksum.reset();
return result;
}
});
}
/**
* Computes and returns the digest value for a supplied input stream.
* The digest object is reset when this method returns successfully.
*
* @param supplier the input stream factory
* @param md the digest object
* @return the result of {@link MessageDigest#digest()} after updating the
* digest object with all of the bytes in the stream
* @throws IOException if an I/O error occurs
*/
public static byte[] getDigest(InputSupplier<? extends InputStream> supplier,
final MessageDigest md) throws IOException {
return readBytes(supplier, new ByteProcessor<byte[]>() {
@Override
public boolean processBytes(byte[] buf, int off, int len) {
md.update(buf, off, len);
return true;
}
@Override
public byte[] getResult() {
return md.digest();
}
});
}
/**
* Reads some bytes from an input stream and stores them into the buffer array
* {@code b}. This method blocks until {@code len} bytes of input data have
* been read into the array, or end of file is detected. The number of bytes
* read is returned, possibly zero. Does not close the stream.
*
* <p>A caller can detect EOF if the number of bytes read is less than
* {@code len}. All subsequent calls on the same stream will return zero.
*
* <p>If {@code b} is null, a {@code NullPointerException} is thrown. If
* {@code off} is negative, or {@code len} is negative, or {@code off+len} is
* greater than the length of the array {@code b}, then an
* {@code IndexOutOfBoundsException} is thrown. If {@code len} is zero, then
* no bytes are read. Otherwise, the first byte read is stored into element
* {@code b[off]}, the next one into {@code b[off+1]}, and so on. The number
* of bytes read is, at most, equal to {@code len}.
*
* @param in the input stream to read from
* @param b the buffer into which the data is read
* @param off an int specifying the offset into the data
* @param len an int specifying the number of bytes to read
* @return the number of bytes read
* @throws IOException if an I/O error occurs
*/
public static int read(InputStream in, byte[] b, int off, int len)
throws IOException {
if (len < 0) {
throw new IndexOutOfBoundsException("len is negative");
}
int total = 0;
while (total < len) {
int result = in.read(b, off + total, len - total);
if (result == -1) {
break;
}
total += result;
}
return total;
}
/**
* Returns an {@link InputSupplier} that returns input streams from the
* an underlying supplier, where each stream starts at the given
* offset and is limited to the specified number of bytes.
*
* @param supplier the supplier from which to get the raw streams
* @param offset the offset in bytes into the underlying stream where
* the returned streams will start
* @param length the maximum length of the returned streams
* @throws IllegalArgumentException if offset or length are negative
*/
public static InputSupplier<InputStream> slice(
final InputSupplier<? extends InputStream> supplier,
final long offset,
final long length) {
Preconditions.checkNotNull(supplier);
Preconditions.checkArgument(offset >= 0, "offset is negative");
Preconditions.checkArgument(length >= 0, "length is negative");
return new InputSupplier<InputStream>() {
@Override public InputStream getInput() throws IOException {
InputStream in = supplier.getInput();
if (offset > 0) {
try {
skipFully(in, offset);
} catch (IOException e) {
Closeables.closeQuietly(in);
throw e;
}
}
return new LimitInputStream(in, length);
}
};
}
/**
* Joins multiple {@link InputStream} suppliers into a single supplier.
* Streams returned from the supplier will contain the concatenated data from
* the streams of the underlying suppliers.
*
* <p>Only one underlying input stream will be open at a time. Closing the
* joined stream will close the open underlying stream.
*
* <p>Reading from the joined stream will throw a {@link NullPointerException}
* if any of the suppliers are null or return null.
*
* @param suppliers the suppliers to concatenate
* @return a supplier that will return a stream containing the concatenated
* stream data
*/
public static InputSupplier<InputStream> join(
final Iterable<? extends InputSupplier<? extends InputStream>> suppliers) {
return new InputSupplier<InputStream>() {
@Override public InputStream getInput() throws IOException {
return new MultiInputStream(suppliers.iterator());
}
};
}
/** Varargs form of {@link #join(Iterable)}. */
public static InputSupplier<InputStream> join(
InputSupplier<? extends InputStream>... suppliers) {
return join(Arrays.asList(suppliers));
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Provides utility methods for working with character streams.
*
* <p>All method parameters must be non-null unless documented otherwise.
*
* <p>Some of the methods in this class take arguments with a generic type of
* {@code Readable & Closeable}. A {@link java.io.Reader} implements both of
* those interfaces. Similarly for {@code Appendable & Closeable} and
* {@link java.io.Writer}.
*
* @author Chris Nokleberg
* @author Bin Zhu
* @since 1.0
*/
@Beta
public final class CharStreams {
private static final int BUF_SIZE = 0x800; // 2K chars (4K bytes)
private CharStreams() {}
/**
* Returns a factory that will supply instances of {@link StringReader} that
* read a string value.
*
* @param value the string to read
* @return the factory
*/
public static InputSupplier<StringReader> newReaderSupplier(
final String value) {
Preconditions.checkNotNull(value);
return new InputSupplier<StringReader>() {
@Override
public StringReader getInput() {
return new StringReader(value);
}
};
}
/**
* Returns a factory that will supply instances of {@link InputStreamReader},
* using the given {@link InputStream} factory and character set.
*
* @param in the factory that will be used to open input streams
* @param charset the character set used to decode the input stream
* @return the factory
*/
public static InputSupplier<InputStreamReader> newReaderSupplier(
final InputSupplier<? extends InputStream> in, final Charset charset) {
Preconditions.checkNotNull(in);
Preconditions.checkNotNull(charset);
return new InputSupplier<InputStreamReader>() {
@Override
public InputStreamReader getInput() throws IOException {
return new InputStreamReader(in.getInput(), charset);
}
};
}
/**
* Returns a factory that will supply instances of {@link OutputStreamWriter},
* using the given {@link OutputStream} factory and character set.
*
* @param out the factory that will be used to open output streams
* @param charset the character set used to encode the output stream
* @return the factory
*/
public static OutputSupplier<OutputStreamWriter> newWriterSupplier(
final OutputSupplier<? extends OutputStream> out, final Charset charset) {
Preconditions.checkNotNull(out);
Preconditions.checkNotNull(charset);
return new OutputSupplier<OutputStreamWriter>() {
@Override
public OutputStreamWriter getOutput() throws IOException {
return new OutputStreamWriter(out.getOutput(), charset);
}
};
}
/**
* Writes a character sequence (such as a string) to an appendable
* object from the given supplier.
*
* @param from the character sequence to write
* @param to the output supplier
* @throws IOException if an I/O error occurs
*/
public static <W extends Appendable & Closeable> void write(CharSequence from,
OutputSupplier<W> to) throws IOException {
Preconditions.checkNotNull(from);
boolean threw = true;
W out = to.getOutput();
try {
out.append(from);
threw = false;
} finally {
Closeables.close(out, threw);
}
}
/**
* Opens {@link Readable} and {@link Appendable} objects from the
* given factories, copies all characters between the two, and closes
* them.
*
* @param from the input factory
* @param to the output factory
* @return the number of characters copied
* @throws IOException if an I/O error occurs
*/
public static <R extends Readable & Closeable,
W extends Appendable & Closeable> long copy(InputSupplier<R> from,
OutputSupplier<W> to) throws IOException {
int successfulOps = 0;
R in = from.getInput();
try {
W out = to.getOutput();
try {
long count = copy(in, out);
successfulOps++;
return count;
} finally {
Closeables.close(out, successfulOps < 1);
successfulOps++;
}
} finally {
Closeables.close(in, successfulOps < 2);
}
}
/**
* Opens a {@link Readable} object from the supplier, copies all characters
* to the {@link Appendable} object, and closes the input. Does not close
* or flush the output.
*
* @param from the input factory
* @param to the object to write to
* @return the number of characters copied
* @throws IOException if an I/O error occurs
*/
public static <R extends Readable & Closeable> long copy(
InputSupplier<R> from, Appendable to) throws IOException {
boolean threw = true;
R in = from.getInput();
try {
long count = copy(in, to);
threw = false;
return count;
} finally {
Closeables.close(in, threw);
}
}
/**
* Copies all characters between the {@link Readable} and {@link Appendable}
* objects. Does not close or flush either object.
*
* @param from the object to read from
* @param to the object to write to
* @return the number of characters copied
* @throws IOException if an I/O error occurs
*/
public static long copy(Readable from, Appendable to) throws IOException {
CharBuffer buf = CharBuffer.allocate(BUF_SIZE);
long total = 0;
while (true) {
int r = from.read(buf);
if (r == -1) {
break;
}
buf.flip();
to.append(buf, 0, r);
total += r;
}
return total;
}
/**
* Reads all characters from a {@link Readable} object into a {@link String}.
* Does not close the {@code Readable}.
*
* @param r the object to read from
* @return a string containing all the characters
* @throws IOException if an I/O error occurs
*/
public static String toString(Readable r) throws IOException {
return toStringBuilder(r).toString();
}
/**
* Returns the characters from a {@link Readable} & {@link Closeable} object
* supplied by a factory as a {@link String}.
*
* @param supplier the factory to read from
* @return a string containing all the characters
* @throws IOException if an I/O error occurs
*/
public static <R extends Readable & Closeable> String toString(
InputSupplier<R> supplier) throws IOException {
return toStringBuilder(supplier).toString();
}
/**
* Reads all characters from a {@link Readable} object into a new
* {@link StringBuilder} instance. Does not close the {@code Readable}.
*
* @param r the object to read from
* @return a {@link StringBuilder} containing all the characters
* @throws IOException if an I/O error occurs
*/
private static StringBuilder toStringBuilder(Readable r) throws IOException {
StringBuilder sb = new StringBuilder();
copy(r, sb);
return sb;
}
/**
* Returns the characters from a {@link Readable} & {@link Closeable} object
* supplied by a factory as a new {@link StringBuilder} instance.
*
* @param supplier the factory to read from
* @throws IOException if an I/O error occurs
*/
private static <R extends Readable & Closeable> StringBuilder toStringBuilder(
InputSupplier<R> supplier) throws IOException {
boolean threw = true;
R r = supplier.getInput();
try {
StringBuilder result = toStringBuilder(r);
threw = false;
return result;
} finally {
Closeables.close(r, threw);
}
}
/**
* Reads the first line from a {@link Readable} & {@link Closeable} object
* supplied by a factory. The line does not include line-termination
* characters, but does include other leading and trailing whitespace.
*
* @param supplier the factory to read from
* @return the first line, or null if the reader is empty
* @throws IOException if an I/O error occurs
*/
public static <R extends Readable & Closeable> String readFirstLine(
InputSupplier<R> supplier) throws IOException {
boolean threw = true;
R r = supplier.getInput();
try {
String line = new LineReader(r).readLine();
threw = false;
return line;
} finally {
Closeables.close(r, threw);
}
}
/**
* Reads all of the lines from a {@link Readable} & {@link Closeable} object
* supplied by a factory. The lines do not include line-termination
* characters, but do include other leading and trailing whitespace.
*
* @param supplier the factory to read from
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
public static <R extends Readable & Closeable> List<String> readLines(
InputSupplier<R> supplier) throws IOException {
boolean threw = true;
R r = supplier.getInput();
try {
List<String> result = readLines(r);
threw = false;
return result;
} finally {
Closeables.close(r, threw);
}
}
/**
* Reads all of the lines from a {@link Readable} object. The lines do
* not include line-termination characters, but do include other
* leading and trailing whitespace.
*
* <p>Does not close the {@code Readable}. If reading files or resources you
* should use the {@link Files#readLines} and {@link Resources#readLines}
* methods.
*
* @param r the object to read from
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
public static List<String> readLines(Readable r) throws IOException {
List<String> result = new ArrayList<String>();
LineReader lineReader = new LineReader(r);
String line;
while ((line = lineReader.readLine()) != null) {
result.add(line);
}
return result;
}
/**
* Streams lines from a {@link Readable} and {@link Closeable} object
* supplied by a factory, stopping when our callback returns false, or we
* have read all of the lines.
*
* @param supplier the factory to read from
* @param callback the LineProcessor to use to handle the lines
* @return the output of processing the lines
* @throws IOException if an I/O error occurs
*/
public static <R extends Readable & Closeable, T> T readLines(
InputSupplier<R> supplier, LineProcessor<T> callback) throws IOException {
boolean threw = true;
R r = supplier.getInput();
try {
LineReader lineReader = new LineReader(r);
String line;
while ((line = lineReader.readLine()) != null) {
if (!callback.processLine(line)) {
break;
}
}
threw = false;
} finally {
Closeables.close(r, threw);
}
return callback.getResult();
}
/**
* Joins multiple {@link Reader} suppliers into a single supplier.
* Reader returned from the supplier will contain the concatenated data
* from the readers of the underlying suppliers.
*
* <p>Reading from the joined reader will throw a {@link NullPointerException}
* if any of the suppliers are null or return null.
*
* <p>Only one underlying reader will be open at a time. Closing the
* joined reader will close the open underlying reader.
*
* @param suppliers the suppliers to concatenate
* @return a supplier that will return a reader containing the concatenated
* data
*/
public static InputSupplier<Reader> join(
final Iterable<? extends InputSupplier<? extends Reader>> suppliers) {
return new InputSupplier<Reader>() {
@Override public Reader getInput() throws IOException {
return new MultiReader(suppliers.iterator());
}
};
}
/** Varargs form of {@link #join(Iterable)}. */
public static InputSupplier<Reader> join(
InputSupplier<? extends Reader>... suppliers) {
return join(Arrays.asList(suppliers));
}
/**
* Discards {@code n} characters of data from the reader. This method
* will block until the full amount has been skipped. Does not close the
* reader.
*
* @param reader the reader to read from
* @param n the number of characters to skip
* @throws EOFException if this stream reaches the end before skipping all
* the bytes
* @throws IOException if an I/O error occurs
*/
public static void skipFully(Reader reader, long n) throws IOException {
while (n > 0) {
long amt = reader.skip(n);
if (amt == 0) {
// force a blocking read
if (reader.read() == -1) {
throw new EOFException();
}
n--;
} else {
n -= amt;
}
}
}
/**
* Returns a Writer that sends all output to the given {@link Appendable}
* target. Closing the writer will close the target if it is {@link
* Closeable}, and flushing the writer will flush the target if it is {@link
* java.io.Flushable}.
*
* @param target the object to which output will be sent
* @return a new Writer object, unless target is a Writer, in which case the
* target is returned
*/
public static Writer asWriter(Appendable target) {
if (target instanceof Writer) {
return (Writer) target;
}
return new AppendableWriter(target);
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import java.io.IOException;
/**
* A factory for readable streams of bytes or characters.
*
* @author Chris Nokleberg
* @since 1.0
*/
public interface InputSupplier<T> {
/**
* Returns an object that encapsulates a readable resource.
* <p>
* Like {@link Iterable#iterator}, this method may be called repeatedly to
* get independent channels to the same underlying resource.
* <p>
* Where the channel maintains a position within the resource, moving that
* cursor within one channel should not affect the starting position of
* channels returned by other calls.
*/
T getInput() throws IOException;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
/**
* An {@link InputStream} that concatenates multiple substreams. At most
* one stream will be open at a time.
*
* @author Chris Nokleberg
* @since 1.0
*/
final class MultiInputStream extends InputStream {
private Iterator<? extends InputSupplier<? extends InputStream>> it;
private InputStream in;
/**
* Creates a new instance.
*
* @param it an iterator of I/O suppliers that will provide each substream
*/
public MultiInputStream(
Iterator<? extends InputSupplier<? extends InputStream>> it)
throws IOException {
this.it = it;
advance();
}
@Override public void close() throws IOException {
if (in != null) {
try {
in.close();
} finally {
in = null;
}
}
}
/**
* Closes the current input stream and opens the next one, if any.
*/
private void advance() throws IOException {
close();
if (it.hasNext()) {
in = it.next().getInput();
}
}
@Override public int available() throws IOException {
if (in == null) {
return 0;
}
return in.available();
}
@Override public boolean markSupported() {
return false;
}
@Override public int read() throws IOException {
if (in == null) {
return -1;
}
int result = in.read();
if (result == -1) {
advance();
return read();
}
return result;
}
@Override public int read(byte[] b, int off, int len) throws IOException {
if (in == null) {
return -1;
}
int result = in.read(b, off, len);
if (result == -1) {
advance();
return read(b, off, len);
}
return result;
}
@Override public long skip(long n) throws IOException {
if (in == null || n <= 0) {
return 0;
}
long result = in.skip(n);
if (result != 0) {
return result;
}
if (read() == -1) {
return 0;
}
return 1 + in.skip(n - 1);
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import java.io.Closeable;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Utility methods for working with {@link Closeable} objects.
*
* @author Michael Lancaster
* @since 1.0
*/
@Beta
public final class Closeables {
@VisibleForTesting static final Logger logger
= Logger.getLogger(Closeables.class.getName());
private Closeables() {}
/**
* Closes a {@link Closeable}, with control over whether an
* {@code IOException} may be thrown. This is primarily useful in a
* finally block, where a thrown exception needs to be logged but not
* propagated (otherwise the original exception will be lost).
*
* <p>If {@code swallowIOException} is true then we never throw
* {@code IOException} but merely log it.
*
* <p>Example:
*
* <p><pre>public void useStreamNicely() throws IOException {
* SomeStream stream = new SomeStream("foo");
* boolean threw = true;
* try {
* // Some code which does something with the Stream. May throw a
* // Throwable.
* threw = false; // No throwable thrown.
* } finally {
* // Close the stream.
* // If an exception occurs, only rethrow it if (threw==false).
* Closeables.close(stream, threw);
* }
* </pre>
*
* @param closeable the {@code Closeable} object to be closed, or null,
* in which case this method does nothing
* @param swallowIOException if true, don't propagate IO exceptions
* thrown by the {@code close} methods
* @throws IOException if {@code swallowIOException} is false and
* {@code close} throws an {@code IOException}.
*/
public static void close(@Nullable Closeable closeable,
boolean swallowIOException) throws IOException {
if (closeable == null) {
return;
}
try {
closeable.close();
} catch (IOException e) {
if (swallowIOException) {
logger.log(Level.WARNING,
"IOException thrown while closing Closeable.", e);
} else {
throw e;
}
}
}
/**
* Equivalent to calling {@code close(closeable, true)}, but with no
* IOException in the signature.
* @param closeable the {@code Closeable} object to be closed, or null, in
* which case this method does nothing
*/
public static void closeQuietly(@Nullable Closeable closeable) {
try {
close(closeable, true);
} catch (IOException e) {
logger.log(Level.SEVERE, "IOException should not have been thrown.", e);
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
import java.util.LinkedList;
import java.util.Queue;
/**
* A class for reading lines of text. Provides the same functionality
* as {@link java.io.BufferedReader#readLine()} but for all {@link Readable}
* objects, not just instances of {@link Reader}.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public final class LineReader {
private final Readable readable;
private final Reader reader;
private final char[] buf = new char[0x1000]; // 4K
private final CharBuffer cbuf = CharBuffer.wrap(buf);
private final Queue<String> lines = new LinkedList<String>();
private final LineBuffer lineBuf = new LineBuffer() {
@Override protected void handleLine(String line, String end) {
lines.add(line);
}
};
/**
* Creates a new instance that will read lines from the given
* {@code Readable} object.
*/
public LineReader(Readable readable) {
Preconditions.checkNotNull(readable);
this.readable = readable;
this.reader = (readable instanceof Reader) ? (Reader) readable : null;
}
/**
* Reads a line of text. A line is considered to be terminated by any
* one of a line feed ({@code '\n'}), a carriage return
* ({@code '\r'}), or a carriage return followed immediately by a linefeed
* ({@code "\r\n"}).
*
* @return a {@code String} containing the contents of the line, not
* including any line-termination characters, or {@code null} if the
* end of the stream has been reached.
* @throws IOException if an I/O error occurs
*/
public String readLine() throws IOException {
while (lines.peek() == null) {
cbuf.clear();
// The default implementation of Reader#read(CharBuffer) allocates a
// temporary char[], so we call Reader#read(char[], int, int) instead.
int read = (reader != null)
? reader.read(buf, 0, buf.length)
: readable.read(cbuf);
if (read == -1) {
lineBuf.finish();
break;
}
lineBuf.add(buf, 0, read);
}
return lines.poll();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Longs;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* An implementation of {@link DataOutput} that uses little-endian byte ordering
* for writing {@code char}, {@code short}, {@code int}, {@code float}, {@code
* double}, and {@code long} values.
* <p>
* <b>Note:</b> This class intentionally violates the specification of its
* supertype {@code DataOutput}, which explicitly requires big-endian byte
* order.
*
* @author Chris Nokleberg
* @author Keith Bottner
* @since 8.0
*/
@Beta
public class LittleEndianDataOutputStream extends FilterOutputStream
implements DataOutput {
/**
* Creates a {@code LittleEndianDataOutputStream} that wraps the given stream.
*
* @param out the stream to delegate to
*/
public LittleEndianDataOutputStream(OutputStream out) {
super(new DataOutputStream(Preconditions.checkNotNull(out)));
}
@Override public void write(byte[] b, int off, int len) throws IOException {
// Override slow FilterOutputStream impl
out.write(b, off, len);
}
@Override public void writeBoolean(boolean v) throws IOException {
((DataOutputStream) out).writeBoolean(v);
}
@Override public void writeByte(int v) throws IOException {
((DataOutputStream) out).writeByte(v);
}
/**
* @deprecated The semantics of {@code writeBytes(String s)} are considered
* dangerous. Please use {@link #writeUTF(String s)},
* {@link #writeChars(String s)} or another write method instead.
*/
@Deprecated
@Override public void writeBytes(String s) throws IOException {
((DataOutputStream) out).writeBytes(s);
}
/**
* Writes a char as specified by {@link DataOutputStream#writeChar(int)},
* except using little-endian byte order.
*
* @throws IOException if an I/O error occurs
*/
@Override public void writeChar(int v) throws IOException {
writeShort(v);
}
/**
* Writes a {@code String} as specified by
* {@link DataOutputStream#writeChars(String)}, except each character is
* written using little-endian byte order.
*
* @throws IOException if an I/O error occurs
*/
@Override public void writeChars(String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
writeChar(s.charAt(i));
}
}
/**
* Writes a {@code double} as specified by
* {@link DataOutputStream#writeDouble(double)}, except using little-endian
* byte order.
*
* @throws IOException if an I/O error occurs
*/
@Override public void writeDouble(double v) throws IOException {
writeLong(Double.doubleToLongBits(v));
}
/**
* Writes a {@code float} as specified by
* {@link DataOutputStream#writeFloat(float)}, except using little-endian byte
* order.
*
* @throws IOException if an I/O error occurs
*/
@Override public void writeFloat(float v) throws IOException {
writeInt(Float.floatToIntBits(v));
}
/**
* Writes an {@code int} as specified by
* {@link DataOutputStream#writeInt(int)}, except using little-endian byte
* order.
*
* @throws IOException if an I/O error occurs
*/
@Override public void writeInt(int v) throws IOException {
out.write(0xFF & v);
out.write(0xFF & (v >> 8));
out.write(0xFF & (v >> 16));
out.write(0xFF & (v >> 24));
}
/**
* Writes a {@code long} as specified by
* {@link DataOutputStream#writeLong(long)}, except using little-endian byte
* order.
*
* @throws IOException if an I/O error occurs
*/
@Override public void writeLong(long v) throws IOException {
byte[] bytes = Longs.toByteArray(Long.reverseBytes(v));
write(bytes, 0, bytes.length);
}
/**
* Writes a {@code short} as specified by
* {@link DataOutputStream#writeShort(int)}, except using little-endian byte
* order.
*
* @throws IOException if an I/O error occurs
*/
@Override public void writeShort(int v) throws IOException {
out.write(0xFF & v);
out.write(0xFF & (v >> 8));
}
@Override public void writeUTF(String str) throws IOException {
((DataOutputStream) out).writeUTF(str);
}
}
| Java |
/*
* Copyright (C) 2006 The Guava Authors
*
* 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.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import java.io.File;
import java.io.FilenameFilter;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.annotation.Nullable;
/**
* File name filter that only accepts files matching a regular expression. This class is thread-safe
* and immutable.
*
* @author Apple Chow
* @since 1.0
*/
@Beta
public final class PatternFilenameFilter implements FilenameFilter {
private final Pattern pattern;
/**
* Constructs a pattern file name filter object.
* @param patternStr the pattern string on which to filter file names
*
* @throws PatternSyntaxException if pattern compilation fails (runtime)
*/
public PatternFilenameFilter(String patternStr) {
this(Pattern.compile(patternStr));
}
/**
* Constructs a pattern file name filter object.
* @param pattern the pattern on which to filter file names
*/
public PatternFilenameFilter(Pattern pattern) {
this.pattern = Preconditions.checkNotNull(pattern);
}
@Override public boolean accept(@Nullable File dir, String fileName) {
return pattern.matcher(fileName).matches();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
/**
* Provides utility methods for working with resources in the classpath.
* Note that even though these methods use {@link URL} parameters, they
* are usually not appropriate for HTTP or other non-classpath resources.
*
* <p>All method parameters must be non-null unless documented otherwise.
*
* @author Chris Nokleberg
* @author Ben Yu
* @since 1.0
*/
@Beta
public final class Resources {
private Resources() {}
/**
* Returns a factory that will supply instances of {@link InputStream} that
* read from the given URL.
*
* @param url the URL to read from
* @return the factory
*/
public static InputSupplier<InputStream> newInputStreamSupplier(
final URL url) {
checkNotNull(url);
return new InputSupplier<InputStream>() {
@Override
public InputStream getInput() throws IOException {
return url.openStream();
}
};
}
/**
* Returns a factory that will supply instances of
* {@link InputStreamReader} that read a URL using the given character set.
*
* @param url the URL to read from
* @param charset the character set used when reading the URL contents
* @return the factory
*/
public static InputSupplier<InputStreamReader> newReaderSupplier(
URL url, Charset charset) {
return CharStreams.newReaderSupplier(newInputStreamSupplier(url), charset);
}
/**
* Reads all bytes from a URL into a byte array.
*
* @param url the URL to read from
* @return a byte array containing all the bytes from the URL
* @throws IOException if an I/O error occurs
*/
public static byte[] toByteArray(URL url) throws IOException {
return ByteStreams.toByteArray(newInputStreamSupplier(url));
}
/**
* Reads all characters from a URL into a {@link String}, using the given
* character set.
*
* @param url the URL to read from
* @param charset the character set used when reading the URL
* @return a string containing all the characters from the URL
* @throws IOException if an I/O error occurs.
*/
public static String toString(URL url, Charset charset) throws IOException {
return CharStreams.toString(newReaderSupplier(url, charset));
}
/**
* Streams lines from a URL, stopping when our callback returns false, or we
* have read all of the lines.
*
* @param url the URL to read from
* @param charset the character set used when reading the URL
* @param callback the LineProcessor to use to handle the lines
* @return the output of processing the lines
* @throws IOException if an I/O error occurs
*/
public static <T> T readLines(URL url, Charset charset,
LineProcessor<T> callback) throws IOException {
return CharStreams.readLines(newReaderSupplier(url, charset), callback);
}
/**
* Reads all of the lines from a URL. The lines do not include
* line-termination characters, but do include other leading and trailing
* whitespace.
*
* @param url the URL to read from
* @param charset the character set used when writing the file
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
public static List<String> readLines(URL url, Charset charset)
throws IOException {
return CharStreams.readLines(newReaderSupplier(url, charset));
}
/**
* Copies all bytes from a URL to an output stream.
*
* @param from the URL to read from
* @param to the output stream
* @throws IOException if an I/O error occurs
*/
public static void copy(URL from, OutputStream to) throws IOException {
ByteStreams.copy(newInputStreamSupplier(from), to);
}
/**
* Returns a {@code URL} pointing to {@code resourceName} if the resource is
* found in the class path. {@code Resources.class.getClassLoader()} is used
* to locate the resource.
*
* @throws IllegalArgumentException if resource is not found
*/
public static URL getResource(String resourceName) {
URL url = Resources.class.getClassLoader().getResource(resourceName);
checkArgument(url != null, "resource %s not found.", resourceName);
return url;
}
/**
* Returns a {@code URL} pointing to {@code resourceName} that is relative to
* {@code contextClass}, if the resource is found in the class path.
*
* @throws IllegalArgumentException if resource is not found
*/
public static URL getResource(Class<?> contextClass, String resourceName) {
URL url = contextClass.getResource(resourceName);
checkArgument(url != null, "resource %s relative to %s not found.",
resourceName, contextClass.getName());
return url;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.
*/
/**
* This package contains utility methods and classes for working with Java I/O,
* for example input streams, output streams, readers, writers, and files.
*
* <p>Many of the methods are based on the
* {@link com.google.common.io.InputSupplier} and
* {@link com.google.common.io.OutputSupplier} interfaces. They are used as
* factories for I/O objects that might throw {@link java.io.IOException} when
* being created. The advantage of using a factory is that the helper methods in
* this package can take care of closing the resource properly, even if an
* exception is thrown. The {@link com.google.common.io.ByteStreams},
* {@link com.google.common.io.CharStreams}, and
* {@link com.google.common.io.Files} classes all have static helper methods to
* create new factories and to work with them.
*
* <p>This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*
* @author Chris Nokleberg
*/
@ParametersAreNonnullByDefault
package com.google.common.io;
import javax.annotation.ParametersAreNonnullByDefault;
| Java |
/*
* Copyright (C) 2006 The Guava Authors
*
* 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.google.common.io;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
import java.io.Writer;
/**
* Writer that places all output on an {@link Appendable} target. If the target
* is {@link Flushable} or {@link Closeable}, flush()es and close()s will also
* be delegated to the target.
*
* @author Alan Green
* @author Sebastian Kanthak
* @since 1.0
*/
class AppendableWriter extends Writer {
private final Appendable target;
private boolean closed;
/**
* Creates a new writer that appends everything it writes to {@code target}.
*
* @param target target to which to append output
*/
AppendableWriter(Appendable target) {
this.target = target;
}
/*
* Abstract methods from Writer
*/
@Override public void write(char cbuf[], int off, int len)
throws IOException {
checkNotClosed();
// It turns out that creating a new String is usually as fast, or faster
// than wrapping cbuf in a light-weight CharSequence.
target.append(new String(cbuf, off, len));
}
@Override public void flush() throws IOException {
checkNotClosed();
if (target instanceof Flushable) {
((Flushable) target).flush();
}
}
@Override public void close() throws IOException {
this.closed = true;
if (target instanceof Closeable) {
((Closeable) target).close();
}
}
/*
* Override a few functions for performance reasons to avoid creating
* unnecessary strings.
*/
@Override public void write(int c) throws IOException {
checkNotClosed();
target.append((char) c);
}
@Override public void write(String str) throws IOException {
checkNotClosed();
target.append(str);
}
@Override public void write(String str, int off, int len) throws IOException {
checkNotClosed();
// tricky: append takes start, end pair...
target.append(str, off, off + len);
}
@Override public Writer append(char c) throws IOException {
checkNotClosed();
target.append(c);
return this;
}
@Override public Writer append(CharSequence charSeq) throws IOException {
checkNotClosed();
target.append(charSeq);
return this;
}
@Override public Writer append(CharSequence charSeq, int start, int end)
throws IOException {
checkNotClosed();
target.append(charSeq, start, end);
return this;
}
private void checkNotClosed() throws IOException {
if (closed) {
throw new IOException("Cannot write to a closed writer.");
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import com.google.common.annotations.Beta;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* An OutputStream that counts the number of bytes written.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public final class CountingOutputStream extends FilterOutputStream {
private long count;
/**
* Wraps another output stream, counting the number of bytes written.
*
* @param out the output stream to be wrapped
*/
public CountingOutputStream(OutputStream out) {
super(out);
}
/** Returns the number of bytes written. */
public long getCount() {
return count;
}
@Override public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
count += len;
}
@Override public void write(int b) throws IOException {
out.write(b);
count++;
}
}
| Java |
/*
* Copyright (C) 2004 The Guava Authors
*
* 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.google.common.io;
import com.google.common.annotations.Beta;
import java.io.OutputStream;
/**
* Implementation of {@link OutputStream} that simply discards written bytes.
*
* @author Spencer Kimball
* @since 1.0
*/
@Beta
public final class NullOutputStream extends OutputStream {
/** Discards the specified byte. */
@Override public void write(int b) {
}
/** Discards the specified byte array. */
@Override public void write(byte[] b, int off, int len) {
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import java.io.IOException;
/**
* Package-protected abstract class that implements the line reading
* algorithm used by {@link LineReader}. Line separators are per {@link
* java.io.BufferedReader}: line feed, carriage return, or carriage
* return followed immediately by a linefeed.
*
* <p>Subclasses must implement {@link #handleLine}, call {@link #add}
* to pass character data, and call {@link #finish} at the end of stream.
*
* @author Chris Nokleberg
* @since 1.0
*/
abstract class LineBuffer {
/** Holds partial line contents. */
private StringBuilder line = new StringBuilder();
/** Whether a line ending with a CR is pending processing. */
private boolean sawReturn;
/**
* Process additional characters from the stream. When a line separator
* is found the contents of the line and the line separator itself
* are passed to the abstract {@link #handleLine} method.
*
* @param cbuf the character buffer to process
* @param off the offset into the buffer
* @param len the number of characters to process
* @throws IOException if an I/O error occurs
* @see #finish
*/
protected void add(char[] cbuf, int off, int len) throws IOException {
int pos = off;
if (sawReturn && len > 0) {
// Last call to add ended with a CR; we can handle the line now.
if (finishLine(cbuf[pos] == '\n')) {
pos++;
}
}
int start = pos;
for (int end = off + len; pos < end; pos++) {
switch (cbuf[pos]) {
case '\r':
line.append(cbuf, start, pos - start);
sawReturn = true;
if (pos + 1 < end) {
if (finishLine(cbuf[pos + 1] == '\n')) {
pos++;
}
}
start = pos + 1;
break;
case '\n':
line.append(cbuf, start, pos - start);
finishLine(true);
start = pos + 1;
break;
}
}
line.append(cbuf, start, off + len - start);
}
/** Called when a line is complete. */
private boolean finishLine(boolean sawNewline) throws IOException {
handleLine(line.toString(), sawReturn
? (sawNewline ? "\r\n" : "\r")
: (sawNewline ? "\n" : ""));
line = new StringBuilder();
sawReturn = false;
return sawNewline;
}
/**
* Subclasses must call this method after finishing character processing,
* in order to ensure that any unterminated line in the buffer is
* passed to {@link #handleLine}.
*
* @throws IOException if an I/O error occurs
*/
protected void finish() throws IOException {
if (sawReturn || line.length() > 0) {
finishLine(false);
}
}
/**
* Called for each line found in the character data passed to
* {@link #add}.
*
* @param line a line of text (possibly empty), without any line separators
* @param end the line separator; one of {@code "\r"}, {@code "\n"},
* {@code "\r\n"}, or {@code ""}
* @throws IOException if an I/O error occurs
*/
protected abstract void handleLine(String line, String end)
throws IOException;
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* 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.google.common.io;
import com.google.common.annotations.Beta;
import java.io.IOException;
/**
* A callback interface to process bytes from a stream.
*
* <p>{@link #processBytes} will be called for each line that is read, and
* should return {@code false} when you want to stop processing.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public interface ByteProcessor<T> {
/**
* This method will be called for each chunk of bytes in an
* input stream. The implementation should process the bytes
* from {@code buf[off]} through {@code buf[off + len - 1]}
* (inclusive).
*
* @param buf the byte array containing the data to process
* @param off the initial offset into the array
* @param len the length of data to be processed
* @return true to continue processing, false to stop
*/
boolean processBytes(byte[] buf, int off, int len) throws IOException;
/** Return the result of processing all the bytes. */
T getResult();
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* 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.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* An {@link OutputStream} that starts buffering to a byte array, but
* switches to file buffering once the data reaches a configurable size.
*
* <p>This class is thread-safe.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public final class FileBackedOutputStream extends OutputStream {
private final int fileThreshold;
private final boolean resetOnFinalize;
private final InputSupplier<InputStream> supplier;
private OutputStream out;
private MemoryOutput memory;
private File file;
/** ByteArrayOutputStream that exposes its internals. */
private static class MemoryOutput extends ByteArrayOutputStream {
byte[] getBuffer() {
return buf;
}
int getCount() {
return count;
}
}
/** Returns the file holding the data (possibly null). */
@VisibleForTesting synchronized File getFile() {
return file;
}
/**
* Creates a new instance that uses the given file threshold, and does
* not reset the data when the {@link InputSupplier} returned by
* {@link #getSupplier} is finalized.
*
* @param fileThreshold the number of bytes before the stream should
* switch to buffering to a file
*/
public FileBackedOutputStream(int fileThreshold) {
this(fileThreshold, false);
}
/**
* Creates a new instance that uses the given file threshold, and
* optionally resets the data when the {@link InputSupplier} returned
* by {@link #getSupplier} is finalized.
*
* @param fileThreshold the number of bytes before the stream should
* switch to buffering to a file
* @param resetOnFinalize if true, the {@link #reset} method will
* be called when the {@link InputSupplier} returned by {@link
* #getSupplier} is finalized
*/
public FileBackedOutputStream(int fileThreshold, boolean resetOnFinalize) {
this.fileThreshold = fileThreshold;
this.resetOnFinalize = resetOnFinalize;
memory = new MemoryOutput();
out = memory;
if (resetOnFinalize) {
supplier = new InputSupplier<InputStream>() {
@Override
public InputStream getInput() throws IOException {
return openStream();
}
@Override protected void finalize() {
try {
reset();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
};
} else {
supplier = new InputSupplier<InputStream>() {
@Override
public InputStream getInput() throws IOException {
return openStream();
}
};
}
}
/**
* Returns a supplier that may be used to retrieve the data buffered
* by this stream.
*/
public InputSupplier<InputStream> getSupplier() {
return supplier;
}
private synchronized InputStream openStream() throws IOException {
if (file != null) {
return new FileInputStream(file);
} else {
return new ByteArrayInputStream(
memory.getBuffer(), 0, memory.getCount());
}
}
/**
* Calls {@link #close} if not already closed, and then resets this
* object back to its initial state, for reuse. If data was buffered
* to a file, it will be deleted.
*
* @throws IOException if an I/O error occurred while deleting the file buffer
*/
public synchronized void reset() throws IOException {
try {
close();
} finally {
if (memory == null) {
memory = new MemoryOutput();
} else {
memory.reset();
}
out = memory;
if (file != null) {
File deleteMe = file;
file = null;
if (!deleteMe.delete()) {
throw new IOException("Could not delete: " + deleteMe);
}
}
}
}
@Override public synchronized void write(int b) throws IOException {
update(1);
out.write(b);
}
@Override public synchronized void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override public synchronized void write(byte[] b, int off, int len)
throws IOException {
update(len);
out.write(b, off, len);
}
@Override public synchronized void close() throws IOException {
out.close();
}
@Override public synchronized void flush() throws IOException {
out.flush();
}
/**
* Checks if writing {@code len} bytes would go over threshold, and
* switches to file buffering if so.
*/
private void update(int len) throws IOException {
if (file == null && (memory.getCount() + len > fileThreshold)) {
File temp = File.createTempFile("FileBackedOutputStream", null);
if (resetOnFinalize) {
// Finalizers are not guaranteed to be called on system shutdown;
// this is insurance.
temp.deleteOnExit();
}
FileOutputStream transfer = new FileOutputStream(temp);
transfer.write(memory.getBuffer(), 0, memory.getCount());
transfer.flush();
// We've successfully transferred the data; switch to writing to file
out = transfer;
file = temp;
memory = null;
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import java.io.IOException;
/**
* A factory for writable streams of bytes or characters.
*
* @author Chris Nokleberg
* @since 1.0
*/
public interface OutputSupplier<T> {
/**
* Returns an object that encapsulates a writable resource.
* <p>
* Like {@link Iterable#iterator}, this method may be called repeatedly to
* get independent channels to the same underlying resource.
* <p>
* Where the channel maintains a position within the resource, moving that
* cursor within one channel should not affect the starting position of
* channels returned by other calls.
*/
T getOutput() throws IOException;
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* 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.google.common.io;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
/**
* A {@link Reader} that concatenates multiple readers.
*
* @author Bin Zhu
* @since 1.0
*/
class MultiReader extends Reader {
private final Iterator<? extends InputSupplier<? extends Reader>> it;
private Reader current;
MultiReader(Iterator<? extends InputSupplier<? extends Reader>> readers)
throws IOException {
this.it = readers;
advance();
}
/**
* Closes the current reader and opens the next one, if any.
*/
private void advance() throws IOException {
close();
if (it.hasNext()) {
current = it.next().getInput();
}
}
@Override public int read(char cbuf[], int off, int len) throws IOException {
if (current == null) {
return -1;
}
int result = current.read(cbuf, off, len);
if (result == -1) {
advance();
return read(cbuf, off, len);
}
return result;
}
@Override public long skip(long n) throws IOException {
Preconditions.checkArgument(n >= 0, "n is negative");
if (n > 0) {
while (current != null) {
long result = current.skip(n);
if (result > 0) {
return result;
}
advance();
}
}
return 0;
}
@Override public boolean ready() throws IOException {
return (current != null) && current.ready();
}
@Override public void close() throws IOException {
if (current != null) {
try {
current.close();
} finally {
current = null;
}
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* 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.google.common.io;
import com.google.common.annotations.Beta;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* An {@link InputStream} that counts the number of bytes read.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public final class CountingInputStream extends FilterInputStream {
private long count;
private long mark = -1;
/**
* Wraps another input stream, counting the number of bytes read.
*
* @param in the input stream to be wrapped
*/
public CountingInputStream(InputStream in) {
super(in);
}
/** Returns the number of bytes read. */
public long getCount() {
return count;
}
@Override public int read() throws IOException {
int result = in.read();
if (result != -1) {
count++;
}
return result;
}
@Override public int read(byte[] b, int off, int len) throws IOException {
int result = in.read(b, off, len);
if (result != -1) {
count += result;
}
return result;
}
@Override public long skip(long n) throws IOException {
long result = in.skip(n);
count += result;
return result;
}
@Override public synchronized void mark(int readlimit) {
in.mark(readlimit);
mark = count;
// it's okay to mark even if mark isn't supported, as reset won't work
}
@Override public synchronized void reset() throws IOException {
if (!in.markSupported()) {
throw new IOException("Mark not supported");
}
if (mark == -1) {
throw new IOException("Mark not set");
}
in.reset();
count = mark;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.