code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* 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;
/**
* {@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) 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) 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 |
/*
* 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.util.concurrent.MoreExecutors.invokeAnyImpl;
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.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;
}
@Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException {
try {
return invokeAnyImpl(this, 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 invokeAnyImpl(this, 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) 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) 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 com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
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
@GwtCompatible
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) 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) 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) 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 |
/*
* 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) 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.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();
}
};
/**
* Constructor for use by subclasses.
*/
protected AbstractExecutionThreadService() {}
/**
* Start the service. This method is invoked on the execution thread.
*
* <p>By default this method does nothing.
*/
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.
*
* <p>By default this method does nothing.
*/
// TODO: consider supporting a TearDownTestCase-like API
protected void shutDown() throws Exception {}
/**
* Invoked to request the service to stop.
*
* <p>By default this method does nothing.
*/
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();
}
@Override public final void addListener(Listener listener, Executor executor) {
delegate.addListener(listener, executor);
}
/**
* 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) 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) 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. However, it may also wrap a checked exception in some
* cases.
*
* <p>When wrapping an {@code Error} from another thread, prefer {@link
* ExecutionError}. When wrapping a checked exception, prefer {@code
* ExecutionException}.
*
* @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) 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;
/**
* 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();
}
@Override public final void addListener(Listener listener, Executor executor) {
delegate.addListener(listener, executor);
}
private String getServiceName() {
return getClass().getSimpleName();
}
}
| 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) 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.annotations.Beta;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
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
* {@link CustomScheduler}.
*
* @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.
*
* <p>By default this method does nothing.
*/
protected void startUp() throws Exception {}
/**
* Stop the service. This is guaranteed not to run concurrently with {@link #runOneIteration}.
*
* <p>By default this method does nothing.
*/
protected 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. If this method is overridden the
* executor will not be {@linkplain ScheduledExecutorService#shutdown shutdown} when this
* service {@linkplain Service.State#TERMINATED terminates} or
* {@linkplain Service.State#TERMINATED fails}. Subclasses may override this method to supply a
* custom {@link ScheduledExecutorService} instance. This method is guaranteed to only be called
* once.
*
* <p>By default this returns a new {@link ScheduledExecutorService} with a single thread thread
* pool that will be shut down when the service {@linkplain Service.State#TERMINATED terminates}
* or {@linkplain Service.State#TERMINATED fails}.
*/
protected ScheduledExecutorService executor() {
final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
// Add a listener to shutdown the executor after the service is stopped. This ensures that the
// JVM shutdown will not be prevented from exiting after this service has stopped or failed.
// Technically this listener is added after start() was called so it is a little gross, but it
// is called within doStart() so we know that the service cannot terminate or fail concurrently
// with adding this listener so it is impossible to miss an event that we are interested in.
addListener(new Listener() {
@Override public void starting() {}
@Override public void running() {}
@Override public void stopping(State from) {}
@Override public void terminated(State from) {
executor.shutdown();
}
@Override public void failed(State from, Throwable failure) {
executor.shutdown();
}}, MoreExecutors.sameThreadExecutor());
return executor;
}
@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();
}
@Override public final void addListener(Listener listener, Executor executor) {
delegate.addListener(listener, executor);
}
/**
* 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) 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) 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.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;
/**
* The {@code CycleDetectingLockFactory} creates {@link ReentrantLock}s and
* {@link ReentrantReadWriteLock}s that detect potential deadlock by checking
* for cycles in lock acquisition order.
* <p>
* Potential deadlocks detected when calling the {@code lock()},
* {@code lockInterruptibly()}, or {@code tryLock()} methods will result in the
* execution of the {@link Policy} specified when creating the factory. The
* currently available policies are:
* <ul>
* <li>DISABLED
* <li>WARN
* <li>THROW
* </ul>
* The locks created by a factory instance will detect lock acquisition cycles
* with locks created by other {@code CycleDetectingLockFactory} instances
* (except those with {@code Policy.DISABLED}). A lock's behavior when a cycle
* is detected, however, is defined by the {@code Policy} of the factory that
* created it. This allows detection of cycles across components while
* delegating control over lock behavior to individual components.
* <p>
* Applications are encouraged to use a {@code CycleDetectingLockFactory} to
* create any locks for which external/unmanaged code is executed while the lock
* is held. (See caveats under <strong>Performance</strong>).
* <p>
* <strong>Cycle Detection</strong>
* <p>
* Deadlocks can arise when locks are acquired in an order that forms a cycle.
* In a simple example involving two locks and two threads, deadlock occurs
* when one thread acquires Lock A, and then Lock B, while another thread
* acquires Lock B, and then Lock A:
* <pre>
* Thread1: acquire(LockA) --X acquire(LockB)
* Thread2: acquire(LockB) --X acquire(LockA)
* </pre>
* Neither thread will progress because each is waiting for the other. In more
* complex applications, cycles can arise from interactions among more than 2
* locks:
* <pre>
* Thread1: acquire(LockA) --X acquire(LockB)
* Thread2: acquire(LockB) --X acquire(LockC)
* ...
* ThreadN: acquire(LockN) --X acquire(LockA)
* </pre>
* The implementation detects cycles by constructing a directed graph in which
* each lock represents a node and each edge represents an acquisition ordering
* between two locks.
* <ul>
* <li>Each lock adds (and removes) itself to/from a ThreadLocal Set of acquired
* locks when the Thread acquires its first hold (and releases its last
* remaining hold).
* <li>Before the lock is acquired, the lock is checked against the current set
* of acquired locks---to each of the acquired locks, an edge from the
* soon-to-be-acquired lock is either verified or created.
* <li>If a new edge needs to be created, the outgoing edges of the acquired
* locks are traversed to check for a cycle that reaches the lock to be
* acquired. If no cycle is detected, a new "safe" edge is created.
* <li>If a cycle is detected, an "unsafe" (cyclic) edge is created to represent
* a potential deadlock situation, and the appropriate Policy is executed.
* </ul>
* Note that detection of potential deadlock does not necessarily indicate that
* deadlock will happen, as it is possible that higher level application logic
* prevents the cyclic lock acquisition from occurring. One example of a false
* positive is:
* <pre>
* LockA -> LockB -> LockC
* LockA -> LockC -> LockB
* </pre>
*
* <strong>ReadWriteLocks</strong>
* <p>
* While {@code ReadWriteLock}s have different properties and can form cycles
* without potential deadlock, this class treats {@code ReadWriteLock}s as
* equivalent to traditional exclusive locks. Although this increases the false
* positives that the locks detect (i.e. cycles that will not actually result in
* deadlock), it simplifies the algorithm and implementation considerably. The
* assumption is that a user of this factory wishes to eliminate any cyclic
* acquisition ordering.
* <p>
* <strong>Explicit Lock Acquisition Ordering</strong>
* <p>
* The {@link CycleDetectingLockFactory.WithExplicitOrdering} class can be used
* to enforce an application-specific ordering in addition to performing general
* cycle detection.
* <p>
* <strong>Garbage Collection</strong>
* <p>
* In order to allow proper garbage collection of unused locks, the edges of
* the lock graph are weak references.
* <p>
* <strong>Performance</strong>
* <p>
* The extra bookkeeping done by cycle detecting locks comes at some cost to
* performance. Benchmarks (as of December 2011) show that:
*
* <ul>
* <li>for an unnested {@code lock()} and {@code unlock()}, a cycle detecting
* lock takes 38ns as opposed to the 24ns taken by a plain lock.
* <li>for nested locking, the cost increases with the depth of the nesting:
* <ul>
* <li> 2 levels: average of 64ns per lock()/unlock()
* <li> 3 levels: average of 77ns per lock()/unlock()
* <li> 4 levels: average of 99ns per lock()/unlock()
* <li> 5 levels: average of 103ns per lock()/unlock()
* <li>10 levels: average of 184ns per lock()/unlock()
* <li>20 levels: average of 393ns per lock()/unlock()
* </ul>
* </ul>
*
* As such, the CycleDetectingLockFactory may not be suitable for
* performance-critical applications which involve tightly-looped or
* deeply-nested locking algorithms.
*
* @author Darick Tong
* @since 13.0
*/
@Beta
@ThreadSafe
public class CycleDetectingLockFactory {
/**
* Encapsulates the action to be taken when a potential deadlock is
* encountered. Clients can use one of the predefined {@link Policies} or
* specify a custom implementation. Implementations must be thread-safe.
*
* @since 13.0
*/
@Beta
@ThreadSafe
public interface Policy {
/**
* Called when a potential deadlock is encountered. Implementations can
* throw the given {@code exception} and/or execute other desired logic.
* <p>
* Note that the method will be called even upon an invocation of
* {@code tryLock()}. Although {@code tryLock()} technically recovers from
* deadlock by eventually timing out, this behavior is chosen based on the
* assumption that it is the application's wish to prohibit any cyclical
* lock acquisitions.
*/
void handlePotentialDeadlock(PotentialDeadlockException exception);
}
/**
* Pre-defined {@link Policy} implementations.
*
* @since 13.0
*/
@Beta
public enum Policies implements Policy {
/**
* When potential deadlock is detected, this policy results in the throwing
* of the {@code PotentialDeadlockException} indicating the potential
* deadlock, which includes stack traces illustrating the cycle in lock
* acquisition order.
*/
THROW {
@Override
public void handlePotentialDeadlock(PotentialDeadlockException e) {
throw e;
}
},
/**
* When potential deadlock is detected, this policy results in the logging
* of a {@link Level#SEVERE} message indicating the potential deadlock,
* which includes stack traces illustrating the cycle in lock acquisition
* order.
*/
WARN {
@Override
public void handlePotentialDeadlock(PotentialDeadlockException e) {
logger.log(Level.SEVERE, "Detected potential deadlock", e);
}
},
/**
* Disables cycle detection. This option causes the factory to return
* unmodified lock implementations provided by the JDK, and is provided to
* allow applications to easily parameterize when cycle detection is
* enabled.
* <p>
* Note that locks created by a factory with this policy will <em>not</em>
* participate the cycle detection performed by locks created by other
* factories.
*/
DISABLED {
@Override
public void handlePotentialDeadlock(PotentialDeadlockException e) {
}
};
}
/**
* Creates a new factory with the specified policy.
*/
public static CycleDetectingLockFactory newInstance(Policy policy) {
return new CycleDetectingLockFactory(policy);
}
/**
* Equivalent to {@code newReentrantLock(lockName, false)}.
*/
public ReentrantLock newReentrantLock(String lockName) {
return newReentrantLock(lockName, false);
}
/**
* Creates a {@link ReentrantLock} with the given fairness policy. The
* {@code lockName} is used in the warning or exception output to help
* identify the locks involved in the detected deadlock.
*/
public ReentrantLock newReentrantLock(String lockName, boolean fair) {
return policy == Policies.DISABLED ? new ReentrantLock(fair)
: new CycleDetectingReentrantLock(
new LockGraphNode(lockName), fair);
}
/**
* Equivalent to {@code newReentrantReadWriteLock(lockName, false)}.
*/
public ReentrantReadWriteLock newReentrantReadWriteLock(String lockName) {
return newReentrantReadWriteLock(lockName, false);
}
/**
* Creates a {@link ReentrantReadWriteLock} with the given fairness policy.
* The {@code lockName} is used in the warning or exception output to help
* identify the locks involved in the detected deadlock.
*/
public ReentrantReadWriteLock newReentrantReadWriteLock(
String lockName, boolean fair) {
return policy == Policies.DISABLED ? new ReentrantReadWriteLock(fair)
: new CycleDetectingReentrantReadWriteLock(
new LockGraphNode(lockName), fair);
}
// A static mapping from an Enum type to its set of LockGraphNodes.
private static final Map<Class<? extends Enum>,
Map<? extends Enum, LockGraphNode>> lockGraphNodesPerType =
new MapMaker().weakKeys().makeComputingMap(
new OrderedLockGraphNodesCreator());
/**
* Creates a {@code CycleDetectingLockFactory.WithExplicitOrdering<E>}.
*/
public static <E extends Enum<E>> WithExplicitOrdering<E>
newInstanceWithExplicitOrdering(Class<E> enumClass, Policy policy) {
// OrderedLockGraphNodesCreator maps each enumClass to a Map with the
// corresponding enum key type.
@SuppressWarnings("unchecked")
Map<E, LockGraphNode> lockGraphNodes =
(Map<E, LockGraphNode>) lockGraphNodesPerType.get(enumClass);
return new WithExplicitOrdering<E>(policy, lockGraphNodes);
}
/**
* A {@code CycleDetectingLockFactory.WithExplicitOrdering} provides the
* additional enforcement of an application-specified ordering of lock
* acquisitions. The application defines the allowed ordering with an
* {@code Enum} whose values each correspond to a lock type. The order in
* which the values are declared dictates the allowed order of lock
* acquisition. In other words, locks corresponding to smaller values of
* {@link Enum#ordinal()} should only be acquired before locks with larger
* ordinals. Example:
*
* <pre> {@code
* enum MyLockOrder {
* FIRST, SECOND, THIRD;
* }
*
* CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory =
* CycleDetectingLockFactory.newInstanceWithExplicitOrdering(Policies.THROW);
*
* Lock lock1 = factory.newReentrantLock(MyLockOrder.FIRST);
* Lock lock2 = factory.newReentrantLock(MyLockOrder.SECOND);
* Lock lock3 = factory.newReentrantLock(MyLockOrder.THIRD);
*
* lock1.lock();
* lock3.lock();
* lock2.lock(); // will throw an IllegalStateException
* }</pre>
*
* As with all locks created by instances of {@code CycleDetectingLockFactory}
* explicitly ordered locks participate in general cycle detection with all
* other cycle detecting locks, and a lock's behavior when detecting a cyclic
* lock acquisition is defined by the {@code Policy} of the factory that
* created it.
* <p>
* Note, however, that although multiple locks can be created for a given Enum
* value, whether it be through separate factory instances or through multiple
* calls to the same factory, attempting to acquire multiple locks with the
* same Enum value (within the same thread) will result in an
* IllegalStateException regardless of the factory's policy. For example:
*
* <pre> {@code
* CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory1 =
* CycleDetectingLockFactory.newInstanceWithExplicitOrdering(...);
* CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory2 =
* CycleDetectingLockFactory.newInstanceWithExplicitOrdering(...);
*
* Lock lockA = factory1.newReentrantLock(MyLockOrder.FIRST);
* Lock lockB = factory1.newReentrantLock(MyLockOrder.FIRST);
* Lock lockC = factory2.newReentrantLock(MyLockOrder.FIRST);
*
* lockA.lock();
*
* lockB.lock(); // will throw an IllegalStateException
* lockC.lock(); // will throw an IllegalStateException
*
* lockA.lock(); // reentrant acquisition is okay
* }</pre>
*
* It is the responsibility of the application to ensure that multiple lock
* instances with the same rank are never acquired in the same thread.
*
* @param <E> The Enum type representing the explicit lock ordering.
* @since 13.0
*/
@Beta
public static final class WithExplicitOrdering<E extends Enum<E>>
extends CycleDetectingLockFactory {
private final Map<E, LockGraphNode> lockGraphNodes;
@VisibleForTesting
WithExplicitOrdering(
Policy policy, Map<E, LockGraphNode> lockGraphNodes) {
super(policy);
this.lockGraphNodes = lockGraphNodes;
}
/**
* Equivalent to {@code newReentrantLock(rank, false)}.
*/
public ReentrantLock newReentrantLock(E rank) {
return newReentrantLock(rank, false);
}
/**
* Creates a {@link ReentrantLock} with the given fairness policy and rank.
* The values returned by {@link Enum#getDeclaringClass()} and
* {@link Enum#name()} are used to describe the lock in warning or
* exception output.
*
* @throws IllegalStateException If the factory has already created a
* {@code Lock} with the specified rank.
*/
public ReentrantLock newReentrantLock(E rank, boolean fair) {
return policy == Policies.DISABLED ? new ReentrantLock(fair)
: new CycleDetectingReentrantLock(lockGraphNodes.get(rank), fair);
}
/**
* Equivalent to {@code newReentrantReadWriteLock(rank, false)}.
*/
public ReentrantReadWriteLock newReentrantReadWriteLock(E rank) {
return newReentrantReadWriteLock(rank, false);
}
/**
* Creates a {@link ReentrantReadWriteLock} with the given fairness policy
* and rank. The values returned by {@link Enum#getDeclaringClass()} and
* {@link Enum#name()} are used to describe the lock in warning or exception
* output.
*
* @throws IllegalStateException If the factory has already created a
* {@code Lock} with the specified rank.
*/
public ReentrantReadWriteLock newReentrantReadWriteLock(
E rank, boolean fair) {
return policy == Policies.DISABLED ? new ReentrantReadWriteLock(fair)
: new CycleDetectingReentrantReadWriteLock(
lockGraphNodes.get(rank), fair);
}
}
/**
* For a given Enum type, creates an immutable map from each of the Enum's
* values to a corresponding LockGraphNode, with the
* {@code allowedPriorLocks} and {@code disallowedPriorLocks} prepopulated
* with nodes according to the natural ordering of the associated Enum values.
*/
@VisibleForTesting
static class OrderedLockGraphNodesCreator
implements Function<Class<? extends Enum>,
Map<? extends Enum, LockGraphNode>> {
@Override
@SuppressWarnings("unchecked") // There's no way to properly express with
// wildcards the recursive Enum type required by createNodesFor(), and the
// Map/Function types must use wildcards since they accept any Enum class.
public Map<? extends Enum, LockGraphNode> apply(
Class<? extends Enum> clazz) {
return createNodesFor(clazz);
}
<E extends Enum<E>> Map<E, LockGraphNode> createNodesFor(Class<E> clazz) {
EnumMap<E, LockGraphNode> map = Maps.newEnumMap(clazz);
E[] keys = clazz.getEnumConstants();
final int numKeys = keys.length;
ArrayList<LockGraphNode> nodes =
Lists.newArrayListWithCapacity(numKeys);
// Create a LockGraphNode for each enum value.
for (E key : keys) {
LockGraphNode node = new LockGraphNode(getLockName(key));
nodes.add(node);
map.put(key, node);
}
// Pre-populate all allowedPriorLocks with nodes of smaller ordinal.
for (int i = 1; i < numKeys; i++) {
nodes.get(i).checkAcquiredLocks(Policies.THROW, nodes.subList(0, i));
}
// Pre-populate all disallowedPriorLocks with nodes of larger ordinal.
for (int i = 0; i < numKeys - 1; i++) {
nodes.get(i).checkAcquiredLocks(
Policies.DISABLED, nodes.subList(i + 1, numKeys));
}
return Collections.unmodifiableMap(map);
}
/**
* For the given Enum value {@code rank}, returns the value's
* {@code "EnumClass.name"}, which is used in exception and warning
* output.
*/
private String getLockName(Enum<?> rank) {
return rank.getDeclaringClass().getSimpleName() + "." + rank.name();
}
}
//////// Implementation /////////
private static final Logger logger = Logger.getLogger(
CycleDetectingLockFactory.class.getName());
final Policy policy;
private CycleDetectingLockFactory(Policy policy) {
this.policy = policy;
}
/**
* Tracks the currently acquired locks for each Thread, kept up to date by
* calls to {@link #aboutToAcquire(CycleDetectingLock)} and
* {@link #lockStateChanged(CycleDetectingLock)}.
*/
// This is logically a Set, but an ArrayList is used to minimize the amount
// of allocation done on lock()/unlock().
private static final ThreadLocal<ArrayList<LockGraphNode>>
acquiredLocks = new ThreadLocal<ArrayList<LockGraphNode>>() {
@Override
protected ArrayList<LockGraphNode> initialValue() {
return Lists.<LockGraphNode>newArrayListWithCapacity(3);
}
};
/**
* A Throwable used to record a stack trace that illustrates an example of
* a specific lock acquisition ordering. The top of the stack trace is
* truncated such that it starts with the acquisition of the lock in
* question, e.g.
*
* <pre>
* com...ExampleStackTrace: LockB -> LockC
* at com...CycleDetectingReentrantLock.lock(CycleDetectingLockFactory.java:443)
* at ...
* at ...
* at com...MyClass.someMethodThatAcquiresLockB(MyClass.java:123)
* </pre>
*/
private static class ExampleStackTrace extends IllegalStateException {
static final StackTraceElement[] EMPTY_STACK_TRACE =
new StackTraceElement[0];
static Set<String> EXCLUDED_CLASS_NAMES = ImmutableSet.of(
CycleDetectingLockFactory.class.getName(),
ExampleStackTrace.class.getName(),
LockGraphNode.class.getName());
ExampleStackTrace(LockGraphNode node1, LockGraphNode node2) {
super(node1.getLockName() + " -> " + node2.getLockName());
StackTraceElement[] origStackTrace = getStackTrace();
for (int i = 0, n = origStackTrace.length; i < n; i++) {
if (WithExplicitOrdering.class.getName().equals(
origStackTrace[i].getClassName())) {
// For pre-populated disallowedPriorLocks edges, omit the stack trace.
setStackTrace(EMPTY_STACK_TRACE);
break;
}
if (!EXCLUDED_CLASS_NAMES.contains(origStackTrace[i].getClassName())) {
setStackTrace(Arrays.copyOfRange(origStackTrace, i, n));
break;
}
}
}
}
/**
* Represents a detected cycle in lock acquisition ordering. The exception
* includes a causal chain of {@code ExampleStackTrace}s to illustrate the
* cycle, e.g.
*
* <pre>
* com....PotentialDeadlockException: Potential Deadlock from LockC -> ReadWriteA
* at ...
* at ...
* Caused by: com...ExampleStackTrace: LockB -> LockC
* at ...
* at ...
* Caused by: com...ExampleStackTrace: ReadWriteA -> LockB
* at ...
* at ...
* </pre>
*
* Instances are logged for the {@code Policies.WARN}, and thrown for
* {@code Policies.THROW}.
*
* @since 13.0
*/
@Beta
public static final class PotentialDeadlockException
extends ExampleStackTrace {
private final ExampleStackTrace conflictingStackTrace;
private PotentialDeadlockException(
LockGraphNode node1,
LockGraphNode node2,
ExampleStackTrace conflictingStackTrace) {
super(node1, node2);
this.conflictingStackTrace = conflictingStackTrace;
initCause(conflictingStackTrace);
}
public ExampleStackTrace getConflictingStackTrace() {
return conflictingStackTrace;
}
/**
* Appends the chain of messages from the {@code conflictingStackTrace} to
* the original {@code message}.
*/
@Override
public String getMessage() {
StringBuilder message = new StringBuilder(super.getMessage());
for (Throwable t = conflictingStackTrace; t != null; t = t.getCause()) {
message.append(", ").append(t.getMessage());
}
return message.toString();
}
}
/**
* Internal Lock implementations implement the {@code CycleDetectingLock}
* interface, allowing the detection logic to treat all locks in the same
* manner.
*/
private interface CycleDetectingLock {
/** @return the {@link LockGraphNode} associated with this lock. */
LockGraphNode getLockGraphNode();
/** @return {@code true} if the current thread has acquired this lock. */
boolean isAcquiredByCurrentThread();
}
/**
* A {@code LockGraphNode} associated with each lock instance keeps track of
* the directed edges in the lock acquisition graph.
*/
private static class LockGraphNode {
/**
* The map tracking the locks that are known to be acquired before this
* lock, each associated with an example stack trace. Locks are weakly keyed
* to allow proper garbage collection when they are no longer referenced.
*/
final Map<LockGraphNode, ExampleStackTrace> allowedPriorLocks =
new MapMaker().weakKeys().makeMap();
/**
* The map tracking lock nodes that can cause a lock acquisition cycle if
* acquired before this node.
*/
final Map<LockGraphNode, PotentialDeadlockException>
disallowedPriorLocks = new MapMaker().weakKeys().makeMap();
final String lockName;
LockGraphNode(String lockName) {
this.lockName = Preconditions.checkNotNull(lockName);
}
String getLockName() {
return lockName;
}
void checkAcquiredLocks(
Policy policy, List<LockGraphNode> acquiredLocks) {
for (int i = 0, size = acquiredLocks.size(); i < size; i++) {
checkAcquiredLock(policy, acquiredLocks.get(i));
}
}
/**
* Checks the acquisition-ordering between {@code this}, which is about to
* be acquired, and the specified {@code acquiredLock}.
* <p>
* When this method returns, the {@code acquiredLock} should be in either
* the {@code preAcquireLocks} map, for the case in which it is safe to
* acquire {@code this} after the {@code acquiredLock}, or in the
* {@code disallowedPriorLocks} map, in which case it is not safe.
*/
void checkAcquiredLock(Policy policy, LockGraphNode acquiredLock) {
// checkAcquiredLock() should never be invoked by a lock that has already
// been acquired. For unordered locks, aboutToAcquire() ensures this by
// checking isAcquiredByCurrentThread(). For ordered locks, however, this
// can happen because multiple locks may share the same LockGraphNode. In
// this situation, throw an IllegalStateException as defined by contract
// described in the documentation of WithExplicitOrdering.
Preconditions.checkState(
this != acquiredLock,
"Attempted to acquire multiple locks with the same rank " +
acquiredLock.getLockName());
if (allowedPriorLocks.containsKey(acquiredLock)) {
// The acquisition ordering from "acquiredLock" to "this" has already
// been verified as safe. In a properly written application, this is
// the common case.
return;
}
PotentialDeadlockException previousDeadlockException =
disallowedPriorLocks.get(acquiredLock);
if (previousDeadlockException != null) {
// Previously determined to be an unsafe lock acquisition.
// Create a new PotentialDeadlockException with the same causal chain
// (the example cycle) as that of the cached exception.
PotentialDeadlockException exception = new PotentialDeadlockException(
acquiredLock, this,
previousDeadlockException.getConflictingStackTrace());
policy.handlePotentialDeadlock(exception);
return;
}
// Otherwise, it's the first time seeing this lock relationship. Look for
// a path from the acquiredLock to this.
Set<LockGraphNode> seen = Sets.newIdentityHashSet();
ExampleStackTrace path = acquiredLock.findPathTo(this, seen);
if (path == null) {
// this can be safely acquired after the acquiredLock.
//
// Note that there is a race condition here which can result in missing
// a cyclic edge: it's possible for two threads to simultaneous find
// "safe" edges which together form a cycle. Preventing this race
// condition efficiently without _introducing_ deadlock is probably
// tricky. For now, just accept the race condition---missing a warning
// now and then is still better than having no deadlock detection.
allowedPriorLocks.put(
acquiredLock, new ExampleStackTrace(acquiredLock, this));
} else {
// Unsafe acquisition order detected. Create and cache a
// PotentialDeadlockException.
PotentialDeadlockException exception =
new PotentialDeadlockException(acquiredLock, this, path);
disallowedPriorLocks.put(acquiredLock, exception);
policy.handlePotentialDeadlock(exception);
}
}
/**
* Performs a depth-first traversal of the graph edges defined by each
* node's {@code allowedPriorLocks} to find a path between {@code this} and
* the specified {@code lock}.
*
* @return If a path was found, a chained {@link ExampleStackTrace}
* illustrating the path to the {@code lock}, or {@code null} if no path
* was found.
*/
@Nullable
private ExampleStackTrace findPathTo(
LockGraphNode node, Set<LockGraphNode> seen) {
if (!seen.add(this)) {
return null; // Already traversed this node.
}
ExampleStackTrace found = allowedPriorLocks.get(node);
if (found != null) {
return found; // Found a path ending at the node!
}
// Recurse the edges.
for (Map.Entry<LockGraphNode, ExampleStackTrace> entry :
allowedPriorLocks.entrySet()) {
LockGraphNode preAcquiredLock = entry.getKey();
found = preAcquiredLock.findPathTo(node, seen);
if (found != null) {
// One of this node's allowedPriorLocks found a path. Prepend an
// ExampleStackTrace(preAcquiredLock, this) to the returned chain of
// ExampleStackTraces.
ExampleStackTrace path =
new ExampleStackTrace(preAcquiredLock, this);
path.setStackTrace(entry.getValue().getStackTrace());
path.initCause(found);
return path;
}
}
return null;
}
}
/**
* CycleDetectingLock implementations must call this method before attempting
* to acquire the lock.
*/
private void aboutToAcquire(CycleDetectingLock lock) {
if (!lock.isAcquiredByCurrentThread()) {
ArrayList<LockGraphNode> acquiredLockList = acquiredLocks.get();
LockGraphNode node = lock.getLockGraphNode();
node.checkAcquiredLocks(policy, acquiredLockList);
acquiredLockList.add(node);
}
}
/**
* CycleDetectingLock implementations must call this method in a
* {@code finally} clause after any attempt to change the lock state,
* including both lock and unlock attempts. Failure to do so can result in
* corrupting the acquireLocks set.
*/
private void lockStateChanged(CycleDetectingLock lock) {
if (!lock.isAcquiredByCurrentThread()) {
ArrayList<LockGraphNode> acquiredLockList = acquiredLocks.get();
LockGraphNode node = lock.getLockGraphNode();
// Iterate in reverse because locks are usually locked/unlocked in a
// LIFO order.
for (int i = acquiredLockList.size() - 1; i >=0; i--) {
if (acquiredLockList.get(i) == node) {
acquiredLockList.remove(i);
break;
}
}
}
}
final class CycleDetectingReentrantLock
extends ReentrantLock implements CycleDetectingLock {
private final LockGraphNode lockGraphNode;
private CycleDetectingReentrantLock(
LockGraphNode lockGraphNode, boolean fair) {
super(fair);
this.lockGraphNode = Preconditions.checkNotNull(lockGraphNode);
}
///// CycleDetectingLock methods. /////
@Override
public LockGraphNode getLockGraphNode() {
return lockGraphNode;
}
@Override
public boolean isAcquiredByCurrentThread() {
return isHeldByCurrentThread();
}
///// Overridden ReentrantLock methods. /////
@Override
public void lock() {
aboutToAcquire(this);
try {
super.lock();
} finally {
lockStateChanged(this);
}
}
@Override
public void lockInterruptibly() throws InterruptedException {
aboutToAcquire(this);
try {
super.lockInterruptibly();
} finally {
lockStateChanged(this);
}
}
@Override
public boolean tryLock() {
aboutToAcquire(this);
try {
return super.tryLock();
} finally {
lockStateChanged(this);
}
}
@Override
public boolean tryLock(long timeout, TimeUnit unit)
throws InterruptedException {
aboutToAcquire(this);
try {
return super.tryLock(timeout, unit);
} finally {
lockStateChanged(this);
}
}
@Override
public void unlock() {
try {
super.unlock();
} finally {
lockStateChanged(this);
}
}
}
final class CycleDetectingReentrantReadWriteLock
extends ReentrantReadWriteLock implements CycleDetectingLock {
// These ReadLock/WriteLock implementations shadow those in the
// ReentrantReadWriteLock superclass. They are simply wrappers around the
// internal Sync object, so this is safe since the shadowed locks are never
// exposed or used.
private final CycleDetectingReentrantReadLock readLock;
private final CycleDetectingReentrantWriteLock writeLock;
private final LockGraphNode lockGraphNode;
private CycleDetectingReentrantReadWriteLock(
LockGraphNode lockGraphNode, boolean fair) {
super(fair);
this.readLock = new CycleDetectingReentrantReadLock(this);
this.writeLock = new CycleDetectingReentrantWriteLock(this);
this.lockGraphNode = Preconditions.checkNotNull(lockGraphNode);
}
///// Overridden ReentrantReadWriteLock methods. /////
@Override
public ReadLock readLock() {
return readLock;
}
@Override
public WriteLock writeLock() {
return writeLock;
}
///// CycleDetectingLock methods. /////
@Override
public LockGraphNode getLockGraphNode() {
return lockGraphNode;
}
@Override
public boolean isAcquiredByCurrentThread() {
return isWriteLockedByCurrentThread() || getReadHoldCount() > 0;
}
}
private class CycleDetectingReentrantReadLock
extends ReentrantReadWriteLock.ReadLock {
final CycleDetectingReentrantReadWriteLock readWriteLock;
CycleDetectingReentrantReadLock(
CycleDetectingReentrantReadWriteLock readWriteLock) {
super(readWriteLock);
this.readWriteLock = readWriteLock;
}
@Override
public void lock() {
aboutToAcquire(readWriteLock);
try {
super.lock();
} finally {
lockStateChanged(readWriteLock);
}
}
@Override
public void lockInterruptibly() throws InterruptedException {
aboutToAcquire(readWriteLock);
try {
super.lockInterruptibly();
} finally {
lockStateChanged(readWriteLock);
}
}
@Override
public boolean tryLock() {
aboutToAcquire(readWriteLock);
try {
return super.tryLock();
} finally {
lockStateChanged(readWriteLock);
}
}
@Override
public boolean tryLock(long timeout, TimeUnit unit)
throws InterruptedException {
aboutToAcquire(readWriteLock);
try {
return super.tryLock(timeout, unit);
} finally {
lockStateChanged(readWriteLock);
}
}
@Override
public void unlock() {
try {
super.unlock();
} finally {
lockStateChanged(readWriteLock);
}
}
}
private class CycleDetectingReentrantWriteLock
extends ReentrantReadWriteLock.WriteLock {
final CycleDetectingReentrantReadWriteLock readWriteLock;
CycleDetectingReentrantWriteLock(
CycleDetectingReentrantReadWriteLock readWriteLock) {
super(readWriteLock);
this.readWriteLock = readWriteLock;
}
@Override
public void lock() {
aboutToAcquire(readWriteLock);
try {
super.lock();
} finally {
lockStateChanged(readWriteLock);
}
}
@Override
public void lockInterruptibly() throws InterruptedException {
aboutToAcquire(readWriteLock);
try {
super.lockInterruptibly();
} finally {
lockStateChanged(readWriteLock);
}
}
@Override
public boolean tryLock() {
aboutToAcquire(readWriteLock);
try {
return super.tryLock();
} finally {
lockStateChanged(readWriteLock);
}
}
@Override
public boolean tryLock(long timeout, TimeUnit unit)
throws InterruptedException {
aboutToAcquire(readWriteLock);
try {
return super.tryLock(timeout, unit);
} finally {
lockStateChanged(readWriteLock);
}
}
@Override
public void unlock() {
try {
super.unlock();
} finally {
lockStateChanged(readWriteLock);
}
}
}
}
| 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 |
/*
* 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. For
* example, the listener may run on an unpredictable or undesirable thread:
*
* <ul>
* <li>If the input {@code Future} is done at the time {@code addListener} is
* called, {@code addListener} will execute the listener inline.
* <li>If the input {@code Future} is not yet done, {@code addListener} will
* schedule the listener to be run by the thread that completes the input
* {@code Future}, which may be an internal system thread such as an RPC
* network thread.
* </ul>
*
* Also note that, regardless of which thread executes the listener, all
* other registered but unexecuted listeners are prevented from running
* during its execution, 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}. For a simplified but general
* listener interface, see {@link
* com.google.common.util.concurrent.Futures#addCallback addCallback()}.
*
* @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) 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 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 {@code
* 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);
}
/**
* Submits a blocking task for the given {@link Future} to provide {@link
* ListenableFuture} functionality.
*
* <p><b>Warning:</b> If the input future does not already implement {@code
* ListenableFuture}, the returned future will emulate {@link
* ListenableFuture#addListener} by submitting a task to the given executor at
* at the first call to {@code addListener}. The task must be started by the
* executor promptly, or else the returned {@code ListenableFuture} may fail
* to work. The task's execution consists of blocking until the input future
* is {@linkplain Future#isDone() done}, so each call to this method may
* claim and hold a thread for an arbitrary length of time. Use of bounded
* executors or other executors that may fail to execute a task promptly may
* result in deadlocks.
*
* <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.
*
* @since 12.0
*/
public 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.Beta;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
* Provides a backup {@code Future} to replace an earlier failed {@code Future}.
* An implementation of this interface can be applied to an input {@code Future}
* with {@link Futures#withFallback}.
*
* @param <V> the result type of the provided backup {@code Future}
*
* @author Bruno Diniz
* @since 14.0
*/
@Beta
public interface FutureFallback<V> {
/**
* Returns a {@code Future} to be used in place of the {@code Future} that
* failed with the given exception. The exception is provided so that the
* {@code Fallback} implementation can conditionally determine whether to
* propagate the exception or to attempt to recover.
*
* @param t the exception that made the future fail. 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.
*/
ListenableFuture<V> create(Throwable t) throws Exception;
}
| 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) 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.Functions;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
import com.google.common.collect.MapMaker;
import com.google.common.math.IntMath;
import com.google.common.primitives.Ints;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* A striped {@code Lock/Semaphore/ReadWriteLock}. This offers the underlying lock striping
* similar to that of {@code ConcurrentHashMap} in a reusable form, and extends it for
* semaphores and read-write locks. Conceptually, lock striping is the technique of dividing a lock
* into many <i>stripes</i>, increasing the granularity of a single lock and allowing independent
* operations to lock different stripes and proceed concurrently, instead of creating contention
* for a single lock.
*
* <p>The guarantee provided by this class is that equal keys lead to the same lock (or semaphore),
* i.e. {@code if (key1.equals(key2))} then {@code striped.get(key1) == striped.get(key2)}
* (assuming {@link Object#hashCode()} is correctly implemented for the keys). Note
* that if {@code key1} is <strong>not</strong> equal to {@code key2}, it is <strong>not</strong>
* guaranteed that {@code striped.get(key1) != striped.get(key2)}; the elements might nevertheless
* be mapped to the same lock. The lower the number of stripes, the higher the probability of this
* happening.
*
* <p>There are three flavors of this class: {@code Striped<Lock>}, {@code Striped<Semaphore>},
* and {@code Striped<ReadWriteLock>}. For each type, two implementations are offered:
* {@linkplain #lock(int) strong} and {@linkplain #lazyWeakLock(int) weak}
* {@code Striped<Lock>}, {@linkplain #semaphore(int, int) strong} and {@linkplain
* #lazyWeakSemaphore(int, int) weak} {@code Striped<Semaphore>}, and {@linkplain
* #readWriteLock(int) strong} and {@linkplain #lazyWeakReadWriteLock(int) weak}
* {@code Striped<ReadWriteLock>}. <i>Strong</i> means that all stripes (locks/semaphores) are
* initialized eagerly, and are not reclaimed unless {@code Striped} itself is reclaimable.
* <i>Weak</i> means that locks/semaphores are created lazily, and they are allowed to be reclaimed
* if nobody is holding on to them. This is useful, for example, if one wants to create a {@code
* Striped<Lock>} of many locks, but worries that in most cases only a small portion of these
* would be in use.
*
* <p>Prior to this class, one might be tempted to use {@code Map<K, Lock>}, where {@code K}
* represents the task. This maximizes concurrency by having each unique key mapped to a unique
* lock, but also maximizes memory footprint. On the other extreme, one could use a single lock
* for all tasks, which minimizes memory footprint but also minimizes concurrency. Instead of
* choosing either of these extremes, {@code Striped} allows the user to trade between required
* concurrency and memory footprint. For example, if a set of tasks are CPU-bound, one could easily
* create a very compact {@code Striped<Lock>} of {@code availableProcessors() * 4} stripes,
* instead of possibly thousands of locks which could be created in a {@code Map<K, Lock>}
* structure.
*
* @author Dimitris Andreou
* @since 13.0
*/
@Beta
public abstract class Striped<L> {
private Striped() {}
/**
* Returns the stripe that corresponds to the passed key. It is always guaranteed that if
* {@code key1.equals(key2)}, then {@code get(key1) == get(key2)}.
*
* @param key an arbitrary, non-null key
* @return the stripe that the passed key corresponds to
*/
public abstract L get(Object key);
/**
* Returns the stripe at the specified index. Valid indexes are 0, inclusively, to
* {@code size()}, exclusively.
*
* @param index the index of the stripe to return; must be in {@code [0...size())}
* @return the stripe at the specified index
*/
public abstract L getAt(int index);
/**
* Returns the index to which the given key is mapped, so that getAt(indexFor(key)) == get(key).
*/
abstract int indexFor(Object key);
/**
* Returns the total number of stripes in this instance.
*/
public abstract int size();
/**
* Returns the stripes that correspond to the passed objects, in ascending (as per
* {@link #getAt(int)}) order. Thus, threads that use the stripes in the order returned
* by this method are guaranteed to not deadlock each other.
*
* <p>It should be noted that using a {@code Striped<L>} with relatively few stripes, and
* {@code bulkGet(keys)} with a relative large number of keys can cause an excessive number
* of shared stripes (much like the birthday paradox, where much fewer than anticipated birthdays
* are needed for a pair of them to match). Please consider carefully the implications of the
* number of stripes, the intended concurrency level, and the typical number of keys used in a
* {@code bulkGet(keys)} operation. See <a href="http://www.mathpages.com/home/kmath199.htm">Balls
* in Bins model</a> for mathematical formulas that can be used to estimate the probability of
* collisions.
*
* @param keys arbitrary non-null keys
* @return the stripes corresponding to the objects (one per each object, derived by delegating
* to {@link #get(Object)}; may contain duplicates), in an increasing index order.
*/
public Iterable<L> bulkGet(Iterable<?> keys) {
// Initially using the array to store the keys, then reusing it to store the respective L's
final Object[] array = Iterables.toArray(keys, Object.class);
int[] stripes = new int[array.length];
for (int i = 0; i < array.length; i++) {
stripes[i] = indexFor(array[i]);
}
Arrays.sort(stripes);
for (int i = 0; i < array.length; i++) {
array[i] = getAt(stripes[i]);
}
/*
* Note that the returned Iterable holds references to the returned stripes, to avoid
* error-prone code like:
*
* Striped<Lock> stripedLock = Striped.lazyWeakXXX(...)'
* Iterable<Lock> locks = stripedLock.bulkGet(keys);
* for (Lock lock : locks) {
* lock.lock();
* }
* operation();
* for (Lock lock : locks) {
* lock.unlock();
* }
*
* If we only held the int[] stripes, translating it on the fly to L's, the original locks
* might be garbage collected after locking them, ending up in a huge mess.
*/
@SuppressWarnings("unchecked") // we carefully replaced all keys with their respective L's
List<L> asList = (List<L>) Arrays.asList(array);
return Collections.unmodifiableList(asList);
}
// Static factories
/**
* Creates a {@code Striped<Lock>} with eagerly initialized, strongly referenced locks, with the
* specified fairness. Every lock is reentrant.
*
* @param stripes the minimum number of stripes (locks) required
* @return a new {@code Striped<Lock>}
*/
public static Striped<Lock> lock(int stripes) {
return new CompactStriped<Lock>(stripes, new Supplier<Lock>() {
public Lock get() {
return new PaddedLock();
}
});
}
/**
* Creates a {@code Striped<Lock>} with lazily initialized, weakly referenced locks, with the
* specified fairness. Every lock is reentrant.
*
* @param stripes the minimum number of stripes (locks) required
* @return a new {@code Striped<Lock>}
*/
public static Striped<Lock> lazyWeakLock(int stripes) {
return new LazyStriped<Lock>(stripes, new Supplier<Lock>() {
public Lock get() {
return new ReentrantLock(false);
}
});
}
/**
* Creates a {@code Striped<Semaphore>} with eagerly initialized, strongly referenced semaphores,
* with the specified number of permits and fairness.
*
* @param stripes the minimum number of stripes (semaphores) required
* @param permits the number of permits in each semaphore
* @return a new {@code Striped<Semaphore>}
*/
public static Striped<Semaphore> semaphore(int stripes, final int permits) {
return new CompactStriped<Semaphore>(stripes, new Supplier<Semaphore>() {
public Semaphore get() {
return new PaddedSemaphore(permits);
}
});
}
/**
* Creates a {@code Striped<Semaphore>} with lazily initialized, weakly referenced semaphores,
* with the specified number of permits and fairness.
*
* @param stripes the minimum number of stripes (semaphores) required
* @param permits the number of permits in each semaphore
* @return a new {@code Striped<Semaphore>}
*/
public static Striped<Semaphore> lazyWeakSemaphore(int stripes, final int permits) {
return new LazyStriped<Semaphore>(stripes, new Supplier<Semaphore>() {
public Semaphore get() {
return new Semaphore(permits, false);
}
});
}
/**
* Creates a {@code Striped<ReadWriteLock>} with eagerly initialized, strongly referenced
* read-write locks, with the specified fairness. Every lock is reentrant.
*
* @param stripes the minimum number of stripes (locks) required
* @return a new {@code Striped<ReadWriteLock>}
*/
public static Striped<ReadWriteLock> readWriteLock(int stripes) {
return new CompactStriped<ReadWriteLock>(stripes, READ_WRITE_LOCK_SUPPLIER);
}
/**
* Creates a {@code Striped<ReadWriteLock>} with lazily initialized, weakly referenced
* read-write locks, with the specified fairness. Every lock is reentrant.
*
* @param stripes the minimum number of stripes (locks) required
* @return a new {@code Striped<ReadWriteLock>}
*/
public static Striped<ReadWriteLock> lazyWeakReadWriteLock(int stripes) {
return new LazyStriped<ReadWriteLock>(stripes, READ_WRITE_LOCK_SUPPLIER);
}
// ReentrantReadWriteLock is large enough to make padding probably unnecessary
private static final Supplier<ReadWriteLock> READ_WRITE_LOCK_SUPPLIER =
new Supplier<ReadWriteLock>() {
public ReadWriteLock get() {
return new ReentrantReadWriteLock();
}
};
private abstract static class PowerOfTwoStriped<L> extends Striped<L> {
/** Capacity (power of two) minus one, for fast mod evaluation */
final int mask;
PowerOfTwoStriped(int stripes) {
Preconditions.checkArgument(stripes > 0, "Stripes must be positive");
this.mask = stripes > Ints.MAX_POWER_OF_TWO ? ALL_SET : ceilToPowerOfTwo(stripes) - 1;
}
@Override final int indexFor(Object key) {
int hash = smear(key.hashCode());
return hash & mask;
}
@Override public final L get(Object key) {
return getAt(indexFor(key));
}
}
/**
* Implementation of Striped where 2^k stripes are represented as an array of the same length,
* eagerly initialized.
*/
private static class CompactStriped<L> extends PowerOfTwoStriped<L> {
/** Size is a power of two. */
private final Object[] array;
private CompactStriped(int stripes, Supplier<L> supplier) {
super(stripes);
Preconditions.checkArgument(stripes <= Ints.MAX_POWER_OF_TWO, "Stripes must be <= 2^30)");
this.array = new Object[mask + 1];
for (int i = 0; i < array.length; i++) {
array[i] = supplier.get();
}
}
@SuppressWarnings("unchecked") // we only put L's in the array
@Override public L getAt(int index) {
return (L) array[index];
}
@Override public int size() {
return array.length;
}
}
/**
* Implementation of Striped where up to 2^k stripes can be represented, using a Cache
* where the key domain is [0..2^k). To map a user key into a stripe, we take a k-bit slice of the
* user key's (smeared) hashCode(). The stripes are lazily initialized and are weakly referenced.
*/
private static class LazyStriped<L> extends PowerOfTwoStriped<L> {
final ConcurrentMap<Integer, L> cache;
final int size;
LazyStriped(int stripes, Supplier<L> supplier) {
super(stripes);
this.size = (mask == ALL_SET) ? Integer.MAX_VALUE : mask + 1;
this.cache = new MapMaker().weakValues().makeComputingMap(Functions.forSupplier(supplier));
}
@Override public L getAt(int index) {
Preconditions.checkElementIndex(index, size());
return cache.get(index);
}
@Override public int size() {
return size;
}
}
/**
* A bit mask were all bits are set.
*/
private static final int ALL_SET = ~0;
private static int ceilToPowerOfTwo(int x) {
return 1 << IntMath.log2(x, RoundingMode.CEILING);
}
/*
* This method was 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/licenses/publicdomain
*
* As of 2010/06/11, this method is identical to the (package private) hash
* method in OpenJDK 7's java.util.HashMap class.
*/
// Copied from java/com/google/common/collect/Hashing.java
private static int smear(int hashCode) {
hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12);
return hashCode ^ (hashCode >>> 7) ^ (hashCode >>> 4);
}
private static class PaddedLock extends ReentrantLock {
/*
* Padding from 40 into 64 bytes, same size as cache line. Might be beneficial to add
* a fourth long here, to minimize chance of interference between consecutive locks,
* but I couldn't observe any benefit from that.
*/
@SuppressWarnings("unused")
long q1, q2, q3;
PaddedLock() {
super(false);
}
}
private static class PaddedSemaphore extends Semaphore {
// See PaddedReentrantLock comment
@SuppressWarnings("unused")
long q1, q2, q3;
PaddedSemaphore(int permits) {
super(permits, 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.util.concurrent;
import com.google.common.annotations.Beta;
import com.google.common.collect.ForwardingObject;
import java.util.concurrent.Executor;
/**
* 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();
}
@Override public void addListener(Listener listener, Executor executor) {
delegate().addListener(listener, executor);
}
/**
* 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) 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 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) 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) 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) 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) 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 |
/*
* 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 static java.lang.Double.doubleToRawLongBits;
import static java.lang.Double.longBitsToDouble;
import com.google.common.annotations.Beta;
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) 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.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.Beta;
import com.google.common.collect.Lists;
import com.google.common.collect.Queues;
import com.google.common.util.concurrent.Service.State; // javadoc needs this
import java.util.List;
import java.util.Queue;
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.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.Immutable;
/**
* 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
* @author Luke Sandberg
* @since 1.0
*/
@Beta
public abstract class AbstractService implements Service {
private static final Logger logger = Logger.getLogger(AbstractService.class.getName());
private final ReentrantLock lock = new ReentrantLock();
private final Transition startup = new Transition();
private final Transition shutdown = new Transition();
/**
* The listeners to notify during a state transition.
*/
@GuardedBy("lock")
private final List<ListenerExecutorPair> listeners = Lists.newArrayList();
/**
* The queue of listeners that are waiting to be executed.
*
* <p>Enqueue operations should be protected by {@link #lock} while dequeue operations should be
* protected by the implicit lock on this object. Dequeue operations should be executed atomically
* with the execution of the {@link Runnable} and additionally the {@link #lock} should not be
* held when the listeners are being executed. Use {@link #executeListeners} for this operation.
* This is necessary to ensure that elements on the queue are executed in the correct order.
* Enqueue operations should be protected so that listeners are added in the correct order. We use
* a concurrent queue implementation so that enqueues can be executed concurrently with dequeues.
*/
@GuardedBy("queuedListeners")
private final Queue<Runnable> queuedListeners = Queues.newConcurrentLinkedQueue();
/**
* The current state of the service. This should be written with the lock held but can be read
* without it because it is an immutable object in a volatile field. This is desirable so that
* methods like {@link #state}, {@link #failureCause} and notably {@link #toString} can be run
* without grabbing the lock.
*
* <p>To update this field correctly the lock must be held to guarantee that the state is
* consistent.
*/
@GuardedBy("lock")
private volatile StateSnapshot snapshot = new StateSnapshot(State.NEW);
protected AbstractService() {
// Add a listener to update the futures. This needs to be added first so that it is executed
// before the other listeners. This way the other listeners can access the completed futures.
addListener(
new Listener() {
@Override public void starting() {}
@Override public void running() {
startup.set(State.RUNNING);
}
@Override public void stopping(State from) {
if (from == State.STARTING) {
startup.set(State.STOPPING);
}
}
@Override public void terminated(State from) {
if (from == State.NEW) {
startup.set(State.TERMINATED);
}
shutdown.set(State.TERMINATED);
}
@Override public void failed(State from, Throwable failure) {
switch (from) {
case STARTING:
startup.setException(failure);
shutdown.setException(new Exception("Service failed to start.", failure));
break;
case RUNNING:
shutdown.setException(new Exception("Service failed while running", failure));
break;
case STOPPING:
shutdown.setException(failure);
break;
case TERMINATED: /* fall-through */
case FAILED: /* fall-through */
case NEW: /* fall-through */
default:
throw new AssertionError("Unexpected from state: " + from);
}
}
},
MoreExecutors.sameThreadExecutor());
}
/**
* 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 (snapshot.state == State.NEW) {
snapshot = new StateSnapshot(State.STARTING);
starting();
doStart();
}
} catch (Throwable startupFailure) {
notifyFailed(startupFailure);
} finally {
lock.unlock();
executeListeners();
}
return startup;
}
@Override
public final ListenableFuture<State> stop() {
lock.lock();
try {
switch (snapshot.state) {
case NEW:
snapshot = new StateSnapshot(State.TERMINATED);
terminated(State.NEW);
break;
case STARTING:
snapshot = new StateSnapshot(State.STARTING, true, null);
stopping(State.STARTING);
break;
case RUNNING:
snapshot = new StateSnapshot(State.STOPPING);
stopping(State.RUNNING);
doStop();
break;
case STOPPING:
case TERMINATED:
case FAILED:
// do nothing
break;
default:
throw new AssertionError("Unexpected state: " + snapshot.state);
}
} catch (Throwable shutdownFailure) {
notifyFailed(shutdownFailure);
} finally {
lock.unlock();
executeListeners();
}
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 (snapshot.state != State.STARTING) {
IllegalStateException failure = new IllegalStateException(
"Cannot notifyStarted() when the service is " + snapshot.state);
notifyFailed(failure);
throw failure;
}
if (snapshot.shutdownWhenStartupFinishes) {
snapshot = new StateSnapshot(State.STOPPING);
// We don't call listeners here because we already did that when we set the
// shutdownWhenStartupFinishes flag.
doStop();
} else {
snapshot = new StateSnapshot(State.RUNNING);
running();
}
} finally {
lock.unlock();
executeListeners();
}
}
/**
* 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 (snapshot.state != State.STOPPING && snapshot.state != State.RUNNING) {
IllegalStateException failure = new IllegalStateException(
"Cannot notifyStopped() when the service is " + snapshot.state);
notifyFailed(failure);
throw failure;
}
State previous = snapshot.state;
snapshot = new StateSnapshot(State.TERMINATED);
terminated(previous);
} finally {
lock.unlock();
executeListeners();
}
}
/**
* 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 {
switch (snapshot.state) {
case NEW:
case TERMINATED:
throw new IllegalStateException("Failed while in state:" + snapshot.state, cause);
case RUNNING:
case STARTING:
case STOPPING:
State previous = snapshot.state;
snapshot = new StateSnapshot(State.FAILED, false, cause);
failed(previous, cause);
break;
case FAILED:
// Do nothing
break;
default:
throw new AssertionError("Unexpected state: " + snapshot.state);
}
} finally {
lock.unlock();
executeListeners();
}
}
@Override
public final boolean isRunning() {
return state() == State.RUNNING;
}
@Override
public final State state() {
return snapshot.externalState();
}
@Override
public final void addListener(Listener listener, Executor executor) {
checkNotNull(listener, "listener");
checkNotNull(executor, "executor");
lock.lock();
try {
if (snapshot.state != State.TERMINATED && snapshot.state != State.FAILED) {
listeners.add(new ListenerExecutorPair(listener, executor));
}
} 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());
}
}
}
/**
* Attempts to execute all the listeners in {@link #queuedListeners} while not holding the
* {@link #lock}.
*/
private void executeListeners() {
if (!lock.isHeldByCurrentThread()) {
synchronized (queuedListeners) {
Runnable listener;
while ((listener = queuedListeners.poll()) != null) {
listener.run();
}
}
}
}
@GuardedBy("lock")
private void starting() {
for (final ListenerExecutorPair pair : listeners) {
queuedListeners.add(new Runnable() {
@Override public void run() {
pair.execute(new Runnable() {
@Override public void run() {
pair.listener.starting();
}
});
}
});
}
}
@GuardedBy("lock")
private void running() {
for (final ListenerExecutorPair pair : listeners) {
queuedListeners.add(new Runnable() {
@Override public void run() {
pair.execute(new Runnable() {
@Override public void run() {
pair.listener.running();
}
});
}
});
}
}
@GuardedBy("lock")
private void stopping(final State from) {
for (final ListenerExecutorPair pair : listeners) {
queuedListeners.add(new Runnable() {
@Override public void run() {
pair.execute(new Runnable() {
@Override public void run() {
pair.listener.stopping(from);
}
});
}
});
}
}
@GuardedBy("lock")
private void terminated(final State from) {
for (final ListenerExecutorPair pair : listeners) {
queuedListeners.add(new Runnable() {
@Override public void run() {
pair.execute(new Runnable() {
@Override public void run() {
pair.listener.terminated(from);
}
});
}
});
}
// There are no more state transitions so we can clear this out.
listeners.clear();
}
@GuardedBy("lock")
private void failed(final State from, final Throwable cause) {
for (final ListenerExecutorPair pair : listeners) {
queuedListeners.add(new Runnable() {
@Override public void run() {
pair.execute(new Runnable() {
@Override public void run() {
pair.listener.failed(from, cause);
}
});
}
});
}
// There are no more state transitions so we can clear this out.
listeners.clear();
}
/** A simple holder for a listener and its executor. */
private static class ListenerExecutorPair {
final Listener listener;
final Executor executor;
ListenerExecutorPair(Listener listener, Executor executor) {
this.listener = listener;
this.executor = executor;
}
/**
* Executes the given {@link Runnable} on {@link #executor} logging and swallowing all
* exceptions
*/
void execute(Runnable runnable) {
try {
executor.execute(runnable);
} catch (Exception e) {
logger.log(Level.SEVERE, "Exception while executing listener " + listener
+ " with executor " + executor, e);
}
}
}
/**
* An immutable snapshot of the current state of the service. This class represents a consistent
* snapshot of the state and therefore it can be used to answer simple queries without needing to
* grab a lock.
*/
@Immutable
private static final class StateSnapshot {
/**
* The internal state, which equals external state unless
* shutdownWhenStartupFinishes is true.
*/
final State state;
/**
* If true, the user requested a shutdown while the service was still starting
* up.
*/
final boolean shutdownWhenStartupFinishes;
/**
* The exception that caused this service to fail. This will be {@code null}
* unless the service has failed.
*/
@Nullable
final Throwable failure;
StateSnapshot(State internalState) {
this(internalState, false, null);
}
StateSnapshot(
State internalState, boolean shutdownWhenStartupFinishes, @Nullable Throwable failure) {
checkArgument(!shutdownWhenStartupFinishes || internalState == State.STARTING,
"shudownWhenStartupFinishes can only be set if state is STARTING. Got %s instead.",
internalState);
checkArgument(!(failure != null ^ internalState == State.FAILED),
"A failure cause should be set if and only if the state is failed. Got %s and %s "
+ "instead.", internalState, failure);
this.state = internalState;
this.shutdownWhenStartupFinishes = shutdownWhenStartupFinishes;
this.failure = failure;
}
/** @see Service#state() */
State externalState() {
if (shutdownWhenStartupFinishes && state == State.STARTING) {
return State.STOPPING;
} else {
return state;
}
}
/** @see Service#failureCause() */
Throwable failureCause() {
checkState(state == State.FAILED,
"failureCause() is only valid if the service has failed, service is %s", state);
return failure;
}
}
}
| 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.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.collect.Lists;
import com.google.common.collect.Queues;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.BlockingQueue;
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.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.TimeoutException;
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) {
return new Application()
.getExitingExecutorService(executor, terminationTimeout, timeUnit);
}
/**
* 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) {
return new Application()
.getExitingScheduledExecutorService(executor, terminationTimeout, timeUnit);
}
/**
* 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(
ExecutorService service, long terminationTimeout, TimeUnit timeUnit) {
new Application()
.addDelayedShutdownHook(service, terminationTimeout, timeUnit);
}
/**
* 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 new Application().getExitingExecutorService(executor);
}
/**
* 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 new Application().getExitingScheduledExecutorService(executor);
}
/** Represents the current application to register shutdown hooks. */
@VisibleForTesting static class Application {
final ExecutorService getExitingExecutorService(
ThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
useDaemonThreadFactory(executor);
ExecutorService service = Executors.unconfigurableExecutorService(executor);
addDelayedShutdownHook(service, terminationTimeout, timeUnit);
return service;
}
final ScheduledExecutorService getExitingScheduledExecutorService(
ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) {
useDaemonThreadFactory(executor);
ScheduledExecutorService service = Executors.unconfigurableScheduledExecutorService(executor);
addDelayedShutdownHook(service, terminationTimeout, timeUnit);
return service;
}
final void addDelayedShutdownHook(
final ExecutorService service, final long terminationTimeout, final TimeUnit timeUnit) {
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.
}
}
}, "DelayedShutdownHook-for-" + service));
}
final ExecutorService getExitingExecutorService(ThreadPoolExecutor executor) {
return getExitingExecutorService(executor, 120, TimeUnit.SECONDS);
}
final ScheduledExecutorService getExitingScheduledExecutorService(
ScheduledThreadPoolExecutor executor) {
return getExitingScheduledExecutorService(executor, 120, TimeUnit.SECONDS);
}
@VisibleForTesting void addShutdownHook(Thread hook) {
Runtime.getRuntime().addShutdownHook(hook);
}
}
private static void useDaemonThreadFactory(ThreadPoolExecutor executor) {
executor.setThreadFactory(new ThreadFactoryBuilder()
.setDaemon(true)
.setThreadFactory(executor.getThreadFactory())
.build());
}
/**
* 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 {
@SuppressWarnings("hiding")
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);
}
}
/*
* This following method is a modified version of one found in
* http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/test/tck/AbstractExecutorServiceTest.java?revision=1.30
* 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/
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
/**
* An implementation of {@link ExecutorService#invokeAny} for {@link ListeningExecutorService}
* implementations.
*/ static <T> T invokeAnyImpl(ListeningExecutorService executorService,
Collection<? extends Callable<T>> tasks, boolean timed, long nanos)
throws InterruptedException, ExecutionException, TimeoutException {
int ntasks = tasks.size();
checkArgument(ntasks > 0);
List<Future<T>> futures = Lists.newArrayListWithCapacity(ntasks);
BlockingQueue<Future<T>> futureQueue = Queues.newLinkedBlockingQueue();
// 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();
futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue));
--ntasks;
int active = 1;
for (;;) {
Future<T> f = futureQueue.poll();
if (f == null) {
if (ntasks > 0) {
--ntasks;
futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue));
++active;
} else if (active == 0) {
break;
} else if (timed) {
f = futureQueue.poll(nanos, TimeUnit.NANOSECONDS);
if (f == null) {
throw new TimeoutException();
}
long now = System.nanoTime();
nanos -= now - lastTime;
lastTime = now;
} else {
f = futureQueue.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);
}
}
}
/**
* Submits the task and adds a listener that adds the future to {@code queue} when it completes.
*/
private static <T> ListenableFuture<T> submitAndAddQueueListener(
ListeningExecutorService executorService, Callable<T> task,
final BlockingQueue<Future<T>> queue) {
final ListenableFuture<T> future = executorService.submit(task);
future.addListener(new Runnable() {
@Override public void run() {
queue.add(future);
}
}, MoreExecutors.sameThreadExecutor());
return future;
}
}
| 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.
*/
/**
* Arithmetic functions operating on primitive values and {@link java.math.BigInteger} instances.
*
* <p>This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/MathExplained">
* math utilities</a>.
*/
@ParametersAreNonnullByDefault
package com.google.common.math;
import javax.annotation.ParametersAreNonnullByDefault;
| 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.math;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkNoOverflow;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.BigInteger;
import java.math.RoundingMode;
/**
* A class for arithmetic on values of type {@code long}. Where possible, methods are defined and
* named analogously to their {@code BigInteger} counterparts.
*
* <p>The implementations of many methods in this class are based on material from Henry S. Warren,
* Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
*
* <p>Similar functionality for {@code int} and for {@link BigInteger} can be found in
* {@link IntMath} and {@link BigIntegerMath} respectively. For other common operations on
* {@code long} values, see {@link com.google.common.primitives.Longs}.
*
* @author Louis Wasserman
* @since 11.0
*/
@Beta
@GwtCompatible(emulated = true)
public final class LongMath {
// NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
/**
* Returns {@code true} if {@code x} represents a power of two.
*
* <p>This differs from {@code Long.bitCount(x) == 1}, because
* {@code Long.bitCount(Long.MIN_VALUE) == 1}, but {@link Long#MIN_VALUE} is not a power of two.
*/
public static boolean isPowerOfTwo(long x) {
return x > 0 & (x & (x - 1)) == 0;
}
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
public static int log2(long x, RoundingMode mode) {
checkPositive("x", x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x));
// fall through
case DOWN:
case FLOOR:
return (Long.SIZE - 1) - Long.numberOfLeadingZeros(x);
case UP:
case CEILING:
return Long.SIZE - Long.numberOfLeadingZeros(x - 1);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
int leadingZeros = Long.numberOfLeadingZeros(x);
long cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros;
// floor(2^(logFloor + 0.5))
int logFloor = (Long.SIZE - 1) - leadingZeros;
return (x <= cmp) ? logFloor : logFloor + 1;
default:
throw new AssertionError("impossible");
}
}
/** The biggest half power of two that fits into an unsigned long */
@VisibleForTesting static final long MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333F9DE6484L;
/**
* Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of ten
*/
@GwtIncompatible("TODO")
@SuppressWarnings("fallthrough")
public static int log10(long x, RoundingMode mode) {
checkPositive("x", x);
if (fitsInInt(x)) {
return IntMath.log10((int) x, mode);
}
int logFloor = log10Floor(x);
long floorPow = POWERS_OF_10[logFloor];
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(x == floorPow);
// fall through
case FLOOR:
case DOWN:
return logFloor;
case CEILING:
case UP:
return (x == floorPow) ? logFloor : logFloor + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// sqrt(10) is irrational, so log10(x)-logFloor is never exactly 0.5
return (x <= HALF_POWERS_OF_10[logFloor]) ? logFloor : logFloor + 1;
default:
throw new AssertionError();
}
}
@GwtIncompatible("TODO")
static int log10Floor(long x) {
/*
* Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation.
*
* The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))),
* we can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x))
* is 6, then 64 <= x < 128, so floor(log10(x)) is either 1 or 2.
*/
int y = MAX_LOG10_FOR_LEADING_ZEROS[Long.numberOfLeadingZeros(x)];
// y is the higher of the two possible values of floor(log10(x))
long sgn = (x - POWERS_OF_10[y]) >>> (Long.SIZE - 1);
/*
* sgn is the sign bit of x - 10^y; it is 1 if x < 10^y, and 0 otherwise. If x < 10^y, then we
* want the lower of the two possible values, or y - 1, otherwise, we want y.
*/
return y - (int) sgn;
}
// MAX_LOG10_FOR_LEADING_ZEROS[i] == floor(log10(2^(Long.SIZE - i)))
@VisibleForTesting static final byte[] MAX_LOG10_FOR_LEADING_ZEROS = {
19, 18, 18, 18, 18, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15, 14, 14, 14, 13, 13, 13, 12, 12,
12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4,
3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0 };
@GwtIncompatible("TODO")
@VisibleForTesting
static final long[] POWERS_OF_10 = {
1L,
10L,
100L,
1000L,
10000L,
100000L,
1000000L,
10000000L,
100000000L,
1000000000L,
10000000000L,
100000000000L,
1000000000000L,
10000000000000L,
100000000000000L,
1000000000000000L,
10000000000000000L,
100000000000000000L,
1000000000000000000L
};
// HALF_POWERS_OF_10[i] = largest long less than 10^(i + 0.5)
@GwtIncompatible("TODO")
@VisibleForTesting
static final long[] HALF_POWERS_OF_10 = {
3L,
31L,
316L,
3162L,
31622L,
316227L,
3162277L,
31622776L,
316227766L,
3162277660L,
31622776601L,
316227766016L,
3162277660168L,
31622776601683L,
316227766016837L,
3162277660168379L,
31622776601683793L,
316227766016837933L,
3162277660168379331L
};
/**
* Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to
* {@code BigInteger.valueOf(b).pow(k).longValue()}. This implementation runs in {@code O(log k)}
* time.
*
* @throws IllegalArgumentException if {@code k < 0}
*/
@GwtIncompatible("TODO")
public static long pow(long b, int k) {
checkNonNegative("exponent", k);
if (-2 <= b && b <= 2) {
switch ((int) b) {
case 0:
return (k == 0) ? 1 : 0;
case 1:
return 1;
case (-1):
return ((k & 1) == 0) ? 1 : -1;
case 2:
return (k < Long.SIZE) ? 1L << k : 0;
case (-2):
if (k < Long.SIZE) {
return ((k & 1) == 0) ? 1L << k : -(1L << k);
} else {
return 0;
}
}
}
for (long accum = 1;; k >>= 1) {
switch (k) {
case 0:
return accum;
case 1:
return accum * b;
default:
accum *= ((k & 1) == 0) ? 1 : b;
b *= b;
}
}
}
/**
* Returns the square root of {@code x}, rounded with the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x < 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and
* {@code sqrt(x)} is not an integer
*/
@GwtIncompatible("TODO")
@SuppressWarnings("fallthrough")
public static long sqrt(long x, RoundingMode mode) {
checkNonNegative("x", x);
if (fitsInInt(x)) {
return IntMath.sqrt((int) x, mode);
}
long sqrtFloor = sqrtFloor(x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(sqrtFloor * sqrtFloor == x); // fall through
case FLOOR:
case DOWN:
return sqrtFloor;
case CEILING:
case UP:
return (sqrtFloor * sqrtFloor == x) ? sqrtFloor : sqrtFloor + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
long halfSquare = sqrtFloor * sqrtFloor + sqrtFloor;
/*
* We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both
* x and halfSquare are integers, this is equivalent to testing whether or not x <=
* halfSquare. (We have to deal with overflow, though.)
*/
return (halfSquare >= x | halfSquare < 0) ? sqrtFloor : sqrtFloor + 1;
default:
throw new AssertionError();
}
}
@GwtIncompatible("TODO")
private static long sqrtFloor(long x) {
// Hackers's Delight, Figure 11-1
long sqrt0 = (long) Math.sqrt(x);
// Precision can be lost in the cast to double, so we use this as a starting estimate.
long sqrt1 = (sqrt0 + (x / sqrt0)) >> 1;
if (sqrt1 == sqrt0) {
return sqrt0;
}
do {
sqrt0 = sqrt1;
sqrt1 = (sqrt0 + (x / sqrt0)) >> 1;
} while (sqrt1 < sqrt0);
return sqrt0;
}
/**
* Returns the result of dividing {@code p} by {@code q}, rounding using the specified
* {@code RoundingMode}.
*
* @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
* is not an integer multiple of {@code b}
*/
@GwtIncompatible("TODO")
@SuppressWarnings("fallthrough")
public static long divide(long p, long q, RoundingMode mode) {
checkNotNull(mode);
long div = p / q; // throws if q == 0
long rem = p - q * div; // equals p % q
if (rem == 0) {
return div;
}
/*
* Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to
* deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of
* p / q.
*
* signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise.
*/
int signum = 1 | (int) ((p ^ q) >> (Long.SIZE - 1));
boolean increment;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(rem == 0);
// fall through
case DOWN:
increment = false;
break;
case UP:
increment = true;
break;
case CEILING:
increment = signum > 0;
break;
case FLOOR:
increment = signum < 0;
break;
case HALF_EVEN:
case HALF_DOWN:
case HALF_UP:
long absRem = abs(rem);
long cmpRemToHalfDivisor = absRem - (abs(q) - absRem);
// subtracting two nonnegative longs can't overflow
// cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2).
if (cmpRemToHalfDivisor == 0) { // exactly on the half mark
increment = (mode == HALF_UP | (mode == HALF_EVEN & (div & 1) != 0));
} else {
increment = cmpRemToHalfDivisor > 0; // closer to the UP value
}
break;
default:
throw new AssertionError();
}
return increment ? div + signum : div;
}
/**
* Returns {@code x mod m}. This differs from {@code x % m} in that it always returns a
* non-negative result.
*
* <p>For example:
*
* <pre> {@code
*
* mod(7, 4) == 3
* mod(-7, 4) == 1
* mod(-1, 4) == 3
* mod(-8, 4) == 0
* mod(8, 4) == 0}</pre>
*
* @throws ArithmeticException if {@code m <= 0}
*/
@GwtIncompatible("TODO")
public static int mod(long x, int m) {
// Cast is safe because the result is guaranteed in the range [0, m)
return (int) mod(x, (long) m);
}
/**
* Returns {@code x mod m}. This differs from {@code x % m} in that it always returns a
* non-negative result.
*
* <p>For example:
*
* <pre> {@code
*
* mod(7, 4) == 3
* mod(-7, 4) == 1
* mod(-1, 4) == 3
* mod(-8, 4) == 0
* mod(8, 4) == 0}</pre>
*
* @throws ArithmeticException if {@code m <= 0}
*/
@GwtIncompatible("TODO")
public static long mod(long x, long m) {
if (m <= 0) {
throw new ArithmeticException("Modulus " + m + " must be > 0");
}
long result = x % m;
return (result >= 0) ? result : result + m;
}
/**
* Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if
* {@code a == 0 && b == 0}.
*
* @throws IllegalArgumentException if {@code a < 0} or {@code b < 0}
*/
@GwtIncompatible("TODO")
public static long gcd(long a, long b) {
/*
* The reason we require both arguments to be >= 0 is because otherwise, what do you return on
* gcd(0, Long.MIN_VALUE)? BigInteger.gcd would return positive 2^63, but positive 2^63 isn't
* an int.
*/
checkNonNegative("a", a);
checkNonNegative("b", b);
if (a == 0) {
// 0 % b == 0, so b divides a, but the converse doesn't hold.
// BigInteger.gcd is consistent with this decision.
return b;
} else if (b == 0) {
return a; // similar logic
}
/*
* Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm.
* This is >60% faster than the Euclidean algorithm in benchmarks.
*/
int aTwos = Long.numberOfTrailingZeros(a);
a >>= aTwos; // divide out all 2s
int bTwos = Long.numberOfTrailingZeros(b);
b >>= bTwos; // divide out all 2s
while (a != b) { // both a, b are odd
// The key to the binary GCD algorithm is as follows:
// Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b).
// But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two.
// We bend over backwards to avoid branching, adapting a technique from
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
long delta = a - b; // can't overflow, since a and b are nonnegative
long minDeltaOrZero = delta & (delta >> (Long.SIZE - 1));
// equivalent to Math.min(delta, 0)
a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b)
// a is now nonnegative and even
b += minDeltaOrZero; // sets b to min(old a, b)
a >>= Long.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b
}
return a << min(aTwos, bTwos);
}
/**
* Returns the sum of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a + b} overflows in signed {@code long} arithmetic
*/
@GwtIncompatible("TODO")
public static long checkedAdd(long a, long b) {
long result = a + b;
checkNoOverflow((a ^ b) < 0 | (a ^ result) >= 0);
return result;
}
/**
* Returns the difference of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a - b} overflows in signed {@code long} arithmetic
*/
@GwtIncompatible("TODO")
public static long checkedSubtract(long a, long b) {
long result = a - b;
checkNoOverflow((a ^ b) >= 0 | (a ^ result) >= 0);
return result;
}
/**
* Returns the product of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a * b} overflows in signed {@code long} arithmetic
*/
@GwtIncompatible("TODO")
public static long checkedMultiply(long a, long b) {
// Hacker's Delight, Section 2-12
int leadingZeros = Long.numberOfLeadingZeros(a) + Long.numberOfLeadingZeros(~a)
+ Long.numberOfLeadingZeros(b) + Long.numberOfLeadingZeros(~b);
/*
* If leadingZeros > Long.SIZE + 1 it's definitely fine, if it's < Long.SIZE it's definitely
* bad. We do the leadingZeros check to avoid the division below if at all possible.
*
* Otherwise, if b == Long.MIN_VALUE, then the only allowed values of a are 0 and 1. We take
* care of all a < 0 with their own check, because in particular, the case a == -1 will
* incorrectly pass the division check below.
*
* In all other cases, we check that either a is 0 or the result is consistent with division.
*/
if (leadingZeros > Long.SIZE + 1) {
return a * b;
}
checkNoOverflow(leadingZeros >= Long.SIZE);
checkNoOverflow(a >= 0 | b != Long.MIN_VALUE);
long result = a * b;
checkNoOverflow(a == 0 || result / a == b);
return result;
}
/**
* Returns the {@code b} to the {@code k}th power, provided it does not overflow.
*
* @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed
* {@code long} arithmetic
*/
@GwtIncompatible("TODO")
public static long checkedPow(long b, int k) {
checkNonNegative("exponent", k);
if (b >= -2 & b <= 2) {
switch ((int) b) {
case 0:
return (k == 0) ? 1 : 0;
case 1:
return 1;
case (-1):
return ((k & 1) == 0) ? 1 : -1;
case 2:
checkNoOverflow(k < Long.SIZE - 1);
return 1L << k;
case (-2):
checkNoOverflow(k < Long.SIZE);
return ((k & 1) == 0) ? (1L << k) : (-1L << k);
}
}
long accum = 1;
while (true) {
switch (k) {
case 0:
return accum;
case 1:
return checkedMultiply(accum, b);
default:
if ((k & 1) != 0) {
accum = checkedMultiply(accum, b);
}
k >>= 1;
if (k > 0) {
checkNoOverflow(b <= FLOOR_SQRT_MAX_LONG);
b *= b;
}
}
}
}
@GwtIncompatible("TODO")
@VisibleForTesting static final long FLOOR_SQRT_MAX_LONG = 3037000499L;
/**
* Returns {@code n!}, that is, the product of the first {@code n} positive
* integers, {@code 1} if {@code n == 0}, or {@link Long#MAX_VALUE} if the
* result does not fit in a {@code long}.
*
* @throws IllegalArgumentException if {@code n < 0}
*/
@GwtIncompatible("TODO")
public static long factorial(int n) {
checkNonNegative("n", n);
return (n < FACTORIALS.length) ? FACTORIALS[n] : Long.MAX_VALUE;
}
static final long[] FACTORIALS = {
1L,
1L,
1L * 2,
1L * 2 * 3,
1L * 2 * 3 * 4,
1L * 2 * 3 * 4 * 5,
1L * 2 * 3 * 4 * 5 * 6,
1L * 2 * 3 * 4 * 5 * 6 * 7,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19,
1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20
};
/**
* Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
* {@code k}, or {@link Long#MAX_VALUE} if the result does not fit in a {@code long}.
*
* @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n}
*/
public static long binomial(int n, int k) {
checkNonNegative("n", n);
checkNonNegative("k", k);
checkArgument(k <= n, "k (%s) > n (%s)", k, n);
if (k > (n >> 1)) {
k = n - k;
}
if (k >= BIGGEST_BINOMIALS.length || n > BIGGEST_BINOMIALS[k]) {
return Long.MAX_VALUE;
}
long result = 1;
if (k < BIGGEST_SIMPLE_BINOMIALS.length && n <= BIGGEST_SIMPLE_BINOMIALS[k]) {
// guaranteed not to overflow
for (int i = 0; i < k; i++) {
result *= n - i;
result /= i + 1;
}
} else {
// We want to do this in long math for speed, but want to avoid overflow.
// Dividing by the GCD suffices to avoid overflow in all the remaining cases.
for (int i = 1; i <= k; i++, n--) {
int d = IntMath.gcd(n, i);
result /= i / d; // (i/d) is guaranteed to divide result
result *= n / d;
}
}
return result;
}
/*
* binomial(BIGGEST_BINOMIALS[k], k) fits in a long, but not
* binomial(BIGGEST_BINOMIALS[k] + 1, k).
*/
static final int[] BIGGEST_BINOMIALS =
{Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, 16175, 4337, 1733,
887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68,
67, 67, 66, 66, 66, 66};
/*
* binomial(BIGGEST_SIMPLE_BINOMIALS[k], k) doesn't need to use the slower GCD-based impl,
* but binomial(BIGGEST_SIMPLE_BINOMIALS[k] + 1, k) does.
*/
@VisibleForTesting static final int[] BIGGEST_SIMPLE_BINOMIALS =
{Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 2642246, 86251, 11724, 3218, 1313,
684, 419, 287, 214, 169, 139, 119, 105, 95, 87, 81, 76, 73, 70, 68, 66, 64, 63, 62, 62,
61, 61, 61};
// These values were generated by using checkedMultiply to see when the simple multiply/divide
// algorithm would lead to an overflow.
@GwtIncompatible("TODO")
static boolean fitsInInt(long x) {
return (int) x == x;
}
/**
* Returns the arithmetic mean of {@code x} and {@code y}, rounded toward
* negative infinity. This method is resilient to overflow.
*
* @since 14.0
*/
public static long mean(long x, long y) {
// Efficient method for computing the arithmetic mean.
// The alternative (x + y) / 2 fails for large values.
// The alternative (x + y) >>> 1 fails for negative values.
return (x & y) + ((x ^ y) >> 1);
}
private LongMath() {}
}
| 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.math;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.math.DoubleUtils.IMPLICIT_BIT;
import static com.google.common.math.DoubleUtils.SIGNIFICAND_BITS;
import static com.google.common.math.DoubleUtils.getSignificand;
import static com.google.common.math.DoubleUtils.isFinite;
import static com.google.common.math.DoubleUtils.isNormal;
import static com.google.common.math.DoubleUtils.scaleNormalize;
import static com.google.common.math.MathPreconditions.checkInRange;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.lang.Math.abs;
import static java.lang.Math.copySign;
import static java.lang.Math.getExponent;
import static java.lang.Math.log;
import static java.lang.Math.rint;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Booleans;
import java.math.BigInteger;
import java.math.RoundingMode;
/**
* A class for arithmetic on doubles that is not covered by {@link java.lang.Math}.
*
* @author Louis Wasserman
* @since 11.0
*/
@Beta
public final class DoubleMath {
/*
* This method returns a value y such that rounding y DOWN (towards zero) gives the same result
* as rounding x according to the specified mode.
*/
static double roundIntermediate(double x, RoundingMode mode) {
if (!isFinite(x)) {
throw new ArithmeticException("input is infinite or NaN");
}
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isMathematicalInteger(x));
return x;
case FLOOR:
if (x >= 0.0 || isMathematicalInteger(x)) {
return x;
} else {
return x - 1.0;
}
case CEILING:
if (x <= 0.0 || isMathematicalInteger(x)) {
return x;
} else {
return x + 1.0;
}
case DOWN:
return x;
case UP:
if (isMathematicalInteger(x)) {
return x;
} else {
return x + Math.copySign(1.0, x);
}
case HALF_EVEN:
return rint(x);
case HALF_UP: {
double z = rint(x);
if (abs(x - z) == 0.5) {
return x + copySign(0.5, x);
} else {
return z;
}
}
case HALF_DOWN: {
double z = rint(x);
if (abs(x - z) == 0.5) {
return x;
} else {
return z;
}
}
default:
throw new AssertionError();
}
}
/**
* Returns the {@code int} value that is equal to {@code x} rounded with the specified rounding
* mode, if possible.
*
* @throws ArithmeticException if
* <ul>
* <li>{@code x} is infinite or NaN
* <li>{@code x}, after being rounded to a mathematical integer using the specified
* rounding mode, is either less than {@code Integer.MIN_VALUE} or greater than {@code
* Integer.MAX_VALUE}
* <li>{@code x} is not a mathematical integer and {@code mode} is
* {@link RoundingMode#UNNECESSARY}
* </ul>
*/
public static int roundToInt(double x, RoundingMode mode) {
double z = roundIntermediate(x, mode);
checkInRange(z > MIN_INT_AS_DOUBLE - 1.0 & z < MAX_INT_AS_DOUBLE + 1.0);
return (int) z;
}
private static final double MIN_INT_AS_DOUBLE = -0x1p31;
private static final double MAX_INT_AS_DOUBLE = 0x1p31 - 1.0;
/**
* Returns the {@code long} value that is equal to {@code x} rounded with the specified rounding
* mode, if possible.
*
* @throws ArithmeticException if
* <ul>
* <li>{@code x} is infinite or NaN
* <li>{@code x}, after being rounded to a mathematical integer using the specified
* rounding mode, is either less than {@code Long.MIN_VALUE} or greater than {@code
* Long.MAX_VALUE}
* <li>{@code x} is not a mathematical integer and {@code mode} is
* {@link RoundingMode#UNNECESSARY}
* </ul>
*/
public static long roundToLong(double x, RoundingMode mode) {
double z = roundIntermediate(x, mode);
checkInRange(MIN_LONG_AS_DOUBLE - z < 1.0 & z < MAX_LONG_AS_DOUBLE_PLUS_ONE);
return (long) z;
}
private static final double MIN_LONG_AS_DOUBLE = -0x1p63;
/*
* We cannot store Long.MAX_VALUE as a double without losing precision. Instead, we store
* Long.MAX_VALUE + 1 == -Long.MIN_VALUE, and then offset all comparisons by 1.
*/
private static final double MAX_LONG_AS_DOUBLE_PLUS_ONE = 0x1p63;
/**
* Returns the {@code BigInteger} value that is equal to {@code x} rounded with the specified
* rounding mode, if possible.
*
* @throws ArithmeticException if
* <ul>
* <li>{@code x} is infinite or NaN
* <li>{@code x} is not a mathematical integer and {@code mode} is
* {@link RoundingMode#UNNECESSARY}
* </ul>
*/
public static BigInteger roundToBigInteger(double x, RoundingMode mode) {
x = roundIntermediate(x, mode);
if (MIN_LONG_AS_DOUBLE - x < 1.0 & x < MAX_LONG_AS_DOUBLE_PLUS_ONE) {
return BigInteger.valueOf((long) x);
}
int exponent = getExponent(x);
long significand = getSignificand(x);
BigInteger result = BigInteger.valueOf(significand).shiftLeft(exponent - SIGNIFICAND_BITS);
return (x < 0) ? result.negate() : result;
}
/**
* Returns {@code true} if {@code x} is exactly equal to {@code 2^k} for some finite integer
* {@code k}.
*/
public static boolean isPowerOfTwo(double x) {
return x > 0.0 && isFinite(x) && LongMath.isPowerOfTwo(getSignificand(x));
}
/**
* Returns the base 2 logarithm of a double value.
*
* <p>Special cases:
* <ul>
* <li>If {@code x} is NaN or less than zero, the result is NaN.
* <li>If {@code x} is positive infinity, the result is positive infinity.
* <li>If {@code x} is positive or negative zero, the result is negative infinity.
* </ul>
*
* <p>The computed result is within 1 ulp of the exact result.
*
* <p>If the result of this method will be immediately rounded to an {@code int},
* {@link #log2(double, RoundingMode)} is faster.
*/
public static double log2(double x) {
return log(x) / LN_2; // surprisingly within 1 ulp according to tests
}
private static final double LN_2 = log(2);
/**
* Returns the base 2 logarithm of a double value, rounded with the specified rounding mode to an
* {@code int}.
*
* <p>Regardless of the rounding mode, this is faster than {@code (int) log2(x)}.
*
* @throws IllegalArgumentException if {@code x <= 0.0}, {@code x} is NaN, or {@code x} is
* infinite
*/
@SuppressWarnings("fallthrough")
public static int log2(double x, RoundingMode mode) {
checkArgument(x > 0.0 && isFinite(x), "x must be positive and finite");
int exponent = getExponent(x);
if (!isNormal(x)) {
return log2(x * IMPLICIT_BIT, mode) - SIGNIFICAND_BITS;
// Do the calculation on a normal value.
}
// x is positive, finite, and normal
boolean increment;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x));
// fall through
case FLOOR:
increment = false;
break;
case CEILING:
increment = !isPowerOfTwo(x);
break;
case DOWN:
increment = exponent < 0 & !isPowerOfTwo(x);
break;
case UP:
increment = exponent >= 0 & !isPowerOfTwo(x);
break;
case HALF_DOWN:
case HALF_EVEN:
case HALF_UP:
double xScaled = scaleNormalize(x);
// sqrt(2) is irrational, and the spec is relative to the "exact numerical result,"
// so log2(x) is never exactly exponent + 0.5.
increment = (xScaled * xScaled) > 2.0;
break;
default:
throw new AssertionError();
}
return increment ? exponent + 1 : exponent;
}
/**
* Returns {@code true} if {@code x} represents a mathematical integer.
*
* <p>This is equivalent to, but not necessarily implemented as, the expression {@code
* !Double.isNaN(x) && !Double.isInfinite(x) && x == Math.rint(x)}.
*/
public static boolean isMathematicalInteger(double x) {
return isFinite(x)
&& (x == 0.0 ||
SIGNIFICAND_BITS - Long.numberOfTrailingZeros(getSignificand(x)) <= getExponent(x));
}
/**
* Returns {@code n!}, that is, the product of the first {@code n} positive
* integers, {@code 1} if {@code n == 0}, or e n!}, or
* {@link Double#POSITIVE_INFINITY} if {@code n! > Double.MAX_VALUE}.
*
* <p>The result is within 1 ulp of the true value.
*
* @throws IllegalArgumentException if {@code n < 0}
*/
public static double factorial(int n) {
checkNonNegative("n", n);
if (n > MAX_FACTORIAL) {
return Double.POSITIVE_INFINITY;
} else {
// Multiplying the last (n & 0xf) values into their own accumulator gives a more accurate
// result than multiplying by EVERY_SIXTEENTH_FACTORIAL[n >> 4] directly.
double accum = 1.0;
for (int i = 1 + (n & ~0xf); i <= n; i++) {
accum *= i;
}
return accum * EVERY_SIXTEENTH_FACTORIAL[n >> 4];
}
}
@VisibleForTesting
static final int MAX_FACTORIAL = 170;
@VisibleForTesting
static final double[] EVERY_SIXTEENTH_FACTORIAL = {
0x1.0p0,
0x1.30777758p44,
0x1.956ad0aae33a4p117,
0x1.ee69a78d72cb6p202,
0x1.fe478ee34844ap295,
0x1.c619094edabffp394,
0x1.3638dd7bd6347p498,
0x1.7cac197cfe503p605,
0x1.1e5dfc140e1e5p716,
0x1.8ce85fadb707ep829,
0x1.95d5f3d928edep945};
/**
* Returns {@code true} if {@code a} and {@code b} are within {@code tolerance} of each other.
*
* <p>Technically speaking, this is equivalent to
* {@code Math.abs(a - b) <= tolerance || Double.valueOf(a).equals(Double.valueOf(b))}.
*
* <p>Notable special cases include:
* <ul>
* <li>All NaNs are fuzzily equal.
* <li>If {@code a == b}, then {@code a} and {@code b} are always fuzzily equal.
* <li>Positive and negative zero are always fuzzily equal.
* <li>If {@code tolerance} is zero, and neither {@code a} nor {@code b} is NaN, then
* {@code a} and {@code b} are fuzzily equal if and only if {@code a == b}.
* <li>With {@link Double#POSITIVE_INFINITY} tolerance, all non-NaN values are fuzzily equal.
* <li>With finite tolerance, {@code Double.POSITIVE_INFINITY} and {@code
* Double.NEGATIVE_INFINITY} are fuzzily equal only to themselves.
* </li>
*
* <p>This is reflexive and symmetric, but <em>not</em> transitive, so it is <em>not</em> an
* equivalence relation and <em>not</em> suitable for use in {@link Object#equals}
* implementations.
*
* @throws IllegalArgumentException if {@code tolerance} is {@code < 0} or NaN
* @since 13.0
*/
@Beta
public static boolean fuzzyEquals(double a, double b, double tolerance) {
MathPreconditions.checkNonNegative("tolerance", tolerance);
return
Math.copySign(a - b, 1.0) <= tolerance
// copySign(x, 1.0) is a branch-free version of abs(x), but with different NaN semantics
|| (a == b) // needed to ensure that infinities equal themselves
|| ((a != a) && (b != b)); // x != x is equivalent to Double.isNaN(x), but faster
}
/**
* Compares {@code a} and {@code b} "fuzzily," with a tolerance for nearly-equal values.
*
* <p>This method is equivalent to
* {@code fuzzyEquals(a, b, tolerance) ? 0 : Double.compare(a, b)}. In particular, like
* {@link Double#compare(double, double)}, it treats all NaN values as equal and greater than all
* other values (including {@link Double#POSITIVE_INFINITY}).
*
* <p>This is <em>not</em> a total ordering and is <em>not</em> suitable for use in
* {@link Comparable#compareTo} implementations. In particular, it is not transitive.
*
* @throws IllegalArgumentException if {@code tolerance} is {@code < 0} or NaN
* @since 13.0
*/
@Beta
public static int fuzzyCompare(double a, double b, double tolerance) {
if (fuzzyEquals(a, b, tolerance)) {
return 0;
} else if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return Booleans.compare(Double.isNaN(a), Double.isNaN(b));
}
}
private DoubleMath() {}
}
| 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.math;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.Double.MAX_EXPONENT;
import static java.lang.Double.MIN_EXPONENT;
import static java.lang.Double.POSITIVE_INFINITY;
import static java.lang.Double.doubleToRawLongBits;
import static java.lang.Double.isNaN;
import static java.lang.Double.longBitsToDouble;
import static java.lang.Math.getExponent;
import java.math.BigInteger;
/**
* Utilities for {@code double} primitives.
*
* @author Louis Wasserman
*/
final class DoubleUtils {
private DoubleUtils() {
}
static double nextDown(double d) {
return -Math.nextUp(-d);
}
// The mask for the significand, according to the {@link
// Double#doubleToRawLongBits(double)} spec.
static final long SIGNIFICAND_MASK = 0x000fffffffffffffL;
// The mask for the exponent, according to the {@link
// Double#doubleToRawLongBits(double)} spec.
static final long EXPONENT_MASK = 0x7ff0000000000000L;
// The mask for the sign, according to the {@link
// Double#doubleToRawLongBits(double)} spec.
static final long SIGN_MASK = 0x8000000000000000L;
static final int SIGNIFICAND_BITS = 52;
static final int EXPONENT_BIAS = 1023;
/**
* The implicit 1 bit that is omitted in significands of normal doubles.
*/
static final long IMPLICIT_BIT = SIGNIFICAND_MASK + 1;
static long getSignificand(double d) {
checkArgument(isFinite(d), "not a normal value");
int exponent = getExponent(d);
long bits = doubleToRawLongBits(d);
bits &= SIGNIFICAND_MASK;
return (exponent == MIN_EXPONENT - 1)
? bits << 1
: bits | IMPLICIT_BIT;
}
static boolean isFinite(double d) {
return getExponent(d) <= MAX_EXPONENT;
}
static boolean isNormal(double d) {
return getExponent(d) >= MIN_EXPONENT;
}
/*
* Returns x scaled by a power of 2 such that it is in the range [1, 2). Assumes x is positive,
* normal, and finite.
*/
static double scaleNormalize(double x) {
long significand = doubleToRawLongBits(x) & SIGNIFICAND_MASK;
return longBitsToDouble(significand | ONE_BITS);
}
static double bigToDouble(BigInteger x) {
// This is an extremely fast implementation of BigInteger.doubleValue(). JDK patch pending.
BigInteger absX = x.abs();
int exponent = absX.bitLength() - 1;
// exponent == floor(log2(abs(x)))
if (exponent < Long.SIZE - 1) {
return x.longValue();
} else if (exponent > MAX_EXPONENT) {
return x.signum() * POSITIVE_INFINITY;
}
/*
* We need the top SIGNIFICAND_BITS + 1 bits, including the "implicit" one bit. To make
* rounding easier, we pick out the top SIGNIFICAND_BITS + 2 bits, so we have one to help us
* round up or down. twiceSignifFloor will contain the top SIGNIFICAND_BITS + 2 bits, and
* signifFloor the top SIGNIFICAND_BITS + 1.
*
* It helps to consider the real number signif = absX * 2^(SIGNIFICAND_BITS - exponent).
*/
int shift = exponent - SIGNIFICAND_BITS - 1;
long twiceSignifFloor = absX.shiftRight(shift).longValue();
long signifFloor = twiceSignifFloor >> 1;
signifFloor &= SIGNIFICAND_MASK; // remove the implied bit
/*
* We round up if either the fractional part of signif is strictly greater than 0.5 (which is
* true if the 0.5 bit is set and any lower bit is set), or if the fractional part of signif is
* >= 0.5 and signifFloor is odd (which is true if both the 0.5 bit and the 1 bit are set).
*/
boolean increment = (twiceSignifFloor & 1) != 0
&& ((signifFloor & 1) != 0 || absX.getLowestSetBit() < shift);
long signifRounded = increment ? signifFloor + 1 : signifFloor;
long bits = (long) ((exponent + EXPONENT_BIAS)) << SIGNIFICAND_BITS;
bits += signifRounded;
/*
* If signifRounded == 2^53, we'd need to set all of the significand bits to zero and add 1 to
* the exponent. This is exactly the behavior we get from just adding signifRounded to bits
* directly. If the exponent is MAX_DOUBLE_EXPONENT, we round up (correctly) to
* Double.POSITIVE_INFINITY.
*/
bits |= x.signum() & SIGN_MASK;
return longBitsToDouble(bits);
}
/**
* Returns its argument if it is non-negative, zero if it is negative.
*/
static double ensureNonNegative(double value) {
checkArgument(!isNaN(value));
if (value > 0.0) {
return value;
} else {
return 0.0;
}
}
private static final long ONE_BITS = doubleToRawLongBits(1.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.math;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.math.BigInteger;
/**
* A collection of preconditions for math functions.
*
* @author Louis Wasserman
*/
@GwtCompatible
final class MathPreconditions {
static int checkPositive(String role, int x) {
if (x <= 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be > 0");
}
return x;
}
static long checkPositive(String role, long x) {
if (x <= 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be > 0");
}
return x;
}
static BigInteger checkPositive(String role, BigInteger x) {
if (x.signum() <= 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be > 0");
}
return x;
}
static int checkNonNegative(String role, int x) {
if (x < 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
}
return x;
}
static long checkNonNegative(String role, long x) {
if (x < 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
}
return x;
}
static BigInteger checkNonNegative(String role, BigInteger x) {
if (checkNotNull(x).signum() < 0) {
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
}
return x;
}
static double checkNonNegative(String role, double x) {
if (!(x >= 0)) {
throw new IllegalArgumentException(role + " (" + x + ") must be >= 0");
}
return x;
}
static void checkRoundingUnnecessary(boolean condition) {
if (!condition) {
throw new ArithmeticException("mode was UNNECESSARY, but rounding was necessary");
}
}
static void checkInRange(boolean condition) {
if (!condition) {
throw new ArithmeticException("not in range");
}
}
static void checkNoOverflow(boolean condition) {
if (!condition) {
throw new ArithmeticException("overflow");
}
}
private MathPreconditions() {}
}
| 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.math;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.math.RoundingMode.CEILING;
import static java.math.RoundingMode.FLOOR;
import static java.math.RoundingMode.HALF_EVEN;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
/**
* A class for arithmetic on values of type {@code BigInteger}.
*
* <p>The implementations of many methods in this class are based on material from Henry S. Warren,
* Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
*
* <p>Similar functionality for {@code int} and for {@code long} can be found in
* {@link IntMath} and {@link LongMath} respectively.
*
* @author Louis Wasserman
* @since 11.0
*/
@Beta
@GwtCompatible(emulated = true)
public final class BigIntegerMath {
/**
* Returns {@code true} if {@code x} represents a power of two.
*/
public static boolean isPowerOfTwo(BigInteger x) {
checkNotNull(x);
return x.signum() > 0 && x.getLowestSetBit() == x.bitLength() - 1;
}
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
public static int log2(BigInteger x, RoundingMode mode) {
checkPositive("x", checkNotNull(x));
int logFloor = x.bitLength() - 1;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through
case DOWN:
case FLOOR:
return logFloor;
case UP:
case CEILING:
return isPowerOfTwo(x) ? logFloor : logFloor + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
if (logFloor < SQRT2_PRECOMPUTE_THRESHOLD) {
BigInteger halfPower = SQRT2_PRECOMPUTED_BITS.shiftRight(
SQRT2_PRECOMPUTE_THRESHOLD - logFloor);
if (x.compareTo(halfPower) <= 0) {
return logFloor;
} else {
return logFloor + 1;
}
}
/*
* Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
*
* To determine which side of logFloor.5 the logarithm is, we compare x^2 to 2^(2 *
* logFloor + 1).
*/
BigInteger x2 = x.pow(2);
int logX2Floor = x2.bitLength() - 1;
return (logX2Floor < 2 * logFloor + 1) ? logFloor : logFloor + 1;
default:
throw new AssertionError();
}
}
/*
* The maximum number of bits in a square root for which we'll precompute an explicit half power
* of two. This can be any value, but higher values incur more class load time and linearly
* increasing memory consumption.
*/
@VisibleForTesting static final int SQRT2_PRECOMPUTE_THRESHOLD = 256;
@VisibleForTesting static final BigInteger SQRT2_PRECOMPUTED_BITS =
new BigInteger("16a09e667f3bcc908b2fb1366ea957d3e3adec17512775099da2f590b0667322a", 16);
/**
* Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of ten
*/
@GwtIncompatible("TODO")
@SuppressWarnings("fallthrough")
public static int log10(BigInteger x, RoundingMode mode) {
checkPositive("x", x);
if (fitsInLong(x)) {
return LongMath.log10(x.longValue(), mode);
}
int approxLog10 = (int) (log2(x, FLOOR) * LN_2 / LN_10);
BigInteger approxPow = BigInteger.TEN.pow(approxLog10);
int approxCmp = approxPow.compareTo(x);
/*
* We adjust approxLog10 and approxPow until they're equal to floor(log10(x)) and
* 10^floor(log10(x)).
*/
if (approxCmp > 0) {
/*
* The code is written so that even completely incorrect approximations will still yield the
* correct answer eventually, but in practice this branch should almost never be entered,
* and even then the loop should not run more than once.
*/
do {
approxLog10--;
approxPow = approxPow.divide(BigInteger.TEN);
approxCmp = approxPow.compareTo(x);
} while (approxCmp > 0);
} else {
BigInteger nextPow = BigInteger.TEN.multiply(approxPow);
int nextCmp = nextPow.compareTo(x);
while (nextCmp <= 0) {
approxLog10++;
approxPow = nextPow;
approxCmp = nextCmp;
nextPow = BigInteger.TEN.multiply(approxPow);
nextCmp = nextPow.compareTo(x);
}
}
int floorLog = approxLog10;
BigInteger floorPow = approxPow;
int floorCmp = approxCmp;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(floorCmp == 0);
// fall through
case FLOOR:
case DOWN:
return floorLog;
case CEILING:
case UP:
return floorPow.equals(x) ? floorLog : floorLog + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// Since sqrt(10) is irrational, log10(x) - floorLog can never be exactly 0.5
BigInteger x2 = x.pow(2);
BigInteger halfPowerSquared = floorPow.pow(2).multiply(BigInteger.TEN);
return (x2.compareTo(halfPowerSquared) <= 0) ? floorLog : floorLog + 1;
default:
throw new AssertionError();
}
}
private static final double LN_10 = Math.log(10);
private static final double LN_2 = Math.log(2);
/**
* Returns the square root of {@code x}, rounded with the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x < 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and
* {@code sqrt(x)} is not an integer
*/
@GwtIncompatible("TODO")
@SuppressWarnings("fallthrough")
public static BigInteger sqrt(BigInteger x, RoundingMode mode) {
checkNonNegative("x", x);
if (fitsInLong(x)) {
return BigInteger.valueOf(LongMath.sqrt(x.longValue(), mode));
}
BigInteger sqrtFloor = sqrtFloor(x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(sqrtFloor.pow(2).equals(x)); // fall through
case FLOOR:
case DOWN:
return sqrtFloor;
case CEILING:
case UP:
return sqrtFloor.pow(2).equals(x) ? sqrtFloor : sqrtFloor.add(BigInteger.ONE);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
BigInteger halfSquare = sqrtFloor.pow(2).add(sqrtFloor);
/*
* We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both
* x and halfSquare are integers, this is equivalent to testing whether or not x <=
* halfSquare.
*/
return (halfSquare.compareTo(x) >= 0) ? sqrtFloor : sqrtFloor.add(BigInteger.ONE);
default:
throw new AssertionError();
}
}
@GwtIncompatible("TODO")
private static BigInteger sqrtFloor(BigInteger x) {
/*
* Adapted from Hacker's Delight, Figure 11-1.
*
* Using DoubleUtils.bigToDouble, getting a double approximation of x is extremely fast, and
* then we can get a double approximation of the square root. Then, we iteratively improve this
* guess with an application of Newton's method, which sets guess := (guess + (x / guess)) / 2.
* This iteration has the following two properties:
*
* a) every iteration (except potentially the first) has guess >= floor(sqrt(x)). This is
* because guess' is the arithmetic mean of guess and x / guess, sqrt(x) is the geometric mean,
* and the arithmetic mean is always higher than the geometric mean.
*
* b) this iteration converges to floor(sqrt(x)). In fact, the number of correct digits doubles
* with each iteration, so this algorithm takes O(log(digits)) iterations.
*
* We start out with a double-precision approximation, which may be higher or lower than the
* true value. Therefore, we perform at least one Newton iteration to get a guess that's
* definitely >= floor(sqrt(x)), and then continue the iteration until we reach a fixed point.
*/
BigInteger sqrt0;
int log2 = log2(x, FLOOR);
if(log2 < Double.MAX_EXPONENT) {
sqrt0 = sqrtApproxWithDoubles(x);
} else {
int shift = (log2 - DoubleUtils.SIGNIFICAND_BITS) & ~1; // even!
/*
* We have that x / 2^shift < 2^54. Our initial approximation to sqrtFloor(x) will be
* 2^(shift/2) * sqrtApproxWithDoubles(x / 2^shift).
*/
sqrt0 = sqrtApproxWithDoubles(x.shiftRight(shift)).shiftLeft(shift >> 1);
}
BigInteger sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1);
if (sqrt0.equals(sqrt1)) {
return sqrt0;
}
do {
sqrt0 = sqrt1;
sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1);
} while (sqrt1.compareTo(sqrt0) < 0);
return sqrt0;
}
@GwtIncompatible("TODO")
private static BigInteger sqrtApproxWithDoubles(BigInteger x) {
return DoubleMath.roundToBigInteger(Math.sqrt(DoubleUtils.bigToDouble(x)), HALF_EVEN);
}
/**
* Returns the result of dividing {@code p} by {@code q}, rounding using the specified
* {@code RoundingMode}.
*
* @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
* is not an integer multiple of {@code b}
*/
@GwtIncompatible("TODO")
public static BigInteger divide(BigInteger p, BigInteger q, RoundingMode mode){
BigDecimal pDec = new BigDecimal(p);
BigDecimal qDec = new BigDecimal(q);
return pDec.divide(qDec, 0, mode).toBigIntegerExact();
}
/**
* Returns {@code n!}, that is, the product of the first {@code n} positive
* integers, or {@code 1} if {@code n == 0}.
*
* <p><b>Warning</b>: the result takes <i>O(n log n)</i> space, so use cautiously.
*
* <p>This uses an efficient binary recursive algorithm to compute the factorial
* with balanced multiplies. It also removes all the 2s from the intermediate
* products (shifting them back in at the end).
*
* @throws IllegalArgumentException if {@code n < 0}
*/
public static BigInteger factorial(int n) {
checkNonNegative("n", n);
// If the factorial is small enough, just use LongMath to do it.
if (n < LongMath.FACTORIALS.length) {
return BigInteger.valueOf(LongMath.FACTORIALS[n]);
}
// Pre-allocate space for our list of intermediate BigIntegers.
int approxSize = IntMath.divide(n * IntMath.log2(n, CEILING), Long.SIZE, CEILING);
ArrayList<BigInteger> bignums = new ArrayList<BigInteger>(approxSize);
// Start from the pre-computed maximum long factorial.
int startingNumber = LongMath.FACTORIALS.length;
long product = LongMath.FACTORIALS[startingNumber - 1];
// Strip off 2s from this value.
int shift = Long.numberOfTrailingZeros(product);
product >>= shift;
// Use floor(log2(num)) + 1 to prevent overflow of multiplication.
int productBits = LongMath.log2(product, FLOOR) + 1;
int bits = LongMath.log2(startingNumber, FLOOR) + 1;
// Check for the next power of two boundary, to save us a CLZ operation.
int nextPowerOfTwo = 1 << (bits - 1);
// Iteratively multiply the longs as big as they can go.
for (long num = startingNumber; num <= n; num++) {
// Check to see if the floor(log2(num)) + 1 has changed.
if ((num & nextPowerOfTwo) != 0) {
nextPowerOfTwo <<= 1;
bits++;
}
// Get rid of the 2s in num.
int tz = Long.numberOfTrailingZeros(num);
long normalizedNum = num >> tz;
shift += tz;
// Adjust floor(log2(num)) + 1.
int normalizedBits = bits - tz;
// If it won't fit in a long, then we store off the intermediate product.
if (normalizedBits + productBits >= Long.SIZE) {
bignums.add(BigInteger.valueOf(product));
product = 1;
productBits = 0;
}
product *= normalizedNum;
productBits = LongMath.log2(product, FLOOR) + 1;
}
// Check for leftovers.
if (product > 1) {
bignums.add(BigInteger.valueOf(product));
}
// Efficiently multiply all the intermediate products together.
return listProduct(bignums).shiftLeft(shift);
}
static BigInteger listProduct(List<BigInteger> nums) {
return listProduct(nums, 0, nums.size());
}
static BigInteger listProduct(List<BigInteger> nums, int start, int end) {
switch (end - start) {
case 0:
return BigInteger.ONE;
case 1:
return nums.get(start);
case 2:
return nums.get(start).multiply(nums.get(start + 1));
case 3:
return nums.get(start).multiply(nums.get(start + 1)).multiply(nums.get(start + 2));
default:
// Otherwise, split the list in half and recursively do this.
int m = (end + start) >>> 1;
return listProduct(nums, start, m).multiply(listProduct(nums, m, end));
}
}
/**
* Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
* {@code k}, that is, {@code n! / (k! (n - k)!)}.
*
* <p><b>Warning</b>: the result can take as much as <i>O(k log n)</i> space.
*
* @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n}
*/
public static BigInteger binomial(int n, int k) {
checkNonNegative("n", n);
checkNonNegative("k", k);
checkArgument(k <= n, "k (%s) > n (%s)", k, n);
if (k > (n >> 1)) {
k = n - k;
}
if (k < LongMath.BIGGEST_BINOMIALS.length && n <= LongMath.BIGGEST_BINOMIALS[k]) {
return BigInteger.valueOf(LongMath.binomial(n, k));
}
BigInteger accum = BigInteger.ONE;
long numeratorAccum = n;
long denominatorAccum = 1;
int bits = LongMath.log2(n, RoundingMode.CEILING);
int numeratorBits = bits;
for (int i = 1; i < k; i++) {
int p = n - i;
int q = i + 1;
// log2(p) >= bits - 1, because p >= n/2
if (numeratorBits + bits >= Long.SIZE - 1) {
// The numerator is as big as it can get without risking overflow.
// Multiply numeratorAccum / denominatorAccum into accum.
accum = accum
.multiply(BigInteger.valueOf(numeratorAccum))
.divide(BigInteger.valueOf(denominatorAccum));
numeratorAccum = p;
denominatorAccum = q;
numeratorBits = bits;
} else {
// We can definitely multiply into the long accumulators without overflowing them.
numeratorAccum *= p;
denominatorAccum *= q;
numeratorBits += bits;
}
}
return accum
.multiply(BigInteger.valueOf(numeratorAccum))
.divide(BigInteger.valueOf(denominatorAccum));
}
// Returns true if BigInteger.valueOf(x.longValue()).equals(x).
@GwtIncompatible("TODO")
static boolean fitsInLong(BigInteger x) {
return x.bitLength() <= Long.SIZE - 1;
}
private BigIntegerMath() {}
}
| 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.math;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.math.MathPreconditions.checkNoOverflow;
import static com.google.common.math.MathPreconditions.checkNonNegative;
import static com.google.common.math.MathPreconditions.checkPositive;
import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import java.math.BigInteger;
import java.math.RoundingMode;
/**
* A class for arithmetic on values of type {@code int}. Where possible, methods are defined and
* named analogously to their {@code BigInteger} counterparts.
*
* <p>The implementations of many methods in this class are based on material from Henry S. Warren,
* Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002).
*
* <p>Similar functionality for {@code long} and for {@link BigInteger} can be found in
* {@link LongMath} and {@link BigIntegerMath} respectively. For other common operations on
* {@code int} values, see {@link com.google.common.primitives.Ints}.
*
* @author Louis Wasserman
* @since 11.0
*/
@Beta
@GwtCompatible(emulated = true)
public final class IntMath {
// NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, ||
/**
* Returns {@code true} if {@code x} represents a power of two.
*
* <p>This differs from {@code Integer.bitCount(x) == 1}, because
* {@code Integer.bitCount(Integer.MIN_VALUE) == 1}, but {@link Integer#MIN_VALUE} is not a power
* of two.
*/
public static boolean isPowerOfTwo(int x) {
return x > 0 & (x & (x - 1)) == 0;
}
/**
* Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of two
*/
@SuppressWarnings("fallthrough")
public static int log2(int x, RoundingMode mode) {
checkPositive("x", x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(isPowerOfTwo(x));
// fall through
case DOWN:
case FLOOR:
return (Integer.SIZE - 1) - Integer.numberOfLeadingZeros(x);
case UP:
case CEILING:
return Integer.SIZE - Integer.numberOfLeadingZeros(x - 1);
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5
int leadingZeros = Integer.numberOfLeadingZeros(x);
int cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros;
// floor(2^(logFloor + 0.5))
int logFloor = (Integer.SIZE - 1) - leadingZeros;
return (x <= cmp) ? logFloor : logFloor + 1;
default:
throw new AssertionError();
}
}
/** The biggest half power of two that can fit in an unsigned int. */
@VisibleForTesting static final int MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333;
/**
* Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x <= 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x}
* is not a power of ten
*/
@GwtIncompatible("need BigIntegerMath to adequately test")
@SuppressWarnings("fallthrough")
public static int log10(int x, RoundingMode mode) {
checkPositive("x", x);
int logFloor = log10Floor(x);
int floorPow = POWERS_OF_10[logFloor];
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(x == floorPow);
// fall through
case FLOOR:
case DOWN:
return logFloor;
case CEILING:
case UP:
return (x == floorPow) ? logFloor : logFloor + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
// sqrt(10) is irrational, so log10(x) - logFloor is never exactly 0.5
return (x <= HALF_POWERS_OF_10[logFloor]) ? logFloor : logFloor + 1;
default:
throw new AssertionError();
}
}
private static int log10Floor(int x) {
/*
* Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation.
*
* The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))),
* we can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x))
* is 6, then 64 <= x < 128, so floor(log10(x)) is either 1 or 2.
*/
int y = MAX_LOG10_FOR_LEADING_ZEROS[Integer.numberOfLeadingZeros(x)];
// y is the higher of the two possible values of floor(log10(x))
int sgn = (x - POWERS_OF_10[y]) >>> (Integer.SIZE - 1);
/*
* sgn is the sign bit of x - 10^y; it is 1 if x < 10^y, and 0 otherwise. If x < 10^y, then we
* want the lower of the two possible values, or y - 1, otherwise, we want y.
*/
return y - sgn;
}
// MAX_LOG10_FOR_LEADING_ZEROS[i] == floor(log10(2^(Long.SIZE - i)))
@VisibleForTesting static final byte[] MAX_LOG10_FOR_LEADING_ZEROS = {9, 9, 9, 8, 8, 8,
7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0};
@VisibleForTesting static final int[] POWERS_OF_10 = {1, 10, 100, 1000, 10000,
100000, 1000000, 10000000, 100000000, 1000000000};
// HALF_POWERS_OF_10[i] = largest int less than 10^(i + 0.5)
@VisibleForTesting static final int[] HALF_POWERS_OF_10 =
{3, 31, 316, 3162, 31622, 316227, 3162277, 31622776, 316227766, Integer.MAX_VALUE};
/**
* Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to
* {@code BigInteger.valueOf(b).pow(k).intValue()}. This implementation runs in {@code O(log k)}
* time.
*
* <p>Compare {@link #checkedPow}, which throws an {@link ArithmeticException} upon overflow.
*
* @throws IllegalArgumentException if {@code k < 0}
*/
@GwtIncompatible("failing tests")
public static int pow(int b, int k) {
checkNonNegative("exponent", k);
switch (b) {
case 0:
return (k == 0) ? 1 : 0;
case 1:
return 1;
case (-1):
return ((k & 1) == 0) ? 1 : -1;
case 2:
return (k < Integer.SIZE) ? (1 << k) : 0;
case (-2):
if (k < Integer.SIZE) {
return ((k & 1) == 0) ? (1 << k) : -(1 << k);
} else {
return 0;
}
}
for (int accum = 1;; k >>= 1) {
switch (k) {
case 0:
return accum;
case 1:
return b * accum;
default:
accum *= ((k & 1) == 0) ? 1 : b;
b *= b;
}
}
}
/**
* Returns the square root of {@code x}, rounded with the specified rounding mode.
*
* @throws IllegalArgumentException if {@code x < 0}
* @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and
* {@code sqrt(x)} is not an integer
*/
@GwtIncompatible("need BigIntegerMath to adequately test")
@SuppressWarnings("fallthrough")
public static int sqrt(int x, RoundingMode mode) {
checkNonNegative("x", x);
int sqrtFloor = sqrtFloor(x);
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(sqrtFloor * sqrtFloor == x); // fall through
case FLOOR:
case DOWN:
return sqrtFloor;
case CEILING:
case UP:
return (sqrtFloor * sqrtFloor == x) ? sqrtFloor : sqrtFloor + 1;
case HALF_DOWN:
case HALF_UP:
case HALF_EVEN:
int halfSquare = sqrtFloor * sqrtFloor + sqrtFloor;
/*
* We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25.
* Since both x and halfSquare are integers, this is equivalent to testing whether or not
* x <= halfSquare. (We have to deal with overflow, though.)
*/
return (x <= halfSquare | halfSquare < 0) ? sqrtFloor : sqrtFloor + 1;
default:
throw new AssertionError();
}
}
private static int sqrtFloor(int x) {
// There is no loss of precision in converting an int to a double, according to
// http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2
return (int) Math.sqrt(x);
}
/**
* Returns the result of dividing {@code p} by {@code q}, rounding using the specified
* {@code RoundingMode}.
*
* @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a}
* is not an integer multiple of {@code b}
*/
@SuppressWarnings("fallthrough")
public static int divide(int p, int q, RoundingMode mode) {
checkNotNull(mode);
if (q == 0) {
throw new ArithmeticException("/ by zero"); // for GWT
}
int div = p / q;
int rem = p - q * div; // equal to p % q
if (rem == 0) {
return div;
}
/*
* Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to
* deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of
* p / q.
*
* signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise.
*/
int signum = 1 | ((p ^ q) >> (Integer.SIZE - 1));
boolean increment;
switch (mode) {
case UNNECESSARY:
checkRoundingUnnecessary(rem == 0);
// fall through
case DOWN:
increment = false;
break;
case UP:
increment = true;
break;
case CEILING:
increment = signum > 0;
break;
case FLOOR:
increment = signum < 0;
break;
case HALF_EVEN:
case HALF_DOWN:
case HALF_UP:
int absRem = abs(rem);
int cmpRemToHalfDivisor = absRem - (abs(q) - absRem);
// subtracting two nonnegative ints can't overflow
// cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2).
if (cmpRemToHalfDivisor == 0) { // exactly on the half mark
increment = (mode == HALF_UP || (mode == HALF_EVEN & (div & 1) != 0));
} else {
increment = cmpRemToHalfDivisor > 0; // closer to the UP value
}
break;
default:
throw new AssertionError();
}
return increment ? div + signum : div;
}
/**
* Returns {@code x mod m}. This differs from {@code x % m} in that it always returns a
* non-negative result.
*
* <p>For example:<pre> {@code
*
* mod(7, 4) == 3
* mod(-7, 4) == 1
* mod(-1, 4) == 3
* mod(-8, 4) == 0
* mod(8, 4) == 0}</pre>
*
* @throws ArithmeticException if {@code m <= 0}
*/
public static int mod(int x, int m) {
if (m <= 0) {
throw new ArithmeticException("Modulus " + m + " must be > 0");
}
int result = x % m;
return (result >= 0) ? result : result + m;
}
/**
* Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if
* {@code a == 0 && b == 0}.
*
* @throws IllegalArgumentException if {@code a < 0} or {@code b < 0}
*/
public static int gcd(int a, int b) {
/*
* The reason we require both arguments to be >= 0 is because otherwise, what do you return on
* gcd(0, Integer.MIN_VALUE)? BigInteger.gcd would return positive 2^31, but positive 2^31
* isn't an int.
*/
checkNonNegative("a", a);
checkNonNegative("b", b);
if (a == 0) {
// 0 % b == 0, so b divides a, but the converse doesn't hold.
// BigInteger.gcd is consistent with this decision.
return b;
} else if (b == 0) {
return a; // similar logic
}
/*
* Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm.
* This is >40% faster than the Euclidean algorithm in benchmarks.
*/
int aTwos = Integer.numberOfTrailingZeros(a);
a >>= aTwos; // divide out all 2s
int bTwos = Integer.numberOfTrailingZeros(b);
b >>= bTwos; // divide out all 2s
while (a != b) { // both a, b are odd
// The key to the binary GCD algorithm is as follows:
// Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b).
// But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two.
// We bend over backwards to avoid branching, adapting a technique from
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
int delta = a - b; // can't overflow, since a and b are nonnegative
int minDeltaOrZero = delta & (delta >> (Integer.SIZE - 1));
// equivalent to Math.min(delta, 0)
a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b)
// a is now nonnegative and even
b += minDeltaOrZero; // sets b to min(old a, b)
a >>= Integer.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b
}
return a << min(aTwos, bTwos);
}
/**
* Returns the sum of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a + b} overflows in signed {@code int} arithmetic
*/
public static int checkedAdd(int a, int b) {
long result = (long) a + b;
checkNoOverflow(result == (int) result);
return (int) result;
}
/**
* Returns the difference of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a - b} overflows in signed {@code int} arithmetic
*/
public static int checkedSubtract(int a, int b) {
long result = (long) a - b;
checkNoOverflow(result == (int) result);
return (int) result;
}
/**
* Returns the product of {@code a} and {@code b}, provided it does not overflow.
*
* @throws ArithmeticException if {@code a * b} overflows in signed {@code int} arithmetic
*/
public static int checkedMultiply(int a, int b) {
long result = (long) a * b;
checkNoOverflow(result == (int) result);
return (int) result;
}
/**
* Returns the {@code b} to the {@code k}th power, provided it does not overflow.
*
* <p>{@link #pow} may be faster, but does not check for overflow.
*
* @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed
* {@code int} arithmetic
*/
public static int checkedPow(int b, int k) {
checkNonNegative("exponent", k);
switch (b) {
case 0:
return (k == 0) ? 1 : 0;
case 1:
return 1;
case (-1):
return ((k & 1) == 0) ? 1 : -1;
case 2:
checkNoOverflow(k < Integer.SIZE - 1);
return 1 << k;
case (-2):
checkNoOverflow(k < Integer.SIZE);
return ((k & 1) == 0) ? 1 << k : -1 << k;
}
int accum = 1;
while (true) {
switch (k) {
case 0:
return accum;
case 1:
return checkedMultiply(accum, b);
default:
if ((k & 1) != 0) {
accum = checkedMultiply(accum, b);
}
k >>= 1;
if (k > 0) {
checkNoOverflow(-FLOOR_SQRT_MAX_INT <= b & b <= FLOOR_SQRT_MAX_INT);
b *= b;
}
}
}
}
@VisibleForTesting static final int FLOOR_SQRT_MAX_INT = 46340;
/**
* Returns {@code n!}, that is, the product of the first {@code n} positive
* integers, {@code 1} if {@code n == 0}, or {@link Integer#MAX_VALUE} if the
* result does not fit in a {@code int}.
*
* @throws IllegalArgumentException if {@code n < 0}
*/
public static int factorial(int n) {
checkNonNegative("n", n);
return (n < FACTORIALS.length) ? FACTORIALS[n] : Integer.MAX_VALUE;
}
static final int[] FACTORIALS = {
1,
1,
1 * 2,
1 * 2 * 3,
1 * 2 * 3 * 4,
1 * 2 * 3 * 4 * 5,
1 * 2 * 3 * 4 * 5 * 6,
1 * 2 * 3 * 4 * 5 * 6 * 7,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12};
/**
* Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and
* {@code k}, or {@link Integer#MAX_VALUE} if the result does not fit in an {@code int}.
*
* @throws IllegalArgumentException if {@code n < 0}, {@code k < 0} or {@code k > n}
*/
@GwtIncompatible("need BigIntegerMath to adequately test")
public static int binomial(int n, int k) {
checkNonNegative("n", n);
checkNonNegative("k", k);
checkArgument(k <= n, "k (%s) > n (%s)", k, n);
if (k > (n >> 1)) {
k = n - k;
}
if (k >= BIGGEST_BINOMIALS.length || n > BIGGEST_BINOMIALS[k]) {
return Integer.MAX_VALUE;
}
switch (k) {
case 0:
return 1;
case 1:
return n;
default:
long result = 1;
for (int i = 0; i < k; i++) {
result *= n - i;
result /= i + 1;
}
return (int) result;
}
}
// binomial(BIGGEST_BINOMIALS[k], k) fits in an int, but not binomial(BIGGEST_BINOMIALS[k]+1,k).
@VisibleForTesting static int[] BIGGEST_BINOMIALS = {
Integer.MAX_VALUE,
Integer.MAX_VALUE,
65536,
2345,
477,
193,
110,
75,
58,
49,
43,
39,
37,
35,
34,
34,
33
};
/**
* Returns the arithmetic mean of {@code x} and {@code y}, rounded towards
* negative infinity. This method is overflow resilient.
*
* @since 14.0
*/
public static int mean(int x, int y) {
// Efficient method for computing the arithmetic mean.
// The alternative (x + y) / 2 fails for large values.
// The alternative (x + y) >>> 1 fails for negative values.
return (x & y) + ((x ^ y) >> 1);
}
private IntMath() {}
}
| 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.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static java.lang.Float.NEGATIVE_INFINITY;
import static java.lang.Float.POSITIVE_INFINITY;
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.AbstractList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@code float} primitives, that are not
* already found in either {@link Float} or {@link Arrays}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Floats {
private Floats() {}
/**
* The number of bytes required to represent a primitive {@code float}
* value.
*
* @since 10.0
*/
public static final int BYTES = Float.SIZE / Byte.SIZE;
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Float) value).hashCode()}.
*
* @param value a primitive {@code float} value
* @return a hash code for the value
*/
public static int hashCode(float value) {
// TODO(kevinb): is there a better way, that's still gwt-safe?
return ((Float) value).hashCode();
}
/**
* Compares the two specified {@code float} values using {@link
* Float#compare(float, float)}. You may prefer to invoke that method
* directly; this method exists only for consistency with the other utilities
* in this package.
*
* @param a the first {@code float} to compare
* @param b the second {@code float} to compare
* @return the result of invoking {@link Float#compare(float, float)}
*/
public static int compare(float a, float b) {
return Float.compare(a, b);
}
/**
* Returns {@code true} if {@code value} represents a real number. This is
* equivalent to, but not necessarily implemented as,
* {@code !(Float.isInfinite(value) || Float.isNaN(value))}.
*
* @since 10.0
*/
public static boolean isFinite(float value) {
return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY;
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}. Note that this always returns {@code false} when {@code
* target} is {@code NaN}.
*
* @param array an array of {@code float} values, possibly empty
* @param target a primitive {@code float} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(float[] array, float target) {
for (float value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}. Note that this always returns {@code -1} when {@code target}
* is {@code NaN}.
*
* @param array an array of {@code float} values, possibly empty
* @param target a primitive {@code float} value
* @return the least index {@code i} for which {@code array[i] == target}, or
* {@code -1} if no such index exists.
*/
public static int indexOf(float[] array, float target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
float[] array, float target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the start position of the first occurrence of the specified {@code
* target} within {@code array}, or {@code -1} if there is no such occurrence.
*
* <p>More formally, returns the lowest index {@code i} such that {@code
* java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
* the same elements as {@code target}.
*
* <p>Note that this always returns {@code -1} when {@code target} contains
* {@code NaN}.
*
* @param array the array to search for the sequence {@code target}
* @param target the array to search for as a sub-sequence of {@code array}
*/
public static int indexOf(float[] array, float[] target) {
checkNotNull(array, "array");
checkNotNull(target, "target");
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Returns the index of the last appearance of the value {@code target} in
* {@code array}. Note that this always returns {@code -1} when {@code target}
* is {@code NaN}.
*
* @param array an array of {@code float} values, possibly empty
* @param target a primitive {@code float} value
* @return the greatest index {@code i} for which {@code array[i] == target},
* or {@code -1} if no such index exists.
*/
public static int lastIndexOf(float[] array, float target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
float[] array, float target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the least value present in {@code array}, using the same rules of
* comparison as {@link Math#min(float, float)}.
*
* @param array a <i>nonempty</i> array of {@code float} values
* @return the value present in {@code array} that is less than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static float min(float... array) {
checkArgument(array.length > 0);
float min = array[0];
for (int i = 1; i < array.length; i++) {
min = Math.min(min, array[i]);
}
return min;
}
/**
* Returns the greatest value present in {@code array}, using the same rules
* of comparison as {@link Math#min(float, float)}.
*
* @param array a <i>nonempty</i> array of {@code float} values
* @return the value present in {@code array} that is greater than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static float max(float... array) {
checkArgument(array.length > 0);
float max = array[0];
for (int i = 1; i < array.length; i++) {
max = Math.max(max, array[i]);
}
return max;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new float[] {a, b}, new float[] {}, new
* float[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code float} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static float[] concat(float[]... arrays) {
int length = 0;
for (float[] array : arrays) {
length += array.length;
}
float[] result = new float[length];
int pos = 0;
for (float[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static float[] ensureCapacity(
float[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static float[] copyOf(float[] original, int length) {
float[] copy = new float[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code float} values, converted
* to strings as specified by {@link Float#toString(float)}, and separated by
* {@code separator}. For example, {@code join("-", 1.0f, 2.0f, 3.0f)}
* returns the string {@code "1.0-2.0-3.0"}.
*
* <p>Note that {@link Float#toString(float)} formats {@code float}
* differently in GWT. In the previous example, it returns the string {@code
* "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code float} values, possibly empty
*/
public static String join(String separator, float... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 12);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code float} arrays
* lexicographically. That is, it compares, using {@link
* #compare(float, float)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example, {@code [] < [1.0f] < [1.0f, 2.0f]
* < [2.0f]}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(float[], float[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<float[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<float[]> {
INSTANCE;
@Override
public int compare(float[] left, float[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Floats.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code float} value in the manner of {@link Number#floatValue}.
*
* <p>Elements are copied from the argument collection as if by {@code
* collection.toArray()}. Calling this method is as thread-safe as calling
* that method.
*
* @param collection a collection of {@code Number} instances
* @return an array containing the same values as {@code collection}, in the
* same order, converted to primitives
* @throws NullPointerException if {@code collection} or any of its elements
* is null
* @since 1.0 (parameter was {@code Collection<Float>} before 12.0)
*/
public static float[] toArray(Collection<? extends Number> collection) {
if (collection instanceof FloatArrayAsList) {
return ((FloatArrayAsList) collection).toFloatArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
float[] array = new float[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).floatValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Float} objects written to or read from it. For example, whether
* {@code list.get(0) == list.get(0)} is true for the returned list is
* unspecified.
*
* <p>The returned list may have unexpected behavior if it contains {@code
* NaN}, or if {@code NaN} is used as a parameter to any of its methods.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Float> asList(float... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new FloatArrayAsList(backingArray);
}
@GwtCompatible
private static class FloatArrayAsList extends AbstractList<Float>
implements RandomAccess, Serializable {
final float[] array;
final int start;
final int end;
FloatArrayAsList(float[] array) {
this(array, 0, array.length);
}
FloatArrayAsList(float[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Float get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Float)
&& Floats.indexOf(array, (Float) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Float) {
int i = Floats.indexOf(array, (Float) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Float) {
int i = Floats.lastIndexOf(array, (Float) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Float set(int index, Float element) {
checkElementIndex(index, size());
float oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Float> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new FloatArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof FloatArrayAsList) {
FloatArrayAsList that = (FloatArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Floats.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 12);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
float[] toFloatArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
float[] result = new float[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
private static final long serialVersionUID = 0;
}
/**
* Parses the specified string as a single-precision floating point value.
* The ASCII character {@code '-'} (<code>'\u002D'</code>) is recognized
* as the minus sign.
*
* <p>Unlike {@link Float#parseFloat(String)}, this method returns
* {@code null} instead of throwing an exception if parsing fails.
* Valid inputs are exactly those accepted by {@link Float#valueOf(String)},
* except that leading and trailing whitespace is not permitted.
*
* <p>This implementation is likely to be faster than {@code
* Float.parseFloat} if many failures are expected.
*
* @param string the string representation of a {@code float} value
* @return the floating point value represented by {@code string}, or
* {@code null} if {@code string} has a length of zero or cannot be
* parsed as a {@code float} value
* @since 14.0
*/
@GwtIncompatible("regular expressions")
@Nullable
@Beta
public static Float tryParse(String string) {
if (Doubles.FLOATING_POINT_PATTERN.matcher(string).matches()) {
// TODO(user): could be potentially optimized, but only with
// extensive testing
try {
return Float.parseFloat(string);
} catch (NumberFormatException e) {
// Float.parseFloat has changed specs several times, so fall through
// gracefully
}
}
return null;
}
}
| 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.
*/
/**
* Static utilities for working with the eight primitive types and {@code void},
* and value types for treating them as unsigned.
*
* <p>This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* <h2>Contents</h2>
*
* <h3>General static utilities</h3>
*
* <ul>
* <li>{@link com.google.common.primitives.Primitives}
* </ul>
*
* <h3>Per-type static utilities</h3>
*
* <ul>
* <li>{@link com.google.common.primitives.Booleans}
* <li>{@link com.google.common.primitives.Bytes}
* <ul>
* <li>{@link com.google.common.primitives.SignedBytes}
* <li>{@link com.google.common.primitives.UnsignedBytes}
* </ul>
* <li>{@link com.google.common.primitives.Chars}
* <li>{@link com.google.common.primitives.Doubles}
* <li>{@link com.google.common.primitives.Floats}
* <li>{@link com.google.common.primitives.Ints}
* <ul>
* <li>{@link com.google.common.primitives.UnsignedInts}
* </ul>
* <li>{@link com.google.common.primitives.Longs}
* <ul>
* <li>{@link com.google.common.primitives.UnsignedLongs}
* </ul>
* <li>{@link com.google.common.primitives.Shorts}
* </ul>
*
* <h3>Value types</h3>
* <ul>
* <li>{@link com.google.common.primitives.UnsignedInteger}
* <li>{@link com.google.common.primitives.UnsignedLong}
* </ul>
*/
@ParametersAreNonnullByDefault
package com.google.common.primitives;
import javax.annotation.ParametersAreNonnullByDefault;
| 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.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
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.AbstractList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
import javax.annotation.CheckForNull;
/**
* Static utility methods pertaining to {@code int} primitives, that are not
* already found in either {@link Integer} or {@link Arrays}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Ints {
private Ints() {}
/**
* The number of bytes required to represent a primitive {@code int}
* value.
*/
public static final int BYTES = Integer.SIZE / Byte.SIZE;
/**
* The largest power of two that can be represented as an {@code int}.
*
* @since 10.0
*/
public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2);
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Integer) value).hashCode()}.
*
* @param value a primitive {@code int} value
* @return a hash code for the value
*/
public static int hashCode(int value) {
return value;
}
/**
* Returns the {@code int} value that is equal to {@code value}, if possible.
*
* @param value any value in the range of the {@code int} type
* @return the {@code int} value that equals {@code value}
* @throws IllegalArgumentException if {@code value} is greater than {@link
* Integer#MAX_VALUE} or less than {@link Integer#MIN_VALUE}
*/
public static int checkedCast(long value) {
int result = (int) value;
checkArgument(result == value, "Out of range: %s", value);
return result;
}
/**
* Returns the {@code int} nearest in value to {@code value}.
*
* @param value any {@code long} value
* @return the same value cast to {@code int} if it is in the range of the
* {@code int} type, {@link Integer#MAX_VALUE} if it is too large,
* or {@link Integer#MIN_VALUE} if it is too small
*/
public static int saturatedCast(long value) {
if (value > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (value < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int) value;
}
/**
* Compares the two specified {@code int} values. The sign of the value
* returned is the same as that of {@code ((Integer) a).compareTo(b)}.
*
* @param a the first {@code int} to compare
* @param b the second {@code int} to compare
* @return a negative value if {@code a} is less than {@code b}; a positive
* value if {@code a} is greater than {@code b}; or zero if they are equal
*/
public static int compare(int a, int b) {
return (a < b) ? -1 : ((a > b) ? 1 : 0);
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}.
*
* @param array an array of {@code int} values, possibly empty
* @param target a primitive {@code int} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(int[] array, int target) {
for (int value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code int} values, possibly empty
* @param target a primitive {@code int} value
* @return the least index {@code i} for which {@code array[i] == target}, or
* {@code -1} if no such index exists.
*/
public static int indexOf(int[] array, int target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
int[] array, int target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the start position of the first occurrence of the specified {@code
* target} within {@code array}, or {@code -1} if there is no such occurrence.
*
* <p>More formally, returns the lowest index {@code i} such that {@code
* java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
* the same elements as {@code target}.
*
* @param array the array to search for the sequence {@code target}
* @param target the array to search for as a sub-sequence of {@code array}
*/
public static int indexOf(int[] array, int[] target) {
checkNotNull(array, "array");
checkNotNull(target, "target");
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Returns the index of the last appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code int} values, possibly empty
* @param target a primitive {@code int} value
* @return the greatest index {@code i} for which {@code array[i] == target},
* or {@code -1} if no such index exists.
*/
public static int lastIndexOf(int[] array, int target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
int[] array, int target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the least value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code int} values
* @return the value present in {@code array} that is less than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static int min(int... array) {
checkArgument(array.length > 0);
int min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
/**
* Returns the greatest value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code int} values
* @return the value present in {@code array} that is greater than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static int max(int... array) {
checkArgument(array.length > 0);
int max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new int[] {a, b}, new int[] {}, new
* int[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code int} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static int[] concat(int[]... arrays) {
int length = 0;
for (int[] array : arrays) {
length += array.length;
}
int[] result = new int[length];
int pos = 0;
for (int[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns a big-endian representation of {@code value} in a 4-element byte
* array; equivalent to {@code ByteBuffer.allocate(4).putInt(value).array()}.
* For example, the input value {@code 0x12131415} would yield the byte array
* {@code {0x12, 0x13, 0x14, 0x15}}.
*
* <p>If you need to convert and concatenate several values (possibly even of
* different types), use a shared {@link java.nio.ByteBuffer} instance, or use
* {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable
* buffer.
*/
@GwtIncompatible("doesn't work")
public static byte[] toByteArray(int value) {
return new byte[] {
(byte) (value >> 24),
(byte) (value >> 16),
(byte) (value >> 8),
(byte) value};
}
/**
* Returns the {@code int} value whose big-endian representation is stored in
* the first 4 bytes of {@code bytes}; equivalent to {@code
* ByteBuffer.wrap(bytes).getInt()}. For example, the input byte array {@code
* {0x12, 0x13, 0x14, 0x15, 0x33}} would yield the {@code int} value {@code
* 0x12131415}.
*
* <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that
* library exposes much more flexibility at little cost in readability.
*
* @throws IllegalArgumentException if {@code bytes} has fewer than 4 elements
*/
@GwtIncompatible("doesn't work")
public static int fromByteArray(byte[] bytes) {
checkArgument(bytes.length >= BYTES,
"array too small: %s < %s", bytes.length, BYTES);
return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3]);
}
/**
* Returns the {@code int} value whose byte representation is the given 4
* bytes, in big-endian order; equivalent to {@code Ints.fromByteArray(new
* byte[] {b1, b2, b3, b4})}.
*
* @since 7.0
*/
@GwtIncompatible("doesn't work")
public static int fromBytes(byte b1, byte b2, byte b3, byte b4) {
return b1 << 24 | (b2 & 0xFF) << 16 | (b3 & 0xFF) << 8 | (b4 & 0xFF);
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static int[] ensureCapacity(
int[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static int[] copyOf(int[] original, int length) {
int[] copy = new int[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code int} values separated
* by {@code separator}. For example, {@code join("-", 1, 2, 3)} returns
* the string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code int} values, possibly empty
*/
public static String join(String separator, int... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 5);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code int} arrays
* lexicographically. That is, it compares, using {@link
* #compare(int, int)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example, {@code [] < [1] < [1, 2] < [2]}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(int[], int[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<int[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<int[]> {
INSTANCE;
@Override
public int compare(int[] left, int[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Ints.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code int} value in the manner of {@link Number#intValue}.
*
* <p>Elements are copied from the argument collection as if by {@code
* collection.toArray()}. Calling this method is as thread-safe as calling
* that method.
*
* @param collection a collection of {@code Number} instances
* @return an array containing the same values as {@code collection}, in the
* same order, converted to primitives
* @throws NullPointerException if {@code collection} or any of its elements
* is null
* @since 1.0 (parameter was {@code Collection<Integer>} before 12.0)
*/
public static int[] toArray(Collection<? extends Number> collection) {
if (collection instanceof IntArrayAsList) {
return ((IntArrayAsList) collection).toIntArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
int[] array = new int[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).intValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Integer} objects written to or read from it. For example, whether
* {@code list.get(0) == list.get(0)} is true for the returned list is
* unspecified.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Integer> asList(int... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new IntArrayAsList(backingArray);
}
@GwtCompatible
private static class IntArrayAsList extends AbstractList<Integer>
implements RandomAccess, Serializable {
final int[] array;
final int start;
final int end;
IntArrayAsList(int[] array) {
this(array, 0, array.length);
}
IntArrayAsList(int[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Integer get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Integer)
&& Ints.indexOf(array, (Integer) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Integer) {
int i = Ints.indexOf(array, (Integer) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Integer) {
int i = Ints.lastIndexOf(array, (Integer) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Integer set(int index, Integer element) {
checkElementIndex(index, size());
int oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Integer> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new IntArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof IntArrayAsList) {
IntArrayAsList that = (IntArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Ints.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 5);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
int[] toIntArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
int[] result = new int[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
private static final long serialVersionUID = 0;
}
/**
* Parses the specified string as a signed decimal integer value. The ASCII
* character {@code '-'} (<code>'\u002D'</code>) is recognized as the
* minus sign.
*
* <p>Unlike {@link Integer#parseInt(String)}, this method returns
* {@code null} instead of throwing an exception if parsing fails.
*
* <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even
* under JDK 7, despite the change to {@link Integer#parseInt(String)} for
* that version.
*
* @param string the string representation of an integer value
* @return the integer value represented by {@code string}, or {@code null} if
* {@code string} has a length of zero or cannot be parsed as an integer
* value
* @since 11.0
*/
@Beta
@CheckForNull
@GwtIncompatible("TODO")
public static Integer tryParse(String string) {
return AndroidInteger.tryParse(string, 10);
}
}
| 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.primitives;
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 sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.nio.ByteOrder;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Comparator;
/**
* Static utility methods pertaining to {@code byte} primitives that interpret
* values as <i>unsigned</i> (that is, any negative value {@code b} is treated
* as the positive value {@code 256 + b}). The corresponding methods that treat
* the values as signed are found in {@link SignedBytes}, and the methods for
* which signedness is not an issue are in {@link Bytes}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @author Martin Buchholz
* @author Hiroshi Yamauchi
* @author Louis Wasserman
* @since 1.0
*/
public final class UnsignedBytes {
private UnsignedBytes() {}
/**
* The largest power of two that can be represented as an unsigned {@code
* byte}.
*
* @since 10.0
*/
public static final byte MAX_POWER_OF_TWO = (byte) 0x80;
/**
* The largest value that fits into an unsigned byte.
*
* @since 13.0
*/
public static final byte MAX_VALUE = (byte) 0xFF;
private static final int UNSIGNED_MASK = 0xFF;
/**
* Returns the value of the given byte as an integer, when treated as
* unsigned. That is, returns {@code value + 256} if {@code value} is
* negative; {@code value} itself otherwise.
*
* @since 6.0
*/
public static int toInt(byte value) {
return value & UNSIGNED_MASK;
}
/**
* Returns the {@code byte} value that, when treated as unsigned, is equal to
* {@code value}, if possible.
*
* @param value a value between 0 and 255 inclusive
* @return the {@code byte} value that, when treated as unsigned, equals
* {@code value}
* @throws IllegalArgumentException if {@code value} is negative or greater
* than 255
*/
public static byte checkedCast(long value) {
checkArgument(value >> Byte.SIZE == 0, "out of range: %s", value);
return (byte) value;
}
/**
* Returns the {@code byte} value that, when treated as unsigned, is nearest
* in value to {@code value}.
*
* @param value any {@code long} value
* @return {@code (byte) 255} if {@code value >= 255}, {@code (byte) 0} if
* {@code value <= 0}, and {@code value} cast to {@code byte} otherwise
*/
public static byte saturatedCast(long value) {
if (value > toInt(MAX_VALUE)) {
return MAX_VALUE; // -1
}
if (value < 0) {
return (byte) 0;
}
return (byte) value;
}
/**
* Compares the two specified {@code byte} values, treating them as unsigned
* values between 0 and 255 inclusive. For example, {@code (byte) -127} is
* considered greater than {@code (byte) 127} because it is seen as having
* the value of positive {@code 129}.
*
* @param a the first {@code byte} to compare
* @param b the second {@code byte} to compare
* @return a negative value if {@code a} is less than {@code b}; a positive
* value if {@code a} is greater than {@code b}; or zero if they are equal
*/
public static int compare(byte a, byte b) {
return toInt(a) - toInt(b);
}
/**
* Returns the least value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code byte} values
* @return the value present in {@code array} that is less than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static byte min(byte... array) {
checkArgument(array.length > 0);
int min = toInt(array[0]);
for (int i = 1; i < array.length; i++) {
int next = toInt(array[i]);
if (next < min) {
min = next;
}
}
return (byte) min;
}
/**
* Returns the greatest value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code byte} values
* @return the value present in {@code array} that is greater than or equal
* to every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static byte max(byte... array) {
checkArgument(array.length > 0);
int max = toInt(array[0]);
for (int i = 1; i < array.length; i++) {
int next = toInt(array[i]);
if (next > max) {
max = next;
}
}
return (byte) max;
}
/**
* Returns a string representation of x, where x is treated as unsigned.
*
* @since 13.0
*/
@Beta
public static String toString(byte x) {
return toString(x, 10);
}
/**
* Returns a string representation of {@code x} for the given radix, where {@code x} is treated
* as unsigned.
*
* @param x the value to convert to a string.
* @param radix the radix to use while working with {@code x}
* @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX}
* and {@link Character#MAX_RADIX}.
* @since 13.0
*/
@Beta
public static String toString(byte x, int radix) {
checkArgument(radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX,
"radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX", radix);
// Benchmarks indicate this is probably not worth optimizing.
return Integer.toString(toInt(x), radix);
}
/**
* Returns the unsigned {@code byte} value represented by the given decimal string.
*
* @throws NumberFormatException if the string does not contain a valid unsigned {@code long}
* value
* @since 13.0
*/
@Beta
public static byte parseUnsignedByte(String string) {
return parseUnsignedByte(string, 10);
}
/**
* Returns the unsigned {@code byte} value represented by a string with the given radix.
*
* @param string the string containing the unsigned {@code byte} representation to be parsed.
* @param radix the radix to use while parsing {@code string}
* @throws NumberFormatException if the string does not contain a valid unsigned {@code byte}
* with the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX}
* and {@link Character#MAX_RADIX}.
* @since 13.0
*/
@Beta
public static byte parseUnsignedByte(String string, int radix) {
int parse = Integer.parseInt(checkNotNull(string), radix);
// We need to throw a NumberFormatException, so we have to duplicate checkedCast. =(
if (parse >> Byte.SIZE == 0) {
return (byte) parse;
} else {
throw new NumberFormatException("out of range: " + parse);
}
}
/**
* Returns a string containing the supplied {@code byte} values separated by
* {@code separator}. For example, {@code join(":", (byte) 1, (byte) 2,
* (byte) 255)} returns the string {@code "1:2:255"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code byte} values, possibly empty
*/
public static String join(String separator, byte... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * (3 + separator.length()));
builder.append(toInt(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(toString(array[i]));
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code byte} arrays
* lexicographically. That is, it compares, using {@link
* #compare(byte, byte)}), the first pair of values that follow any common
* prefix, or when one array is a prefix of the other, treats the shorter
* array as the lesser. For example, {@code [] < [0x01] < [0x01, 0x7F] <
* [0x01, 0x80] < [0x02]}. Values are treated as unsigned.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link java.util.Arrays#equals(byte[], byte[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<byte[]> lexicographicalComparator() {
return LexicographicalComparatorHolder.BEST_COMPARATOR;
}
@VisibleForTesting
static Comparator<byte[]> lexicographicalComparatorJavaImpl() {
return LexicographicalComparatorHolder.PureJavaComparator.INSTANCE;
}
/**
* Provides a lexicographical comparator implementation; either a Java
* implementation or a faster implementation based on {@link Unsafe}.
*
* <p>Uses reflection to gracefully fall back to the Java implementation if
* {@code Unsafe} isn't available.
*/
@VisibleForTesting
static class LexicographicalComparatorHolder {
static final String UNSAFE_COMPARATOR_NAME =
LexicographicalComparatorHolder.class.getName() + "$UnsafeComparator";
static final Comparator<byte[]> BEST_COMPARATOR = getBestComparator();
@VisibleForTesting
enum UnsafeComparator implements Comparator<byte[]> {
INSTANCE;
static final boolean littleEndian =
ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN);
/*
* The following static final fields exist for performance reasons.
*
* In UnsignedBytesBenchmark, accessing the following objects via static
* final fields is the fastest (more than twice as fast as the Java
* implementation, vs ~1.5x with non-final static fields, on x86_32)
* under the Hotspot server compiler. The reason is obviously that the
* non-final fields need to be reloaded inside the loop.
*
* And, no, defining (final or not) local variables out of the loop still
* isn't as good because the null check on the theUnsafe object remains
* inside the loop and BYTE_ARRAY_BASE_OFFSET doesn't get
* constant-folded.
*
* The compiler can treat static final fields as compile-time constants
* and can constant-fold them while (final or not) local variables are
* run time values.
*/
static final Unsafe theUnsafe;
/** The offset to the first element in a byte array. */
static final int BYTE_ARRAY_BASE_OFFSET;
static {
theUnsafe = (Unsafe) AccessController.doPrivileged(
new PrivilegedAction<Object>() {
@Override
public Object run() {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
return f.get(null);
} catch (NoSuchFieldException e) {
// It doesn't matter what we throw;
// it's swallowed in getBestComparator().
throw new Error();
} catch (IllegalAccessException e) {
throw new Error();
}
}
});
BYTE_ARRAY_BASE_OFFSET = theUnsafe.arrayBaseOffset(byte[].class);
// sanity check - this should never fail
if (theUnsafe.arrayIndexScale(byte[].class) != 1) {
throw new AssertionError();
}
}
@Override public int compare(byte[] left, byte[] right) {
int minLength = Math.min(left.length, right.length);
int minWords = minLength / Longs.BYTES;
/*
* Compare 8 bytes at a time. Benchmarking shows comparing 8 bytes at a
* time is no slower than comparing 4 bytes at a time even on 32-bit.
* On the other hand, it is substantially faster on 64-bit.
*/
for (int i = 0; i < minWords * Longs.BYTES; i += Longs.BYTES) {
long lw = theUnsafe.getLong(left, BYTE_ARRAY_BASE_OFFSET + (long) i);
long rw = theUnsafe.getLong(right, BYTE_ARRAY_BASE_OFFSET + (long) i);
long diff = lw ^ rw;
if (diff != 0) {
if (!littleEndian) {
return UnsignedLongs.compare(lw, rw);
}
// Use binary search
int n = 0;
int y;
int x = (int) diff;
if (x == 0) {
x = (int) (diff >>> 32);
n = 32;
}
y = x << 16;
if (y == 0) {
n += 16;
} else {
x = y;
}
y = x << 8;
if (y == 0) {
n += 8;
}
return (int) (((lw >>> n) & UNSIGNED_MASK) - ((rw >>> n) & UNSIGNED_MASK));
}
}
// The epilogue to cover the last (minLength % 8) elements.
for (int i = minWords * Longs.BYTES; i < minLength; i++) {
int result = UnsignedBytes.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
enum PureJavaComparator implements Comparator<byte[]> {
INSTANCE;
@Override public int compare(byte[] left, byte[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = UnsignedBytes.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Returns the Unsafe-using Comparator, or falls back to the pure-Java
* implementation if unable to do so.
*/
static Comparator<byte[]> getBestComparator() {
try {
Class<?> theClass = Class.forName(UNSAFE_COMPARATOR_NAME);
// yes, UnsafeComparator does implement Comparator<byte[]>
@SuppressWarnings("unchecked")
Comparator<byte[]> comparator =
(Comparator<byte[]>) theClass.getEnumConstants()[0];
return comparator;
} catch (Throwable t) { // ensure we really catch *everything*
return lexicographicalComparatorJavaImpl();
}
}
}
}
| 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.primitives;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Contains static utility methods pertaining to primitive types and their
* corresponding wrapper types.
*
* @author Kevin Bourrillion
* @since 1.0
*/
public final class Primitives {
private Primitives() {}
/** A map from primitive types to their corresponding wrapper types. */
private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER_TYPE;
/** A map from wrapper types to their corresponding primitive types. */
private static final Map<Class<?>, Class<?>> WRAPPER_TO_PRIMITIVE_TYPE;
// Sad that we can't use a BiMap. :(
static {
Map<Class<?>, Class<?>> primToWrap = new HashMap<Class<?>, Class<?>>(16);
Map<Class<?>, Class<?>> wrapToPrim = new HashMap<Class<?>, Class<?>>(16);
add(primToWrap, wrapToPrim, boolean.class, Boolean.class);
add(primToWrap, wrapToPrim, byte.class, Byte.class);
add(primToWrap, wrapToPrim, char.class, Character.class);
add(primToWrap, wrapToPrim, double.class, Double.class);
add(primToWrap, wrapToPrim, float.class, Float.class);
add(primToWrap, wrapToPrim, int.class, Integer.class);
add(primToWrap, wrapToPrim, long.class, Long.class);
add(primToWrap, wrapToPrim, short.class, Short.class);
add(primToWrap, wrapToPrim, void.class, Void.class);
PRIMITIVE_TO_WRAPPER_TYPE = Collections.unmodifiableMap(primToWrap);
WRAPPER_TO_PRIMITIVE_TYPE = Collections.unmodifiableMap(wrapToPrim);
}
private static void add(Map<Class<?>, Class<?>> forward,
Map<Class<?>, Class<?>> backward, Class<?> key, Class<?> value) {
forward.put(key, value);
backward.put(value, key);
}
/**
* Returns an immutable set of all nine primitive types (including {@code
* void}). Note that a simpler way to test whether a {@code Class} instance
* is a member of this set is to call {@link Class#isPrimitive}.
*
* @since 3.0
*/
public static Set<Class<?>> allPrimitiveTypes() {
return PRIMITIVE_TO_WRAPPER_TYPE.keySet();
}
/**
* Returns an immutable set of all nine primitive-wrapper types (including
* {@link Void}).
*
* @since 3.0
*/
public static Set<Class<?>> allWrapperTypes() {
return WRAPPER_TO_PRIMITIVE_TYPE.keySet();
}
/**
* Returns {@code true} if {@code type} is one of the nine
* primitive-wrapper types, such as {@link Integer}.
*
* @see Class#isPrimitive
*/
public static boolean isWrapperType(Class<?> type) {
return WRAPPER_TO_PRIMITIVE_TYPE.containsKey(checkNotNull(type));
}
/**
* Returns the corresponding wrapper type of {@code type} if it is a primitive
* type; otherwise returns {@code type} itself. Idempotent.
* <pre>
* wrap(int.class) == Integer.class
* wrap(Integer.class) == Integer.class
* wrap(String.class) == String.class
* </pre>
*/
public static <T> Class<T> wrap(Class<T> type) {
checkNotNull(type);
// cast is safe: long.class and Long.class are both of type Class<Long>
@SuppressWarnings("unchecked")
Class<T> wrapped = (Class<T>) PRIMITIVE_TO_WRAPPER_TYPE.get(type);
return (wrapped == null) ? type : wrapped;
}
/**
* Returns the corresponding primitive type of {@code type} if it is a
* wrapper type; otherwise returns {@code type} itself. Idempotent.
* <pre>
* unwrap(Integer.class) == int.class
* unwrap(int.class) == int.class
* unwrap(String.class) == String.class
* </pre>
*/
public static <T> Class<T> unwrap(Class<T> type) {
checkNotNull(type);
// cast is safe: long.class and Long.class are both of type Class<Long>
@SuppressWarnings("unchecked")
Class<T> unwrapped = (Class<T>) WRAPPER_TO_PRIMITIVE_TYPE.get(type);
return (unwrapped == null) ? type : unwrapped;
}
}
| 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.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.Comparator;
/**
* Static utility methods pertaining to {@code byte} primitives that
* interpret values as signed. The corresponding methods that treat the values
* as unsigned are found in {@link UnsignedBytes}, and the methods for which
* signedness is not an issue are in {@link Bytes}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
// TODO(kevinb): how to prevent warning on UnsignedBytes when building GWT
// javadoc?
@GwtCompatible
public final class SignedBytes {
private SignedBytes() {}
/**
* The largest power of two that can be represented as a signed {@code byte}.
*
* @since 10.0
*/
public static final byte MAX_POWER_OF_TWO = 1 << 6;
/**
* Returns the {@code byte} value that is equal to {@code value}, if possible.
*
* @param value any value in the range of the {@code byte} type
* @return the {@code byte} value that equals {@code value}
* @throws IllegalArgumentException if {@code value} is greater than {@link
* Byte#MAX_VALUE} or less than {@link Byte#MIN_VALUE}
*/
public static byte checkedCast(long value) {
byte result = (byte) value;
checkArgument(result == value, "Out of range: %s", value);
return result;
}
/**
* Returns the {@code byte} nearest in value to {@code value}.
*
* @param value any {@code long} value
* @return the same value cast to {@code byte} if it is in the range of the
* {@code byte} type, {@link Byte#MAX_VALUE} if it is too large,
* or {@link Byte#MIN_VALUE} if it is too small
*/
public static byte saturatedCast(long value) {
if (value > Byte.MAX_VALUE) {
return Byte.MAX_VALUE;
}
if (value < Byte.MIN_VALUE) {
return Byte.MIN_VALUE;
}
return (byte) value;
}
/**
* Compares the two specified {@code byte} values. The sign of the value
* returned is the same as that of {@code ((Byte) a).compareTo(b)}.
*
* @param a the first {@code byte} to compare
* @param b the second {@code byte} to compare
* @return a negative value if {@code a} is less than {@code b}; a positive
* value if {@code a} is greater than {@code b}; or zero if they are equal
*/
public static int compare(byte a, byte b) {
return a - b; // safe due to restricted range
}
/**
* Returns the least value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code byte} values
* @return the value present in {@code array} that is less than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static byte min(byte... array) {
checkArgument(array.length > 0);
byte min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
/**
* Returns the greatest value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code byte} values
* @return the value present in {@code array} that is greater than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static byte max(byte... array) {
checkArgument(array.length > 0);
byte max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
/**
* Returns a string containing the supplied {@code byte} values separated
* by {@code separator}. For example, {@code join(":", 0x01, 0x02, -0x01)}
* returns the string {@code "1:2:-1"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code byte} values, possibly empty
*/
public static String join(String separator, byte... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 5);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code byte} arrays
* lexicographically. That is, it compares, using {@link
* #compare(byte, byte)}), the first pair of values that follow any common
* prefix, or when one array is a prefix of the other, treats the shorter
* array as the lesser. For example, {@code [] < [0x01] < [0x01, 0x80] <
* [0x01, 0x7F] < [0x02]}. Values are treated as signed.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link java.util.Arrays#equals(byte[], byte[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<byte[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<byte[]> {
INSTANCE;
@Override
public int compare(byte[] left, byte[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = SignedBytes.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
}
| Java |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.CheckForNull;
/**
* Static utility methods derived from Android's {@code Integer.java}.
*/
final class AndroidInteger {
/**
* See {@link Ints#tryParse(String)} for the public interface.
*/
@CheckForNull
static Integer tryParse(String string) {
return tryParse(string, 10);
}
/**
* See {@link Ints#tryParse(String, int)} for the public interface.
*/
@CheckForNull
static Integer tryParse(String string, int radix) {
checkNotNull(string);
checkArgument(radix >= Character.MIN_RADIX,
"Invalid radix %s, min radix is %s", radix, Character.MIN_RADIX);
checkArgument(radix <= Character.MAX_RADIX,
"Invalid radix %s, max radix is %s", radix, Character.MAX_RADIX);
int length = string.length(), i = 0;
if (length == 0) {
return null;
}
boolean negative = string.charAt(i) == '-';
if (negative && ++i == length) {
return null;
}
return tryParse(string, i, radix, negative);
}
@CheckForNull
private static Integer tryParse(String string, int offset, int radix,
boolean negative) {
int max = Integer.MIN_VALUE / radix;
int result = 0, length = string.length();
while (offset < length) {
int digit = Character.digit(string.charAt(offset++), radix);
if (digit == -1) {
return null;
}
if (max > result) {
return null;
}
int next = result * radix - digit;
if (next > result) {
return null;
}
result = next;
}
if (!negative) {
result = -result;
if (result < 0) {
return null;
}
}
// For GWT where ints do not overflow
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
return null;
}
return result;
}
private AndroidInteger() {}
}
| 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.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
/**
* Static utility methods pertaining to {@code char} primitives, that are not
* already found in either {@link Character} or {@link Arrays}.
*
* <p>All the operations in this class treat {@code char} values strictly
* numerically; they are neither Unicode-aware nor locale-dependent.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Chars {
private Chars() {}
/**
* The number of bytes required to represent a primitive {@code char}
* value.
*/
public static final int BYTES = Character.SIZE / Byte.SIZE;
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Character) value).hashCode()}.
*
* @param value a primitive {@code char} value
* @return a hash code for the value
*/
public static int hashCode(char value) {
return value;
}
/**
* Returns the {@code char} value that is equal to {@code value}, if possible.
*
* @param value any value in the range of the {@code char} type
* @return the {@code char} value that equals {@code value}
* @throws IllegalArgumentException if {@code value} is greater than {@link
* Character#MAX_VALUE} or less than {@link Character#MIN_VALUE}
*/
public static char checkedCast(long value) {
char result = (char) value;
checkArgument(result == value, "Out of range: %s", value);
return result;
}
/**
* Returns the {@code char} nearest in value to {@code value}.
*
* @param value any {@code long} value
* @return the same value cast to {@code char} if it is in the range of the
* {@code char} type, {@link Character#MAX_VALUE} if it is too large,
* or {@link Character#MIN_VALUE} if it is too small
*/
public static char saturatedCast(long value) {
if (value > Character.MAX_VALUE) {
return Character.MAX_VALUE;
}
if (value < Character.MIN_VALUE) {
return Character.MIN_VALUE;
}
return (char) value;
}
/**
* Compares the two specified {@code char} values. The sign of the value
* returned is the same as that of {@code ((Character) a).compareTo(b)}.
*
* @param a the first {@code char} to compare
* @param b the second {@code char} to compare
* @return a negative value if {@code a} is less than {@code b}; a positive
* value if {@code a} is greater than {@code b}; or zero if they are equal
*/
public static int compare(char a, char b) {
return a - b; // safe due to restricted range
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}.
*
* @param array an array of {@code char} values, possibly empty
* @param target a primitive {@code char} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(char[] array, char target) {
for (char value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code char} values, possibly empty
* @param target a primitive {@code char} value
* @return the least index {@code i} for which {@code array[i] == target}, or
* {@code -1} if no such index exists.
*/
public static int indexOf(char[] array, char target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
char[] array, char target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the start position of the first occurrence of the specified {@code
* target} within {@code array}, or {@code -1} if there is no such occurrence.
*
* <p>More formally, returns the lowest index {@code i} such that {@code
* java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
* the same elements as {@code target}.
*
* @param array the array to search for the sequence {@code target}
* @param target the array to search for as a sub-sequence of {@code array}
*/
public static int indexOf(char[] array, char[] target) {
checkNotNull(array, "array");
checkNotNull(target, "target");
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Returns the index of the last appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code char} values, possibly empty
* @param target a primitive {@code char} value
* @return the greatest index {@code i} for which {@code array[i] == target},
* or {@code -1} if no such index exists.
*/
public static int lastIndexOf(char[] array, char target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
char[] array, char target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the least value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code char} values
* @return the value present in {@code array} that is less than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static char min(char... array) {
checkArgument(array.length > 0);
char min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
/**
* Returns the greatest value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code char} values
* @return the value present in {@code array} that is greater than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static char max(char... array) {
checkArgument(array.length > 0);
char max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new char[] {a, b}, new char[] {}, new
* char[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code char} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static char[] concat(char[]... arrays) {
int length = 0;
for (char[] array : arrays) {
length += array.length;
}
char[] result = new char[length];
int pos = 0;
for (char[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns a big-endian representation of {@code value} in a 2-element byte
* array; equivalent to {@code
* ByteBuffer.allocate(2).putChar(value).array()}. For example, the input
* value {@code '\\u5432'} would yield the byte array {@code {0x54, 0x32}}.
*
* <p>If you need to convert and concatenate several values (possibly even of
* different types), use a shared {@link java.nio.ByteBuffer} instance, or use
* {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable
* buffer.
*/
@GwtIncompatible("doesn't work")
public static byte[] toByteArray(char value) {
return new byte[] {
(byte) (value >> 8),
(byte) value};
}
/**
* Returns the {@code char} value whose big-endian representation is
* stored in the first 2 bytes of {@code bytes}; equivalent to {@code
* ByteBuffer.wrap(bytes).getChar()}. For example, the input byte array
* {@code {0x54, 0x32}} would yield the {@code char} value {@code '\\u5432'}.
*
* <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that
* library exposes much more flexibility at little cost in readability.
*
* @throws IllegalArgumentException if {@code bytes} has fewer than 2
* elements
*/
@GwtIncompatible("doesn't work")
public static char fromByteArray(byte[] bytes) {
checkArgument(bytes.length >= BYTES,
"array too small: %s < %s", bytes.length, BYTES);
return fromBytes(bytes[0], bytes[1]);
}
/**
* Returns the {@code char} value whose byte representation is the given 2
* bytes, in big-endian order; equivalent to {@code Chars.fromByteArray(new
* byte[] {b1, b2})}.
*
* @since 7.0
*/
@GwtIncompatible("doesn't work")
public static char fromBytes(byte b1, byte b2) {
return (char) ((b1 << 8) | (b2 & 0xFF));
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static char[] ensureCapacity(
char[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static char[] copyOf(char[] original, int length) {
char[] copy = new char[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code char} values separated
* by {@code separator}. For example, {@code join("-", '1', '2', '3')} returns
* the string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code char} values, possibly empty
*/
public static String join(String separator, char... array) {
checkNotNull(separator);
int len = array.length;
if (len == 0) {
return "";
}
StringBuilder builder
= new StringBuilder(len + separator.length() * (len - 1));
builder.append(array[0]);
for (int i = 1; i < len; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code char} arrays
* lexicographically. That is, it compares, using {@link
* #compare(char, char)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example,
* {@code [] < ['a'] < ['a', 'b'] < ['b']}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(char[], char[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<char[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<char[]> {
INSTANCE;
@Override
public int compare(char[] left, char[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Chars.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Copies a collection of {@code Character} instances into a new array of
* primitive {@code char} values.
*
* <p>Elements are copied from the argument collection as if by {@code
* collection.toArray()}. Calling this method is as thread-safe as calling
* that method.
*
* @param collection a collection of {@code Character} objects
* @return an array containing the same values as {@code collection}, in the
* same order, converted to primitives
* @throws NullPointerException if {@code collection} or any of its elements
* is null
*/
public static char[] toArray(Collection<Character> collection) {
if (collection instanceof CharArrayAsList) {
return ((CharArrayAsList) collection).toCharArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
char[] array = new char[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = (Character) checkNotNull(boxedArray[i]);
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Character} objects written to or read from it. For example, whether
* {@code list.get(0) == list.get(0)} is true for the returned list is
* unspecified.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Character> asList(char... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new CharArrayAsList(backingArray);
}
@GwtCompatible
private static class CharArrayAsList extends AbstractList<Character>
implements RandomAccess, Serializable {
final char[] array;
final int start;
final int end;
CharArrayAsList(char[] array) {
this(array, 0, array.length);
}
CharArrayAsList(char[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Character get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Character)
&& Chars.indexOf(array, (Character) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Character) {
int i = Chars.indexOf(array, (Character) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Character) {
int i = Chars.lastIndexOf(array, (Character) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Character set(int index, Character element) {
checkElementIndex(index, size());
char oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Character> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new CharArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof CharArrayAsList) {
CharArrayAsList that = (CharArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Chars.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 3);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
char[] toCharArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
char[] result = new char[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
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.primitives;
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.GwtCompatible;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Comparator;
/**
* Static utility methods pertaining to {@code long} primitives that interpret values as
* <i>unsigned</i> (that is, any negative value {@code x} is treated as the positive value
* {@code 2^64 + x}). The methods for which signedness is not an issue are in {@link Longs}, as
* well as signed versions of methods for which signedness is an issue.
*
* <p>In addition, this class provides several static methods for converting a {@code long} to a
* {@code String} and a {@code String} to a {@code long} that treat the {@code long} as an unsigned
* number.
*
* <p>Users of these utilities must be <i>extremely careful</i> not to mix up signed and unsigned
* {@code long} values. When possible, it is recommended that the {@link UnsignedLong} wrapper
* class be used, at a small efficiency penalty, to enforce the distinction in the type system.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support">
* unsigned primitive utilities</a>.
*
* @author Louis Wasserman
* @author Brian Milch
* @author Colin Evans
* @since 10.0
*/
@Beta
@GwtCompatible
public final class UnsignedLongs {
private UnsignedLongs() {}
public static final long MAX_VALUE = -1L; // Equivalent to 2^64 - 1
/**
* A (self-inverse) bijection which converts the ordering on unsigned longs to the ordering on
* longs, that is, {@code a <= b} as unsigned longs if and only if {@code flip(a) <= flip(b)}
* as signed longs.
*/
private static long flip(long a) {
return a ^ Long.MIN_VALUE;
}
/**
* Compares the two specified {@code long} values, treating them as unsigned values between
* {@code 0} and {@code 2^64 - 1} inclusive.
*
* @param a the first unsigned {@code long} to compare
* @param b the second unsigned {@code long} to compare
* @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
* greater than {@code b}; or zero if they are equal
*/
public static int compare(long a, long b) {
return Longs.compare(flip(a), flip(b));
}
/**
* Returns the least value present in {@code array}, treating values as unsigned.
*
* @param array a <i>nonempty</i> array of unsigned {@code long} values
* @return the value present in {@code array} that is less than or equal to every other value in
* the array according to {@link #compare}
* @throws IllegalArgumentException if {@code array} is empty
*/
public static long min(long... array) {
checkArgument(array.length > 0);
long min = flip(array[0]);
for (int i = 1; i < array.length; i++) {
long next = flip(array[i]);
if (next < min) {
min = next;
}
}
return flip(min);
}
/**
* Returns the greatest value present in {@code array}, treating values as unsigned.
*
* @param array a <i>nonempty</i> array of unsigned {@code long} values
* @return the value present in {@code array} that is greater than or equal to every other value
* in the array according to {@link #compare}
* @throws IllegalArgumentException if {@code array} is empty
*/
public static long max(long... array) {
checkArgument(array.length > 0);
long max = flip(array[0]);
for (int i = 1; i < array.length; i++) {
long next = flip(array[i]);
if (next > max) {
max = next;
}
}
return flip(max);
}
/**
* Returns a string containing the supplied unsigned {@code long} values separated by
* {@code separator}. For example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in the resulting
* string (but not at the start or end)
* @param array an array of unsigned {@code long} values, possibly empty
*/
public static String join(String separator, long... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 5);
builder.append(toString(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(toString(array[i]));
}
return builder.toString();
}
/**
* Returns a comparator that compares two arrays of unsigned {@code long} values
* lexicographically. That is, it compares, using {@link #compare(long, long)}), the first pair of
* values that follow any common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example, {@code [] < [1L] < [1L, 2L] < [2L] < [1L << 63]}.
*
* <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
* support only identity equality), but it is consistent with
* {@link Arrays#equals(long[], long[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">Lexicographical order
* article at Wikipedia</a>
*/
public static Comparator<long[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
enum LexicographicalComparator implements Comparator<long[]> {
INSTANCE;
@Override
public int compare(long[] left, long[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
if (left[i] != right[i]) {
return UnsignedLongs.compare(left[i], right[i]);
}
}
return left.length - right.length;
}
}
/**
* Returns dividend / divisor, where the dividend and divisor are treated as unsigned 64-bit
* quantities.
*
* @param dividend the dividend (numerator)
* @param divisor the divisor (denominator)
* @throws ArithmeticException if divisor is 0
*/
public static long divide(long dividend, long divisor) {
if (divisor < 0) { // i.e., divisor >= 2^63:
if (compare(dividend, divisor) < 0) {
return 0; // dividend < divisor
} else {
return 1; // dividend >= divisor
}
}
// Optimization - use signed division if dividend < 2^63
if (dividend >= 0) {
return dividend / divisor;
}
/*
* Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is
* guaranteed to be either exact or one less than the correct value. This follows from fact
* that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not
* quite trivial.
*/
long quotient = ((dividend >>> 1) / divisor) << 1;
long rem = dividend - quotient * divisor;
return quotient + (compare(rem, divisor) >= 0 ? 1 : 0);
}
/**
* Returns dividend % divisor, where the dividend and divisor are treated as unsigned 64-bit
* quantities.
*
* @param dividend the dividend (numerator)
* @param divisor the divisor (denominator)
* @throws ArithmeticException if divisor is 0
* @since 11.0
*/
public static long remainder(long dividend, long divisor) {
if (divisor < 0) { // i.e., divisor >= 2^63:
if (compare(dividend, divisor) < 0) {
return dividend; // dividend < divisor
} else {
return dividend - divisor; // dividend >= divisor
}
}
// Optimization - use signed modulus if dividend < 2^63
if (dividend >= 0) {
return dividend % divisor;
}
/*
* Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is
* guaranteed to be either exact or one less than the correct value. This follows from fact
* that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not
* quite trivial.
*/
long quotient = ((dividend >>> 1) / divisor) << 1;
long rem = dividend - quotient * divisor;
return rem - (compare(rem, divisor) >= 0 ? divisor : 0);
}
/**
* Returns the unsigned {@code long} value represented by the given decimal string.
*
* @throws NumberFormatException if the string does not contain a valid unsigned {@code long}
* value
*/
public static long parseUnsignedLong(String s) {
return parseUnsignedLong(s, 10);
}
/**
* Returns the unsigned {@code long} value represented by the given string.
*
* Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix:
*
* <ul>
* <li>{@code 0x}<i>HexDigits</i>
* <li>{@code 0X}<i>HexDigits</i>
* <li>{@code #}<i>HexDigits</i>
* <li>{@code 0}<i>OctalDigits</i>
* </ul>
*
* @throws NumberFormatException if the string does not contain a valid unsigned {@code long}
* value
* @since 13.0
*/
public static long decode(String stringValue) {
ParseRequest request = ParseRequest.fromString(stringValue);
try {
return parseUnsignedLong(request.rawValue, request.radix);
} catch (NumberFormatException e) {
NumberFormatException decodeException =
new NumberFormatException("Error parsing value: " + stringValue);
decodeException.initCause(e);
throw decodeException;
}
}
/**
* Returns the unsigned {@code long} value represented by a string with the given radix.
*
* @param s the string containing the unsigned {@code long} representation to be parsed.
* @param radix the radix to use while parsing {@code s}
* @throws NumberFormatException if the string does not contain a valid unsigned {@code long}
* with the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX}
* and {@link Character#MAX_RADIX}.
*/
public static long parseUnsignedLong(String s, int radix) {
checkNotNull(s);
if (s.length() == 0) {
throw new NumberFormatException("empty string");
}
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
throw new NumberFormatException("illegal radix: " + radix);
}
int max_safe_pos = maxSafeDigits[radix] - 1;
long value = 0;
for (int pos = 0; pos < s.length(); pos++) {
int digit = Character.digit(s.charAt(pos), radix);
if (digit == -1) {
throw new NumberFormatException(s);
}
if (pos > max_safe_pos && overflowInParse(value, digit, radix)) {
throw new NumberFormatException("Too large for unsigned long: " + s);
}
value = (value * radix) + digit;
}
return value;
}
/**
* Returns true if (current * radix) + digit is a number too large to be represented by an
* unsigned long. This is useful for detecting overflow while parsing a string representation of
* a number. Does not verify whether supplied radix is valid, passing an invalid radix will give
* undefined results or an ArrayIndexOutOfBoundsException.
*/
private static boolean overflowInParse(long current, int digit, int radix) {
if (current >= 0) {
if (current < maxValueDivs[radix]) {
return false;
}
if (current > maxValueDivs[radix]) {
return true;
}
// current == maxValueDivs[radix]
return (digit > maxValueMods[radix]);
}
// current < 0: high bit is set
return true;
}
/**
* Returns a string representation of x, where x is treated as unsigned.
*/
public static String toString(long x) {
return toString(x, 10);
}
/**
* Returns a string representation of {@code x} for the given radix, where {@code x} is treated
* as unsigned.
*
* @param x the value to convert to a string.
* @param radix the radix to use while working with {@code x}
* @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX}
* and {@link Character#MAX_RADIX}.
*/
public static String toString(long x, int radix) {
checkArgument(radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX,
"radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX", radix);
if (x == 0) {
// Simply return "0"
return "0";
} else {
char[] buf = new char[64];
int i = buf.length;
if (x < 0) {
// Separate off the last digit using unsigned division. That will leave
// a number that is nonnegative as a signed integer.
long quotient = divide(x, radix);
long rem = x - quotient * radix;
buf[--i] = Character.forDigit((int) rem, radix);
x = quotient;
}
// Simple modulo/division approach
while (x > 0) {
buf[--i] = Character.forDigit((int) (x % radix), radix);
x /= radix;
}
// Generate string
return new String(buf, i, buf.length - i);
}
}
// calculated as 0xffffffffffffffff / radix
private static final long[] maxValueDivs = new long[Character.MAX_RADIX + 1];
private static final int[] maxValueMods = new int[Character.MAX_RADIX + 1];
private static final int[] maxSafeDigits = new int[Character.MAX_RADIX + 1];
static {
BigInteger overflow = new BigInteger("10000000000000000", 16);
for (int i = Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) {
maxValueDivs[i] = divide(MAX_VALUE, i);
maxValueMods[i] = (int) remainder(MAX_VALUE, i);
maxSafeDigits[i] = overflow.toString(i).length() - 1;
}
}
}
| 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.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static java.lang.Double.NEGATIVE_INFINITY;
import static java.lang.Double.POSITIVE_INFINITY;
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.AbstractList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@code double} primitives, that are not
* already found in either {@link Double} or {@link Arrays}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Doubles {
private Doubles() {}
/**
* The number of bytes required to represent a primitive {@code double}
* value.
*
* @since 10.0
*/
public static final int BYTES = Double.SIZE / Byte.SIZE;
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Double) value).hashCode()}.
*
* @param value a primitive {@code double} value
* @return a hash code for the value
*/
public static int hashCode(double value) {
return ((Double) value).hashCode();
// TODO(kevinb): do it this way when we can (GWT problem):
// long bits = Double.doubleToLongBits(value);
// return (int)(bits ^ (bits >>> 32));
}
/**
* Compares the two specified {@code double} values. The sign of the value
* returned is the same as that of <code>((Double) a).{@linkplain
* Double#compareTo compareTo}(b)</code>. As with that method, {@code NaN} is
* treated as greater than all other values, and {@code 0.0 > -0.0}.
*
* @param a the first {@code double} to compare
* @param b the second {@code double} to compare
* @return a negative value if {@code a} is less than {@code b}; a positive
* value if {@code a} is greater than {@code b}; or zero if they are equal
*/
public static int compare(double a, double b) {
return Double.compare(a, b);
}
/**
* Returns {@code true} if {@code value} represents a real number. This is
* equivalent to, but not necessarily implemented as,
* {@code !(Double.isInfinite(value) || Double.isNaN(value))}.
*
* @since 10.0
*/
public static boolean isFinite(double value) {
return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY;
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}. Note that this always returns {@code false} when {@code
* target} is {@code NaN}.
*
* @param array an array of {@code double} values, possibly empty
* @param target a primitive {@code double} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(double[] array, double target) {
for (double value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}. Note that this always returns {@code -1} when {@code target}
* is {@code NaN}.
*
* @param array an array of {@code double} values, possibly empty
* @param target a primitive {@code double} value
* @return the least index {@code i} for which {@code array[i] == target}, or
* {@code -1} if no such index exists.
*/
public static int indexOf(double[] array, double target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
double[] array, double target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the start position of the first occurrence of the specified {@code
* target} within {@code array}, or {@code -1} if there is no such occurrence.
*
* <p>More formally, returns the lowest index {@code i} such that {@code
* java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
* the same elements as {@code target}.
*
* <p>Note that this always returns {@code -1} when {@code target} contains
* {@code NaN}.
*
* @param array the array to search for the sequence {@code target}
* @param target the array to search for as a sub-sequence of {@code array}
*/
public static int indexOf(double[] array, double[] target) {
checkNotNull(array, "array");
checkNotNull(target, "target");
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Returns the index of the last appearance of the value {@code target} in
* {@code array}. Note that this always returns {@code -1} when {@code target}
* is {@code NaN}.
*
* @param array an array of {@code double} values, possibly empty
* @param target a primitive {@code double} value
* @return the greatest index {@code i} for which {@code array[i] == target},
* or {@code -1} if no such index exists.
*/
public static int lastIndexOf(double[] array, double target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
double[] array, double target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the least value present in {@code array}, using the same rules of
* comparison as {@link Math#min(double, double)}.
*
* @param array a <i>nonempty</i> array of {@code double} values
* @return the value present in {@code array} that is less than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static double min(double... array) {
checkArgument(array.length > 0);
double min = array[0];
for (int i = 1; i < array.length; i++) {
min = Math.min(min, array[i]);
}
return min;
}
/**
* Returns the greatest value present in {@code array}, using the same rules
* of comparison as {@link Math#max(double, double)}.
*
* @param array a <i>nonempty</i> array of {@code double} values
* @return the value present in {@code array} that is greater than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static double max(double... array) {
checkArgument(array.length > 0);
double max = array[0];
for (int i = 1; i < array.length; i++) {
max = Math.max(max, array[i]);
}
return max;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new double[] {a, b}, new double[] {}, new
* double[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code double} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static double[] concat(double[]... arrays) {
int length = 0;
for (double[] array : arrays) {
length += array.length;
}
double[] result = new double[length];
int pos = 0;
for (double[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static double[] ensureCapacity(
double[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static double[] copyOf(double[] original, int length) {
double[] copy = new double[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code double} values, converted
* to strings as specified by {@link Double#toString(double)}, and separated
* by {@code separator}. For example, {@code join("-", 1.0, 2.0, 3.0)} returns
* the string {@code "1.0-2.0-3.0"}.
*
* <p>Note that {@link Double#toString(double)} formats {@code double}
* differently in GWT sometimes. In the previous example, it returns the
* string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code double} values, possibly empty
*/
public static String join(String separator, double... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 12);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code double} arrays
* lexicographically. That is, it compares, using {@link
* #compare(double, double)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example,
* {@code [] < [1.0] < [1.0, 2.0] < [2.0]}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(double[], double[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<double[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<double[]> {
INSTANCE;
@Override
public int compare(double[] left, double[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Doubles.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code double} value in the manner of {@link Number#doubleValue}.
*
* <p>Elements are copied from the argument collection as if by {@code
* collection.toArray()}. Calling this method is as thread-safe as calling
* that method.
*
* @param collection a collection of {@code Number} instances
* @return an array containing the same values as {@code collection}, in the
* same order, converted to primitives
* @throws NullPointerException if {@code collection} or any of its elements
* is null
* @since 1.0 (parameter was {@code Collection<Double>} before 12.0)
*/
public static double[] toArray(Collection<? extends Number> collection) {
if (collection instanceof DoubleArrayAsList) {
return ((DoubleArrayAsList) collection).toDoubleArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
double[] array = new double[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).doubleValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Double} objects written to or read from it. For example, whether
* {@code list.get(0) == list.get(0)} is true for the returned list is
* unspecified.
*
* <p>The returned list may have unexpected behavior if it contains {@code
* NaN}, or if {@code NaN} is used as a parameter to any of its methods.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Double> asList(double... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new DoubleArrayAsList(backingArray);
}
@GwtCompatible
private static class DoubleArrayAsList extends AbstractList<Double>
implements RandomAccess, Serializable {
final double[] array;
final int start;
final int end;
DoubleArrayAsList(double[] array) {
this(array, 0, array.length);
}
DoubleArrayAsList(double[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Double get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Double)
&& Doubles.indexOf(array, (Double) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Double) {
int i = Doubles.indexOf(array, (Double) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Double) {
int i = Doubles.lastIndexOf(array, (Double) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Double set(int index, Double element) {
checkElementIndex(index, size());
double oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Double> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new DoubleArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof DoubleArrayAsList) {
DoubleArrayAsList that = (DoubleArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Doubles.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 12);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
double[] toDoubleArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
double[] result = new double[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
private static final long serialVersionUID = 0;
}
/**
* This is adapted from the regex suggested by {@link Double#valueOf(String)}
* for prevalidating inputs. All valid inputs must pass this regex, but it's
* semantically fine if not all inputs that pass this regex are valid --
* only a performance hit is incurred, not a semantics bug.
*/
@GwtIncompatible("regular expressions")
static final Pattern FLOATING_POINT_PATTERN = fpPattern();
@GwtIncompatible("regular expressions")
private static Pattern fpPattern() {
String decimal = "(?:\\d++(?:\\.\\d*+)?|\\.\\d++)";
String completeDec = decimal + "(?:[eE][+-]?\\d++)?[fFdD]?";
String hex = "(?:\\p{XDigit}++(?:\\.\\p{XDigit}*+)?|\\.\\p{XDigit}++)";
String completeHex = "0[xX]" + hex + "[pP][+-]?\\d++[fFdD]?";
String fpPattern = "[+-]?(?:NaN|Infinity|" + completeDec + "|" + completeHex + ")";
return Pattern.compile(fpPattern);
}
/**
* Parses the specified string as a double-precision floating point value.
* The ASCII character {@code '-'} (<code>'\u002D'</code>) is recognized
* as the minus sign.
*
* <p>Unlike {@link Double#parseDouble(String)}, this method returns
* {@code null} instead of throwing an exception if parsing fails.
* Valid inputs are exactly those accepted by {@link Double#valueOf(String)},
* except that leading and trailing whitespace is not permitted.
*
* <p>This implementation is likely to be faster than {@code
* Double.parseDouble} if many failures are expected.
*
* @param string the string representation of a {@code double} value
* @return the floating point value represented by {@code string}, or
* {@code null} if {@code string} has a length of zero or cannot be
* parsed as a {@code double} value
* @since 14.0
*/
@GwtIncompatible("regular expressions")
@Nullable
@Beta
public static Double tryParse(String string) {
if (FLOATING_POINT_PATTERN.matcher(string).matches()) {
// TODO(user): could be potentially optimized, but only with
// extensive testing
try {
return Double.parseDouble(string);
} catch (NumberFormatException e) {
// Double.parseDouble has changed specs several times, so fall through
// gracefully
}
}
return null;
}
}
| 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.primitives;
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.GwtCompatible;
import java.util.Arrays;
import java.util.Comparator;
/**
* Static utility methods pertaining to {@code int} primitives that interpret values as
* <i>unsigned</i> (that is, any negative value {@code x} is treated as the positive value
* {@code 2^32 + x}). The methods for which signedness is not an issue are in {@link Ints}, as well
* as signed versions of methods for which signedness is an issue.
*
* <p>In addition, this class provides several static methods for converting an {@code int} to a
* {@code String} and a {@code String} to an {@code int} that treat the {@code int} as an unsigned
* number.
*
* <p>Users of these utilities must be <i>extremely careful</i> not to mix up signed and unsigned
* {@code int} values. When possible, it is recommended that the {@link UnsignedInteger} wrapper
* class be used, at a small efficiency penalty, to enforce the distinction in the type system.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support">
* unsigned primitive utilities</a>.
*
* @author Louis Wasserman
* @since 11.0
*/
@Beta
@GwtCompatible
public final class UnsignedInts {
static final long INT_MASK = 0xffffffffL;
private UnsignedInts() {}
static int flip(int value) {
return value ^ Integer.MIN_VALUE;
}
/**
* Compares the two specified {@code int} values, treating them as unsigned values between
* {@code 0} and {@code 2^32 - 1} inclusive.
*
* @param a the first unsigned {@code int} to compare
* @param b the second unsigned {@code int} to compare
* @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is
* greater than {@code b}; or zero if they are equal
*/
public static int compare(int a, int b) {
return Ints.compare(flip(a), flip(b));
}
/**
* Returns the value of the given {@code int} as a {@code long}, when treated as unsigned.
*/
public static long toLong(int value) {
return value & INT_MASK;
}
/**
* Returns the least value present in {@code array}, treating values as unsigned.
*
* @param array a <i>nonempty</i> array of unsigned {@code int} values
* @return the value present in {@code array} that is less than or equal to every other value in
* the array according to {@link #compare}
* @throws IllegalArgumentException if {@code array} is empty
*/
public static int min(int... array) {
checkArgument(array.length > 0);
int min = flip(array[0]);
for (int i = 1; i < array.length; i++) {
int next = flip(array[i]);
if (next < min) {
min = next;
}
}
return flip(min);
}
/**
* Returns the greatest value present in {@code array}, treating values as unsigned.
*
* @param array a <i>nonempty</i> array of unsigned {@code int} values
* @return the value present in {@code array} that is greater than or equal to every other value
* in the array according to {@link #compare}
* @throws IllegalArgumentException if {@code array} is empty
*/
public static int max(int... array) {
checkArgument(array.length > 0);
int max = flip(array[0]);
for (int i = 1; i < array.length; i++) {
int next = flip(array[i]);
if (next > max) {
max = next;
}
}
return flip(max);
}
/**
* Returns a string containing the supplied unsigned {@code int} values separated by
* {@code separator}. For example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in the resulting
* string (but not at the start or end)
* @param array an array of unsigned {@code int} values, possibly empty
*/
public static String join(String separator, int... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 5);
builder.append(toString(array[0]));
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(toString(array[i]));
}
return builder.toString();
}
/**
* Returns a comparator that compares two arrays of unsigned {@code int} values lexicographically.
* That is, it compares, using {@link #compare(int, int)}), the first pair of values that follow
* any common prefix, or when one array is a prefix of the other, treats the shorter array as the
* lesser. For example, {@code [] < [1] < [1, 2] < [2] < [1 << 31]}.
*
* <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
* support only identity equality), but it is consistent with {@link Arrays#equals(int[], int[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> Lexicographical order
* article at Wikipedia</a>
*/
public static Comparator<int[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
enum LexicographicalComparator implements Comparator<int[]> {
INSTANCE;
@Override
public int compare(int[] left, int[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
if (left[i] != right[i]) {
return UnsignedInts.compare(left[i], right[i]);
}
}
return left.length - right.length;
}
}
/**
* Returns dividend / divisor, where the dividend and divisor are treated as unsigned 32-bit
* quantities.
*
* @param dividend the dividend (numerator)
* @param divisor the divisor (denominator)
* @throws ArithmeticException if divisor is 0
*/
public static int divide(int dividend, int divisor) {
return (int) (toLong(dividend) / toLong(divisor));
}
/**
* Returns dividend % divisor, where the dividend and divisor are treated as unsigned 32-bit
* quantities.
*
* @param dividend the dividend (numerator)
* @param divisor the divisor (denominator)
* @throws ArithmeticException if divisor is 0
*/
public static int remainder(int dividend, int divisor) {
return (int) (toLong(dividend) % toLong(divisor));
}
/**
* Returns the unsigned {@code int} value represented by the given string.
*
* Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix:
*
* <ul>
* <li>{@code 0x}<i>HexDigits</i>
* <li>{@code 0X}<i>HexDigits</i>
* <li>{@code #}<i>HexDigits</i>
* <li>{@code 0}<i>OctalDigits</i>
* </ul>
*
* @throws NumberFormatException if the string does not contain a valid unsigned {@code int}
* value
* @since 13.0
*/
public static int decode(String stringValue) {
ParseRequest request = ParseRequest.fromString(stringValue);
try {
return parseUnsignedInt(request.rawValue, request.radix);
} catch (NumberFormatException e) {
NumberFormatException decodeException =
new NumberFormatException("Error parsing value: " + stringValue);
decodeException.initCause(e);
throw decodeException;
}
}
/**
* Returns the unsigned {@code int} value represented by the given decimal string.
*
* @throws NumberFormatException if the string does not contain a valid unsigned integer, or if
* the value represented is too large to fit in an unsigned {@code int}.
* @throws NullPointerException if {@code s} is null
*/
public static int parseUnsignedInt(String s) {
return parseUnsignedInt(s, 10);
}
/**
* Returns the unsigned {@code int} value represented by a string with the given radix.
*
* @param string the string containing the unsigned integer representation to be parsed.
* @param radix the radix to use while parsing {@code s}; must be between
* {@link Character#MIN_RADIX} and {@link Character#MAX_RADIX}.
* @throws NumberFormatException if the string does not contain a valid unsigned {@code int}, or
* if supplied radix is invalid.
*/
public static int parseUnsignedInt(String string, int radix) {
checkNotNull(string);
long result = Long.parseLong(string, radix);
if ((result & INT_MASK) != result) {
throw new NumberFormatException("Input " + string + " in base " + radix
+ " is not in the range of an unsigned integer");
}
return (int) result;
}
/**
* Returns a string representation of x, where x is treated as unsigned.
*/
public static String toString(int x) {
return toString(x, 10);
}
/**
* Returns a string representation of {@code x} for the given radix, where {@code x} is treated
* as unsigned.
*
* @param x the value to convert to a string.
* @param radix the radix to use while working with {@code x}
* @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX}
* and {@link Character#MAX_RADIX}.
*/
public static String toString(int x, int radix) {
long asLong = x & INT_MASK;
return Long.toString(asLong, radix);
}
}
| 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.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.primitives.UnsignedInts.INT_MASK;
import static com.google.common.primitives.UnsignedInts.compare;
import static com.google.common.primitives.UnsignedInts.toLong;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.math.BigInteger;
import javax.annotation.Nullable;
/**
* A wrapper class for unsigned {@code int} values, supporting arithmetic operations.
*
* <p>In some cases, when speed is more important than code readability, it may be faster simply to
* treat primitive {@code int} values as unsigned, using the methods from {@link UnsignedInts}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support">
* unsigned primitive utilities</a>.
*
* @author Louis Wasserman
* @since 11.0
*/
@Beta
@GwtCompatible(emulated = true)
public final class UnsignedInteger extends Number implements Comparable<UnsignedInteger> {
public static final UnsignedInteger ZERO = asUnsigned(0);
public static final UnsignedInteger ONE = asUnsigned(1);
public static final UnsignedInteger MAX_VALUE = asUnsigned(-1);
private final int value;
private UnsignedInteger(int value) {
this.value = value & 0xffffffff;
}
/**
* Returns an {@code UnsignedInteger} that, when treated as signed, is
* equal to {@code value}.
*/
public static UnsignedInteger asUnsigned(int value) {
return new UnsignedInteger(value);
}
/**
* Returns an {@code UnsignedInteger} that is equal to {@code value},
* if possible. The inverse operation of {@link #longValue()}.
*/
public static UnsignedInteger valueOf(long value) {
checkArgument((value & INT_MASK) == value,
"value (%s) is outside the range for an unsigned integer value", value);
return asUnsigned((int) value);
}
/**
* Returns a {@code UnsignedInteger} representing the same value as the specified
* {@link BigInteger}. This is the inverse operation of {@link #bigIntegerValue()}.
*
* @throws IllegalArgumentException if {@code value} is negative or {@code value >= 2^32}
*/
public static UnsignedInteger valueOf(BigInteger value) {
checkNotNull(value);
checkArgument(value.signum() >= 0 && value.bitLength() <= Integer.SIZE,
"value (%s) is outside the range for an unsigned integer value", value);
return asUnsigned(value.intValue());
}
/**
* Returns an {@code UnsignedInteger} holding the value of the specified {@code String}, parsed
* as an unsigned {@code int} value.
*
* @throws NumberFormatException if the string does not contain a parsable unsigned {@code int}
* value
*/
public static UnsignedInteger valueOf(String string) {
return valueOf(string, 10);
}
/**
* Returns an {@code UnsignedInteger} holding the value of the specified {@code String}, parsed
* as an unsigned {@code int} value in the specified radix.
*
* @throws NumberFormatException if the string does not contain a parsable unsigned {@code int}
* value
*/
public static UnsignedInteger valueOf(String string, int radix) {
return asUnsigned(UnsignedInts.parseUnsignedInt(string, radix));
}
/**
* Returns the result of adding this and {@code val}. If the result would have more than 32 bits,
* returns the low 32 bits of the result.
*/
public UnsignedInteger add(UnsignedInteger val) {
checkNotNull(val);
return asUnsigned(this.value + val.value);
}
/**
* Returns the result of subtracting this and {@code val}. If the result would be negative,
* returns the low 32 bits of the result.
*/
public UnsignedInteger subtract(UnsignedInteger val) {
checkNotNull(val);
return asUnsigned(this.value - val.value);
}
/**
* Returns the result of multiplying this and {@code val}. If the result would have more than 32
* bits, returns the low 32 bits of the result.
*/
@GwtIncompatible("Does not truncate correctly")
public UnsignedInteger multiply(UnsignedInteger val) {
checkNotNull(val);
return asUnsigned(value * val.value);
}
/**
* Returns the result of dividing this by {@code val}.
*/
public UnsignedInteger divide(UnsignedInteger val) {
checkNotNull(val);
return asUnsigned(UnsignedInts.divide(value, val.value));
}
/**
* Returns the remainder of dividing this by {@code val}.
*/
public UnsignedInteger remainder(UnsignedInteger val) {
checkNotNull(val);
return asUnsigned(UnsignedInts.remainder(value, val.value));
}
/**
* Returns the value of this {@code UnsignedInteger} as an {@code int}. This is an inverse
* operation to {@link #asUnsigned}.
*
* <p>Note that if this {@code UnsignedInteger} holds a value {@code >= 2^31}, the returned value
* will be equal to {@code this - 2^32}.
*/
@Override
public int intValue() {
return value;
}
/**
* Returns the value of this {@code UnsignedInteger} as a {@code long}.
*/
@Override
public long longValue() {
return toLong(value);
}
/**
* Returns the value of this {@code UnsignedInteger} as a {@code float}, analogous to a widening
* primitive conversion from {@code int} to {@code float}, and correctly rounded.
*/
@Override
public float floatValue() {
return longValue();
}
/**
* Returns the value of this {@code UnsignedInteger} as a {@code float}, analogous to a widening
* primitive conversion from {@code int} to {@code double}, and correctly rounded.
*/
@Override
public double doubleValue() {
return longValue();
}
/**
* Returns the value of this {@code UnsignedInteger} as a {@link BigInteger}.
*/
public BigInteger bigIntegerValue() {
return BigInteger.valueOf(longValue());
}
/**
* Compares this unsigned integer to another unsigned integer.
* Returns {@code 0} if they are equal, a negative number if {@code this < other},
* and a positive number if {@code this > other}.
*/
@Override
public int compareTo(UnsignedInteger other) {
checkNotNull(other);
return compare(value, other.value);
}
@Override
public int hashCode() {
return value;
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof UnsignedInteger) {
UnsignedInteger other = (UnsignedInteger) obj;
return value == other.value;
}
return false;
}
/**
* Returns a string representation of the {@code UnsignedInteger} value, in base 10.
*/
@Override
public String toString() {
return toString(10);
}
/**
* Returns a string representation of the {@code UnsignedInteger} value, in base {@code radix}.
* If {@code radix < Character.MIN_RADIX} or {@code radix > Character.MAX_RADIX}, the radix
* {@code 10} is used.
*/
public String toString(int radix) {
return UnsignedInts.toString(value, radix);
}
}
| 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.primitives;
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.GwtCompatible;
import java.io.Serializable;
import java.math.BigInteger;
import javax.annotation.Nullable;
/**
* A wrapper class for unsigned {@code long} values, supporting arithmetic operations.
*
* <p>In some cases, when speed is more important than code readability, it may be faster simply to
* treat primitive {@code long} values as unsigned, using the methods from {@link UnsignedLongs}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support">
* unsigned primitive utilities</a>.
*
* @author Louis Wasserman
* @author Colin Evans
* @since 11.0
*/
@Beta
@GwtCompatible(serializable = true)
public final class UnsignedLong extends Number implements Comparable<UnsignedLong>, Serializable {
private static final long UNSIGNED_MASK = 0x7fffffffffffffffL;
public static final UnsignedLong ZERO = new UnsignedLong(0);
public static final UnsignedLong ONE = new UnsignedLong(1);
public static final UnsignedLong MAX_VALUE = new UnsignedLong(-1L);
private final long value;
private UnsignedLong(long value) {
this.value = value;
}
/**
* Returns an {@code UnsignedLong} that, when treated as signed, is equal to {@code value}. The
* inverse operation is {@link #longValue()}.
*
* <p>Put another way, if {@code value} is negative, the returned result will be equal to
* {@code 2^64 + value}; otherwise, the returned result will be equal to {@code value}.
*/
public static UnsignedLong asUnsigned(long value) {
return new UnsignedLong(value);
}
/**
* Returns a {@code UnsignedLong} representing the same value as the specified {@code BigInteger}
* . This is the inverse operation of {@link #bigIntegerValue()}.
*
* @throws IllegalArgumentException if {@code value} is negative or {@code value >= 2^64}
*/
public static UnsignedLong valueOf(BigInteger value) {
checkNotNull(value);
checkArgument(value.signum() >= 0 && value.bitLength() <= Long.SIZE,
"value (%s) is outside the range for an unsigned long value", value);
return asUnsigned(value.longValue());
}
/**
* Returns an {@code UnsignedLong} holding the value of the specified {@code String}, parsed as
* an unsigned {@code long} value.
*
* @throws NumberFormatException if the string does not contain a parsable unsigned {@code long}
* value
*/
public static UnsignedLong valueOf(String string) {
return valueOf(string, 10);
}
/**
* Returns an {@code UnsignedLong} holding the value of the specified {@code String}, parsed as
* an unsigned {@code long} value in the specified radix.
*
* @throws NumberFormatException if the string does not contain a parsable unsigned {@code long}
* value, or {@code radix} is not between {@link Character#MIN_RADIX} and
* {@link Character#MAX_RADIX}
*/
public static UnsignedLong valueOf(String string, int radix) {
return asUnsigned(UnsignedLongs.parseUnsignedLong(string, radix));
}
/**
* Returns the result of adding this and {@code val}. If the result would have more than 64 bits,
* returns the low 64 bits of the result.
*/
public UnsignedLong add(UnsignedLong val) {
checkNotNull(val);
return asUnsigned(this.value + val.value);
}
/**
* Returns the result of subtracting this and {@code val}. If the result would be negative,
* returns the low 64 bits of the result.
*/
public UnsignedLong subtract(UnsignedLong val) {
checkNotNull(val);
return asUnsigned(this.value - val.value);
}
/**
* Returns the result of multiplying this and {@code val}. If the result would have more than 64
* bits, returns the low 64 bits of the result.
*/
public UnsignedLong multiply(UnsignedLong val) {
checkNotNull(val);
return asUnsigned(value * val.value);
}
/**
* Returns the result of dividing this by {@code val}.
*/
public UnsignedLong divide(UnsignedLong val) {
checkNotNull(val);
return asUnsigned(UnsignedLongs.divide(value, val.value));
}
/**
* Returns the remainder of dividing this by {@code val}.
*/
public UnsignedLong remainder(UnsignedLong val) {
checkNotNull(val);
return asUnsigned(UnsignedLongs.remainder(value, val.value));
}
/**
* Returns the value of this {@code UnsignedLong} as an {@code int}.
*/
@Override
public int intValue() {
return (int) value;
}
/**
* Returns the value of this {@code UnsignedLong} as a {@code long}. This is an inverse operation
* to {@link #asUnsigned}.
*
* <p>Note that if this {@code UnsignedLong} holds a value {@code >= 2^63}, the returned value
* will be equal to {@code this - 2^64}.
*/
@Override
public long longValue() {
return value;
}
/**
* Returns the value of this {@code UnsignedLong} as a {@code float}, analogous to a widening
* primitive conversion from {@code long} to {@code float}, and correctly rounded.
*/
@Override
public float floatValue() {
@SuppressWarnings("cast")
float fValue = (float) (value & UNSIGNED_MASK);
if (value < 0) {
fValue += 0x1.0p63f;
}
return fValue;
}
/**
* Returns the value of this {@code UnsignedLong} as a {@code double}, analogous to a widening
* primitive conversion from {@code long} to {@code double}, and correctly rounded.
*/
@Override
public double doubleValue() {
@SuppressWarnings("cast")
double dValue = (double) (value & UNSIGNED_MASK);
if (value < 0) {
dValue += 0x1.0p63;
}
return dValue;
}
/**
* Returns the value of this {@code UnsignedLong} as a {@link BigInteger}.
*/
public BigInteger bigIntegerValue() {
BigInteger bigInt = BigInteger.valueOf(value & UNSIGNED_MASK);
if (value < 0) {
bigInt = bigInt.setBit(Long.SIZE - 1);
}
return bigInt;
}
@Override
public int compareTo(UnsignedLong o) {
checkNotNull(o);
return UnsignedLongs.compare(value, o.value);
}
@Override
public int hashCode() {
return Longs.hashCode(value);
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof UnsignedLong) {
UnsignedLong other = (UnsignedLong) obj;
return value == other.value;
}
return false;
}
/**
* Returns a string representation of the {@code UnsignedLong} value, in base 10.
*/
@Override
public String toString() {
return UnsignedLongs.toString(value);
}
/**
* Returns a string representation of the {@code UnsignedLong} value, in base {@code radix}. If
* {@code radix < Character.MIN_RADIX} or {@code radix > Character.MAX_RADIX}, the radix
* {@code 10} is used.
*/
public String toString(int radix) {
return UnsignedLongs.toString(value, radix);
}
}
| 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.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
/**
* Static utility methods pertaining to {@code long} primitives, that are not
* already found in either {@link Long} or {@link Arrays}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible
public final class Longs {
private Longs() {}
/**
* The number of bytes required to represent a primitive {@code long}
* value.
*/
public static final int BYTES = Long.SIZE / Byte.SIZE;
/**
* The largest power of two that can be represented as a {@code long}.
*
* @since 10.0
*/
public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2);
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Long) value).hashCode()}.
*
* <p>This method always return the value specified by {@link
* Long#hashCode()} in java, which might be different from
* {@code ((Long) value).hashCode()} in GWT because {@link Long#hashCode()}
* in GWT does not obey the JRE contract.
*
* @param value a primitive {@code long} value
* @return a hash code for the value
*/
public static int hashCode(long value) {
return (int) (value ^ (value >>> 32));
}
/**
* Compares the two specified {@code long} values. The sign of the value
* returned is the same as that of {@code ((Long) a).compareTo(b)}.
*
* @param a the first {@code long} to compare
* @param b the second {@code long} to compare
* @return a negative value if {@code a} is less than {@code b}; a positive
* value if {@code a} is greater than {@code b}; or zero if they are equal
*/
public static int compare(long a, long b) {
return (a < b) ? -1 : ((a > b) ? 1 : 0);
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}.
*
* @param array an array of {@code long} values, possibly empty
* @param target a primitive {@code long} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(long[] array, long target) {
for (long value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code long} values, possibly empty
* @param target a primitive {@code long} value
* @return the least index {@code i} for which {@code array[i] == target}, or
* {@code -1} if no such index exists.
*/
public static int indexOf(long[] array, long target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
long[] array, long target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the start position of the first occurrence of the specified {@code
* target} within {@code array}, or {@code -1} if there is no such occurrence.
*
* <p>More formally, returns the lowest index {@code i} such that {@code
* java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
* the same elements as {@code target}.
*
* @param array the array to search for the sequence {@code target}
* @param target the array to search for as a sub-sequence of {@code array}
*/
public static int indexOf(long[] array, long[] target) {
checkNotNull(array, "array");
checkNotNull(target, "target");
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Returns the index of the last appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code long} values, possibly empty
* @param target a primitive {@code long} value
* @return the greatest index {@code i} for which {@code array[i] == target},
* or {@code -1} if no such index exists.
*/
public static int lastIndexOf(long[] array, long target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
long[] array, long target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the least value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code long} values
* @return the value present in {@code array} that is less than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static long min(long... array) {
checkArgument(array.length > 0);
long min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
/**
* Returns the greatest value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code long} values
* @return the value present in {@code array} that is greater than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static long max(long... array) {
checkArgument(array.length > 0);
long max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new long[] {a, b}, new long[] {}, new
* long[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code long} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static long[] concat(long[]... arrays) {
int length = 0;
for (long[] array : arrays) {
length += array.length;
}
long[] result = new long[length];
int pos = 0;
for (long[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns a big-endian representation of {@code value} in an 8-element byte
* array; equivalent to {@code ByteBuffer.allocate(8).putLong(value).array()}.
* For example, the input value {@code 0x1213141516171819L} would yield the
* byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}}.
*
* <p>If you need to convert and concatenate several values (possibly even of
* different types), use a shared {@link java.nio.ByteBuffer} instance, or use
* {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable
* buffer.
*/
public static byte[] toByteArray(long value) {
// Note that this code needs to stay compatible with GWT, which has known
// bugs when narrowing byte casts of long values occur.
byte[] result = new byte[8];
for (int i = 7; i >= 0; i--) {
result[i] = (byte) (value & 0xffL);
value >>= 8;
}
return result;
}
/**
* Returns the {@code long} value whose big-endian representation is
* stored in the first 8 bytes of {@code bytes}; equivalent to {@code
* ByteBuffer.wrap(bytes).getLong()}. For example, the input byte array
* {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the
* {@code long} value {@code 0x1213141516171819L}.
*
* <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that
* library exposes much more flexibility at little cost in readability.
*
* @throws IllegalArgumentException if {@code bytes} has fewer than 8
* elements
*/
public static long fromByteArray(byte[] bytes) {
checkArgument(bytes.length >= BYTES,
"array too small: %s < %s", bytes.length, BYTES);
return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3],
bytes[4], bytes[5], bytes[6], bytes[7]) ;
}
/**
* Returns the {@code long} value whose byte representation is the given 8
* bytes, in big-endian order; equivalent to {@code Longs.fromByteArray(new
* byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}.
*
* @since 7.0
*/
public static long fromBytes(byte b1, byte b2, byte b3, byte b4,
byte b5, byte b6, byte b7, byte b8) {
return (b1 & 0xFFL) << 56
| (b2 & 0xFFL) << 48
| (b3 & 0xFFL) << 40
| (b4 & 0xFFL) << 32
| (b5 & 0xFFL) << 24
| (b6 & 0xFFL) << 16
| (b7 & 0xFFL) << 8
| (b8 & 0xFFL);
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static long[] ensureCapacity(
long[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static long[] copyOf(long[] original, int length) {
long[] copy = new long[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code long} values separated
* by {@code separator}. For example, {@code join("-", 1L, 2L, 3L)} returns
* the string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code long} values, possibly empty
*/
public static String join(String separator, long... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 10);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code long} arrays
* lexicographically. That is, it compares, using {@link
* #compare(long, long)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example,
* {@code [] < [1L] < [1L, 2L] < [2L]}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(long[], long[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<long[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<long[]> {
INSTANCE;
@Override
public int compare(long[] left, long[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Longs.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code long} value in the manner of {@link Number#longValue}.
*
* <p>Elements are copied from the argument collection as if by {@code
* collection.toArray()}. Calling this method is as thread-safe as calling
* that method.
*
* @param collection a collection of {@code Number} instances
* @return an array containing the same values as {@code collection}, in the
* same order, converted to primitives
* @throws NullPointerException if {@code collection} or any of its elements
* is null
* @since 1.0 (parameter was {@code Collection<Long>} before 12.0)
*/
public static long[] toArray(Collection<? extends Number> collection) {
if (collection instanceof LongArrayAsList) {
return ((LongArrayAsList) collection).toLongArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
long[] array = new long[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).longValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Long} objects written to or read from it. For example, whether
* {@code list.get(0) == list.get(0)} is true for the returned list is
* unspecified.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Long> asList(long... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new LongArrayAsList(backingArray);
}
@GwtCompatible
private static class LongArrayAsList extends AbstractList<Long>
implements RandomAccess, Serializable {
final long[] array;
final int start;
final int end;
LongArrayAsList(long[] array) {
this(array, 0, array.length);
}
LongArrayAsList(long[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Long get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Long)
&& Longs.indexOf(array, (Long) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Long) {
int i = Longs.indexOf(array, (Long) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Long) {
int i = Longs.lastIndexOf(array, (Long) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Long set(int index, Long element) {
checkElementIndex(index, size());
long oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Long> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new LongArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof LongArrayAsList) {
LongArrayAsList that = (LongArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Longs.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 10);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
long[] toLongArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
long[] result = new long[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
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.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.RandomAccess;
/**
* Static utility methods pertaining to {@code byte} primitives, that are not
* already found in either {@link Byte} or {@link Arrays}, <i>and interpret
* bytes as neither signed nor unsigned</i>. The methods which specifically
* treat bytes as signed or unsigned are found in {@link SignedBytes} and {@link
* UnsignedBytes}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
// TODO(kevinb): how to prevent warning on UnsignedBytes when building GWT
// javadoc?
@GwtCompatible
public final class Bytes {
private Bytes() {}
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Byte) value).hashCode()}.
*
* @param value a primitive {@code byte} value
* @return a hash code for the value
*/
public static int hashCode(byte value) {
return value;
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}.
*
* @param array an array of {@code byte} values, possibly empty
* @param target a primitive {@code byte} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(byte[] array, byte target) {
for (byte value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code byte} values, possibly empty
* @param target a primitive {@code byte} value
* @return the least index {@code i} for which {@code array[i] == target}, or
* {@code -1} if no such index exists.
*/
public static int indexOf(byte[] array, byte target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
byte[] array, byte target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the start position of the first occurrence of the specified {@code
* target} within {@code array}, or {@code -1} if there is no such occurrence.
*
* <p>More formally, returns the lowest index {@code i} such that {@code
* java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
* the same elements as {@code target}.
*
* @param array the array to search for the sequence {@code target}
* @param target the array to search for as a sub-sequence of {@code array}
*/
public static int indexOf(byte[] array, byte[] target) {
checkNotNull(array, "array");
checkNotNull(target, "target");
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Returns the index of the last appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code byte} values, possibly empty
* @param target a primitive {@code byte} value
* @return the greatest index {@code i} for which {@code array[i] == target},
* or {@code -1} if no such index exists.
*/
public static int lastIndexOf(byte[] array, byte target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
byte[] array, byte target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new byte[] {a, b}, new byte[] {}, new
* byte[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code byte} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static byte[] concat(byte[]... arrays) {
int length = 0;
for (byte[] array : arrays) {
length += array.length;
}
byte[] result = new byte[length];
int pos = 0;
for (byte[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static byte[] ensureCapacity(
byte[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static byte[] copyOf(byte[] original, int length) {
byte[] copy = new byte[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code byte} value in the manner of {@link Number#byteValue}.
*
* <p>Elements are copied from the argument collection as if by {@code
* collection.toArray()}. Calling this method is as thread-safe as calling
* that method.
*
* @param collection a collection of {@code Number} instances
* @return an array containing the same values as {@code collection}, in the
* same order, converted to primitives
* @throws NullPointerException if {@code collection} or any of its elements
* is null
* @since 1.0 (parameter was {@code Collection<Byte>} before 12.0)
*/
public static byte[] toArray(Collection<? extends Number> collection) {
if (collection instanceof ByteArrayAsList) {
return ((ByteArrayAsList) collection).toByteArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
byte[] array = new byte[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).byteValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Byte} objects written to or read from it. For example, whether
* {@code list.get(0) == list.get(0)} is true for the returned list is
* unspecified.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Byte> asList(byte... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new ByteArrayAsList(backingArray);
}
@GwtCompatible
private static class ByteArrayAsList extends AbstractList<Byte>
implements RandomAccess, Serializable {
final byte[] array;
final int start;
final int end;
ByteArrayAsList(byte[] array) {
this(array, 0, array.length);
}
ByteArrayAsList(byte[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Byte get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Byte)
&& Bytes.indexOf(array, (Byte) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Byte) {
int i = Bytes.indexOf(array, (Byte) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Byte) {
int i = Bytes.lastIndexOf(array, (Byte) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Byte set(int index, Byte element) {
checkElementIndex(index, size());
byte oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Byte> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new ByteArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof ByteArrayAsList) {
ByteArrayAsList that = (ByteArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Bytes.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 5);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
byte[] toByteArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
byte[] result = new byte[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
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.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
/**
* Static utility methods pertaining to {@code short} primitives, that are not
* already found in either {@link Short} or {@link Arrays}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Shorts {
private Shorts() {}
/**
* The number of bytes required to represent a primitive {@code short}
* value.
*/
public static final int BYTES = Short.SIZE / Byte.SIZE;
/**
* The largest power of two that can be represented as a {@code short}.
*
* @since 10.0
*/
public static final short MAX_POWER_OF_TWO = 1 << (Short.SIZE - 2);
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Short) value).hashCode()}.
*
* @param value a primitive {@code short} value
* @return a hash code for the value
*/
public static int hashCode(short value) {
return value;
}
/**
* Returns the {@code short} value that is equal to {@code value}, if
* possible.
*
* @param value any value in the range of the {@code short} type
* @return the {@code short} value that equals {@code value}
* @throws IllegalArgumentException if {@code value} is greater than {@link
* Short#MAX_VALUE} or less than {@link Short#MIN_VALUE}
*/
public static short checkedCast(long value) {
short result = (short) value;
checkArgument(result == value, "Out of range: %s", value);
return result;
}
/**
* Returns the {@code short} nearest in value to {@code value}.
*
* @param value any {@code long} value
* @return the same value cast to {@code short} if it is in the range of the
* {@code short} type, {@link Short#MAX_VALUE} if it is too large,
* or {@link Short#MIN_VALUE} if it is too small
*/
public static short saturatedCast(long value) {
if (value > Short.MAX_VALUE) {
return Short.MAX_VALUE;
}
if (value < Short.MIN_VALUE) {
return Short.MIN_VALUE;
}
return (short) value;
}
/**
* Compares the two specified {@code short} values. The sign of the value
* returned is the same as that of {@code ((Short) a).compareTo(b)}.
*
* @param a the first {@code short} to compare
* @param b the second {@code short} to compare
* @return a negative value if {@code a} is less than {@code b}; a positive
* value if {@code a} is greater than {@code b}; or zero if they are equal
*/
public static int compare(short a, short b) {
return a - b; // safe due to restricted range
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}.
*
* @param array an array of {@code short} values, possibly empty
* @param target a primitive {@code short} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(short[] array, short target) {
for (short value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code short} values, possibly empty
* @param target a primitive {@code short} value
* @return the least index {@code i} for which {@code array[i] == target}, or
* {@code -1} if no such index exists.
*/
public static int indexOf(short[] array, short target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
short[] array, short target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the start position of the first occurrence of the specified {@code
* target} within {@code array}, or {@code -1} if there is no such occurrence.
*
* <p>More formally, returns the lowest index {@code i} such that {@code
* java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
* the same elements as {@code target}.
*
* @param array the array to search for the sequence {@code target}
* @param target the array to search for as a sub-sequence of {@code array}
*/
public static int indexOf(short[] array, short[] target) {
checkNotNull(array, "array");
checkNotNull(target, "target");
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Returns the index of the last appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code short} values, possibly empty
* @param target a primitive {@code short} value
* @return the greatest index {@code i} for which {@code array[i] == target},
* or {@code -1} if no such index exists.
*/
public static int lastIndexOf(short[] array, short target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
short[] array, short target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the least value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code short} values
* @return the value present in {@code array} that is less than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static short min(short... array) {
checkArgument(array.length > 0);
short min = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}
/**
* Returns the greatest value present in {@code array}.
*
* @param array a <i>nonempty</i> array of {@code short} values
* @return the value present in {@code array} that is greater than or equal to
* every other value in the array
* @throws IllegalArgumentException if {@code array} is empty
*/
public static short max(short... array) {
checkArgument(array.length > 0);
short max = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new short[] {a, b}, new short[] {}, new
* short[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code short} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static short[] concat(short[]... arrays) {
int length = 0;
for (short[] array : arrays) {
length += array.length;
}
short[] result = new short[length];
int pos = 0;
for (short[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns a big-endian representation of {@code value} in a 2-element byte
* array; equivalent to {@code
* ByteBuffer.allocate(2).putShort(value).array()}. For example, the input
* value {@code (short) 0x1234} would yield the byte array {@code {0x12,
* 0x34}}.
*
* <p>If you need to convert and concatenate several values (possibly even of
* different types), use a shared {@link java.nio.ByteBuffer} instance, or use
* {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable
* buffer.
*/
@GwtIncompatible("doesn't work")
public static byte[] toByteArray(short value) {
return new byte[] {
(byte) (value >> 8),
(byte) value};
}
/**
* Returns the {@code short} value whose big-endian representation is
* stored in the first 2 bytes of {@code bytes}; equivalent to {@code
* ByteBuffer.wrap(bytes).getShort()}. For example, the input byte array
* {@code {0x54, 0x32}} would yield the {@code short} value {@code 0x5432}.
*
* <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that
* library exposes much more flexibility at little cost in readability.
*
* @throws IllegalArgumentException if {@code bytes} has fewer than 2
* elements
*/
@GwtIncompatible("doesn't work")
public static short fromByteArray(byte[] bytes) {
checkArgument(bytes.length >= BYTES,
"array too small: %s < %s", bytes.length, BYTES);
return fromBytes(bytes[0], bytes[1]);
}
/**
* Returns the {@code short} value whose byte representation is the given 2
* bytes, in big-endian order; equivalent to {@code Shorts.fromByteArray(new
* byte[] {b1, b2})}.
*
* @since 7.0
*/
@GwtIncompatible("doesn't work")
public static short fromBytes(byte b1, byte b2) {
return (short) ((b1 << 8) | (b2 & 0xFF));
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static short[] ensureCapacity(
short[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static short[] copyOf(short[] original, int length) {
short[] copy = new short[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code short} values separated
* by {@code separator}. For example, {@code join("-", (short) 1, (short) 2,
* (short) 3)} returns the string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code short} values, possibly empty
*/
public static String join(String separator, short... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 6);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code short} arrays
* lexicographically. That is, it compares, using {@link
* #compare(short, short)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example, {@code [] < [(short) 1] <
* [(short) 1, (short) 2] < [(short) 2]}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(short[], short[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<short[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<short[]> {
INSTANCE;
@Override
public int compare(short[] left, short[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Shorts.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Returns an array containing each value of {@code collection}, converted to
* a {@code short} value in the manner of {@link Number#shortValue}.
*
* <p>Elements are copied from the argument collection as if by {@code
* collection.toArray()}. Calling this method is as thread-safe as calling
* that method.
*
* @param collection a collection of {@code Number} instances
* @return an array containing the same values as {@code collection}, in the
* same order, converted to primitives
* @throws NullPointerException if {@code collection} or any of its elements
* is null
* @since 1.0 (parameter was {@code Collection<Short>} before 12.0)
*/
public static short[] toArray(Collection<? extends Number> collection) {
if (collection instanceof ShortArrayAsList) {
return ((ShortArrayAsList) collection).toShortArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
short[] array = new short[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = ((Number) checkNotNull(boxedArray[i])).shortValue();
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Short} objects written to or read from it. For example, whether
* {@code list.get(0) == list.get(0)} is true for the returned list is
* unspecified.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Short> asList(short... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new ShortArrayAsList(backingArray);
}
@GwtCompatible
private static class ShortArrayAsList extends AbstractList<Short>
implements RandomAccess, Serializable {
final short[] array;
final int start;
final int end;
ShortArrayAsList(short[] array) {
this(array, 0, array.length);
}
ShortArrayAsList(short[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Short get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Short)
&& Shorts.indexOf(array, (Short) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Short) {
int i = Shorts.indexOf(array, (Short) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Short) {
int i = Shorts.lastIndexOf(array, (Short) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Short set(int index, Short element) {
checkElementIndex(index, size());
short oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Short> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new ShortArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof ShortArrayAsList) {
ShortArrayAsList that = (ShortArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Shorts.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 6);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
short[] toShortArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
short[] result = new short[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
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.primitives;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.RandomAccess;
/**
* Static utility methods pertaining to {@code boolean} primitives, that are not
* already found in either {@link Boolean} or {@link Arrays}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained">
* primitive utilities</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@GwtCompatible
public final class Booleans {
private Booleans() {}
/**
* Returns a hash code for {@code value}; equal to the result of invoking
* {@code ((Boolean) value).hashCode()}.
*
* @param value a primitive {@code boolean} value
* @return a hash code for the value
*/
public static int hashCode(boolean value) {
return value ? 1231 : 1237;
}
/**
* Compares the two specified {@code boolean} values in the standard way
* ({@code false} is considered less than {@code true}). The sign of the
* value returned is the same as that of {@code ((Boolean) a).compareTo(b)}.
*
* @param a the first {@code boolean} to compare
* @param b the second {@code boolean} to compare
* @return a positive number if only {@code a} is {@code true}, a negative
* number if only {@code b} is true, or zero if {@code a == b}
*/
public static int compare(boolean a, boolean b) {
return (a == b) ? 0 : (a ? 1 : -1);
}
/**
* Returns {@code true} if {@code target} is present as an element anywhere in
* {@code array}.
*
* <p><b>Note:</b> consider representing the array as a {@link
* BitSet} instead, replacing {@code Booleans.contains(array, true)}
* with {@code !bitSet.isEmpty()} and {@code Booleans.contains(array, false)}
* with {@code bitSet.nextClearBit(0) == sizeOfBitSet}.
*
* @param array an array of {@code boolean} values, possibly empty
* @param target a primitive {@code boolean} value
* @return {@code true} if {@code array[i] == target} for some value of {@code
* i}
*/
public static boolean contains(boolean[] array, boolean target) {
for (boolean value : array) {
if (value == target) {
return true;
}
}
return false;
}
/**
* Returns the index of the first appearance of the value {@code target} in
* {@code array}.
*
* <p><b>Note:</b> consider representing the array as a {@link BitSet}
* instead, and using {@link BitSet#nextSetBit(int)} or {@link
* BitSet#nextClearBit(int)}.
*
* @param array an array of {@code boolean} values, possibly empty
* @param target a primitive {@code boolean} value
* @return the least index {@code i} for which {@code array[i] == target}, or
* {@code -1} if no such index exists.
*/
public static int indexOf(boolean[] array, boolean target) {
return indexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int indexOf(
boolean[] array, boolean target, int start, int end) {
for (int i = start; i < end; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the start position of the first occurrence of the specified {@code
* target} within {@code array}, or {@code -1} if there is no such occurrence.
*
* <p>More formally, returns the lowest index {@code i} such that {@code
* java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
* the same elements as {@code target}.
*
* @param array the array to search for the sequence {@code target}
* @param target the array to search for as a sub-sequence of {@code array}
*/
public static int indexOf(boolean[] array, boolean[] target) {
checkNotNull(array, "array");
checkNotNull(target, "target");
if (target.length == 0) {
return 0;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* Returns the index of the last appearance of the value {@code target} in
* {@code array}.
*
* @param array an array of {@code boolean} values, possibly empty
* @param target a primitive {@code boolean} value
* @return the greatest index {@code i} for which {@code array[i] == target},
* or {@code -1} if no such index exists.
*/
public static int lastIndexOf(boolean[] array, boolean target) {
return lastIndexOf(array, target, 0, array.length);
}
// TODO(kevinb): consider making this public
private static int lastIndexOf(
boolean[] array, boolean target, int start, int end) {
for (int i = end - 1; i >= start; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
/**
* Returns the values from each provided array combined into a single array.
* For example, {@code concat(new boolean[] {a, b}, new boolean[] {}, new
* boolean[] {c}} returns the array {@code {a, b, c}}.
*
* @param arrays zero or more {@code boolean} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static boolean[] concat(boolean[]... arrays) {
int length = 0;
for (boolean[] array : arrays) {
length += array.length;
}
boolean[] result = new boolean[length];
int pos = 0;
for (boolean[] array : arrays) {
System.arraycopy(array, 0, result, pos, array.length);
pos += array.length;
}
return result;
}
/**
* Returns an array containing the same values as {@code array}, but
* guaranteed to be of a specified minimum length. If {@code array} already
* has a length of at least {@code minLength}, it is returned directly.
* Otherwise, a new array of size {@code minLength + padding} is returned,
* containing the values of {@code array}, and zeroes in the remaining places.
*
* @param array the source array
* @param minLength the minimum length the returned array must guarantee
* @param padding an extra amount to "grow" the array by if growth is
* necessary
* @throws IllegalArgumentException if {@code minLength} or {@code padding} is
* negative
* @return an array containing the values of {@code array}, with guaranteed
* minimum length {@code minLength}
*/
public static boolean[] ensureCapacity(
boolean[] array, int minLength, int padding) {
checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
checkArgument(padding >= 0, "Invalid padding: %s", padding);
return (array.length < minLength)
? copyOf(array, minLength + padding)
: array;
}
// Arrays.copyOf() requires Java 6
private static boolean[] copyOf(boolean[] original, int length) {
boolean[] copy = new boolean[length];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
return copy;
}
/**
* Returns a string containing the supplied {@code boolean} values separated
* by {@code separator}. For example, {@code join("-", false, true, false)}
* returns the string {@code "false-true-false"}.
*
* @param separator the text that should appear between consecutive values in
* the resulting string (but not at the start or end)
* @param array an array of {@code boolean} values, possibly empty
*/
public static String join(String separator, boolean... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 7);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
/**
* Returns a comparator that compares two {@code boolean} arrays
* lexicographically. That is, it compares, using {@link
* #compare(boolean, boolean)}), the first pair of values that follow any
* common prefix, or when one array is a prefix of the other, treats the
* shorter array as the lesser. For example,
* {@code [] < [false] < [false, true] < [true]}.
*
* <p>The returned comparator is inconsistent with {@link
* Object#equals(Object)} (since arrays support only identity equality), but
* it is consistent with {@link Arrays#equals(boolean[], boolean[])}.
*
* @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
* Lexicographical order article at Wikipedia</a>
* @since 2.0
*/
public static Comparator<boolean[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<boolean[]> {
INSTANCE;
@Override
public int compare(boolean[] left, boolean[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Booleans.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
}
/**
* Copies a collection of {@code Boolean} instances into a new array of
* primitive {@code boolean} values.
*
* <p>Elements are copied from the argument collection as if by {@code
* collection.toArray()}. Calling this method is as thread-safe as calling
* that method.
*
* <p><b>Note:</b> consider representing the collection as a {@link
* BitSet} instead.
*
* @param collection a collection of {@code Boolean} objects
* @return an array containing the same values as {@code collection}, in the
* same order, converted to primitives
* @throws NullPointerException if {@code collection} or any of its elements
* is null
*/
public static boolean[] toArray(Collection<Boolean> collection) {
if (collection instanceof BooleanArrayAsList) {
return ((BooleanArrayAsList) collection).toBooleanArray();
}
Object[] boxedArray = collection.toArray();
int len = boxedArray.length;
boolean[] array = new boolean[len];
for (int i = 0; i < len; i++) {
// checkNotNull for GWT (do not optimize)
array[i] = (Boolean) checkNotNull(boxedArray[i]);
}
return array;
}
/**
* Returns a fixed-size list backed by the specified array, similar to {@link
* Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
* but any attempt to set a value to {@code null} will result in a {@link
* NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of
* {@code Boolean} objects written to or read from it. For example, whether
* {@code list.get(0) == list.get(0)} is true for the returned list is
* unspecified.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Boolean> asList(boolean... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new BooleanArrayAsList(backingArray);
}
@GwtCompatible
private static class BooleanArrayAsList extends AbstractList<Boolean>
implements RandomAccess, Serializable {
final boolean[] array;
final int start;
final int end;
BooleanArrayAsList(boolean[] array) {
this(array, 0, array.length);
}
BooleanArrayAsList(boolean[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override public int size() {
return end - start;
}
@Override public boolean isEmpty() {
return false;
}
@Override public Boolean get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Boolean)
&& Booleans.indexOf(array, (Boolean) target, start, end) != -1;
}
@Override public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Boolean) {
int i = Booleans.indexOf(array, (Boolean) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Boolean) {
int i = Booleans.lastIndexOf(array, (Boolean) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override public Boolean set(int index, Boolean element) {
checkElementIndex(index, size());
boolean oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override public List<Boolean> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new BooleanArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof BooleanArrayAsList) {
BooleanArrayAsList that = (BooleanArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Booleans.hashCode(array[i]);
}
return result;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder(size() * 7);
builder.append(array[start] ? "[true" : "[false");
for (int i = start + 1; i < end; i++) {
builder.append(array[i] ? ", true" : ", false");
}
return builder.append(']').toString();
}
boolean[] toBooleanArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
boolean[] result = new boolean[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
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.primitives;
import com.google.common.annotations.GwtCompatible;
/**
* A string to be parsed as a number and the radix to interpret it in.
*/
@GwtCompatible
final class ParseRequest {
final String rawValue;
final int radix;
private ParseRequest(String rawValue, int radix) {
this.rawValue = rawValue;
this.radix = radix;
}
static ParseRequest fromString(String stringValue) {
if (stringValue.length() == 0) {
throw new NumberFormatException("empty string");
}
// Handle radix specifier if present
String rawValue;
int radix;
char firstChar = stringValue.charAt(0);
if (stringValue.startsWith("0x") || stringValue.startsWith("0X")) {
rawValue = stringValue.substring(2);
radix = 16;
} else if (firstChar == '#') {
rawValue = stringValue.substring(1);
radix = 16;
} else if (firstChar == '0' && stringValue.length() > 1) {
rawValue = stringValue.substring(1);
radix = 8;
} else {
rawValue = stringValue;
radix = 10;
}
return new ParseRequest(rawValue, radix);
}
}
| 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.eventbus;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.SetMultimap;
import com.google.common.reflect.TypeToken;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Dispatches events to listeners, and provides ways for listeners to register
* themselves.
*
* <p>The EventBus allows publish-subscribe-style communication between
* components without requiring the components to explicitly register with one
* another (and thus be aware of each other). It is designed exclusively to
* replace traditional Java in-process event distribution using explicit
* registration. It is <em>not</em> a general-purpose publish-subscribe system,
* nor is it intended for interprocess communication.
*
* <h2>Receiving Events</h2>
* To receive events, an object should:<ol>
* <li>Expose a public method, known as the <i>event handler</i>, which accepts
* a single argument of the type of event desired;</li>
* <li>Mark it with a {@link Subscribe} annotation;</li>
* <li>Pass itself to an EventBus instance's {@link #register(Object)} method.
* </li>
* </ol>
*
* <h2>Posting Events</h2>
* To post an event, simply provide the event object to the
* {@link #post(Object)} method. The EventBus instance will determine the type
* of event and route it to all registered listeners.
*
* <p>Events are routed based on their type — an event will be delivered
* to any handler for any type to which the event is <em>assignable.</em> This
* includes implemented interfaces, all superclasses, and all interfaces
* implemented by superclasses.
*
* <p>When {@code post} is called, all registered handlers for an event are run
* in sequence, so handlers should be reasonably quick. If an event may trigger
* an extended process (such as a database load), spawn a thread or queue it for
* later. (For a convenient way to do this, use an {@link AsyncEventBus}.)
*
* <h2>Handler Methods</h2>
* Event handler methods must accept only one argument: the event.
*
* <p>Handlers should not, in general, throw. If they do, the EventBus will
* catch and log the exception. This is rarely the right solution for error
* handling and should not be relied upon; it is intended solely to help find
* problems during development.
*
* <p>The EventBus guarantees that it will not call a handler method from
* multiple threads simultaneously, unless the method explicitly allows it by
* bearing the {@link AllowConcurrentEvents} annotation. If this annotation is
* not present, handler methods need not worry about being reentrant, unless
* also called from outside the EventBus.
*
* <h2>Dead Events</h2>
* If an event is posted, but no registered handlers can accept it, it is
* considered "dead." To give the system a second chance to handle dead events,
* they are wrapped in an instance of {@link DeadEvent} and reposted.
*
* <p>If a handler for a supertype of all events (such as Object) is registered,
* no event will ever be considered dead, and no DeadEvents will be generated.
* Accordingly, while DeadEvent extends {@link Object}, a handler registered to
* receive any Object will never receive a DeadEvent.
*
* <p>This class is safe for concurrent use.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/EventBusExplained">
* {@code EventBus}</a>.
*
* @author Cliff Biffle
* @since 10.0
*/
@Beta
public class EventBus {
/**
* A thread-safe cache for flattenHierarchy(). The Class class is immutable. This cache is shared
* across all EventBus instances, which greatly improves performance if multiple such instances
* are created and objects of the same class are posted on all of them.
*/
private static final LoadingCache<Class<?>, Set<Class<?>>> flattenHierarchyCache =
CacheBuilder.newBuilder()
.weakKeys()
.build(new CacheLoader<Class<?>, Set<Class<?>>>() {
@SuppressWarnings({"unchecked", "rawtypes"}) // safe cast
@Override
public Set<Class<?>> load(Class<?> concreteClass) {
return (Set) TypeToken.of(concreteClass).getTypes().rawTypes();
}
});
/**
* All registered event handlers, indexed by event type.
*
* <p>This SetMultimap is NOT safe for concurrent use; all access should be
* made after acquiring a read or write lock via {@link #handlersByTypeLock}.
*/
private final SetMultimap<Class<?>, EventHandler> handlersByType =
HashMultimap.create();
private final ReadWriteLock handlersByTypeLock = new ReentrantReadWriteLock();
/**
* Logger for event dispatch failures. Named by the fully-qualified name of
* this class, followed by the identifier provided at construction.
*/
private final Logger logger;
/**
* Strategy for finding handler methods in registered objects. Currently,
* only the {@link AnnotatedHandlerFinder} is supported, but this is
* encapsulated for future expansion.
*/
private final HandlerFindingStrategy finder = new AnnotatedHandlerFinder();
/** queues of events for the current thread to dispatch */
private final ThreadLocal<Queue<EventWithHandler>> eventsToDispatch =
new ThreadLocal<Queue<EventWithHandler>>() {
@Override protected Queue<EventWithHandler> initialValue() {
return new LinkedList<EventWithHandler>();
}
};
/** true if the current thread is currently dispatching an event */
private final ThreadLocal<Boolean> isDispatching =
new ThreadLocal<Boolean>() {
@Override protected Boolean initialValue() {
return false;
}
};
/**
* Creates a new EventBus named "default".
*/
public EventBus() {
this("default");
}
/**
* Creates a new EventBus with the given {@code identifier}.
*
* @param identifier a brief name for this bus, for logging purposes. Should
* be a valid Java identifier.
*/
public EventBus(String identifier) {
logger = Logger.getLogger(EventBus.class.getName() + "." + identifier);
}
/**
* Registers all handler methods on {@code object} to receive events.
* Handler methods are selected and classified using this EventBus's
* {@link HandlerFindingStrategy}; the default strategy is the
* {@link AnnotatedHandlerFinder}.
*
* @param object object whose handler methods should be registered.
*/
public void register(Object object) {
Multimap<Class<?>, EventHandler> methodsInListener =
finder.findAllHandlers(object);
handlersByTypeLock.writeLock().lock();
try {
handlersByType.putAll(methodsInListener);
} finally {
handlersByTypeLock.writeLock().unlock();
}
}
/**
* Unregisters all handler methods on a registered {@code object}.
*
* @param object object whose handler methods should be unregistered.
* @throws IllegalArgumentException if the object was not previously registered.
*/
public void unregister(Object object) {
Multimap<Class<?>, EventHandler> methodsInListener = finder.findAllHandlers(object);
for (Entry<Class<?>, Collection<EventHandler>> entry : methodsInListener.asMap().entrySet()) {
Class<?> eventType = entry.getKey();
Collection<EventHandler> eventMethodsInListener = entry.getValue();
handlersByTypeLock.writeLock().lock();
try {
Set<EventHandler> currentHandlers = handlersByType.get(eventType);
if (!currentHandlers.containsAll(eventMethodsInListener)) {
throw new IllegalArgumentException(
"missing event handler for an annotated method. Is " + object + " registered?");
}
currentHandlers.removeAll(eventMethodsInListener);
} finally {
handlersByTypeLock.writeLock().unlock();
}
}
}
/**
* Posts an event to all registered handlers. This method will return
* successfully after the event has been posted to all handlers, and
* regardless of any exceptions thrown by handlers.
*
* <p>If no handlers have been subscribed for {@code event}'s class, and
* {@code event} is not already a {@link DeadEvent}, it will be wrapped in a
* DeadEvent and reposted.
*
* @param event event to post.
*/
public void post(Object event) {
Set<Class<?>> dispatchTypes = flattenHierarchy(event.getClass());
boolean dispatched = false;
for (Class<?> eventType : dispatchTypes) {
handlersByTypeLock.readLock().lock();
try {
Set<EventHandler> wrappers = handlersByType.get(eventType);
if (!wrappers.isEmpty()) {
dispatched = true;
for (EventHandler wrapper : wrappers) {
enqueueEvent(event, wrapper);
}
}
} finally {
handlersByTypeLock.readLock().unlock();
}
}
if (!dispatched && !(event instanceof DeadEvent)) {
post(new DeadEvent(this, event));
}
dispatchQueuedEvents();
}
/**
* Queue the {@code event} for dispatch during
* {@link #dispatchQueuedEvents()}. Events are queued in-order of occurrence
* so they can be dispatched in the same order.
*/
void enqueueEvent(Object event, EventHandler handler) {
eventsToDispatch.get().offer(new EventWithHandler(event, handler));
}
/**
* Drain the queue of events to be dispatched. As the queue is being drained,
* new events may be posted to the end of the queue.
*/
void dispatchQueuedEvents() {
// don't dispatch if we're already dispatching, that would allow reentrancy
// and out-of-order events. Instead, leave the events to be dispatched
// after the in-progress dispatch is complete.
if (isDispatching.get()) {
return;
}
isDispatching.set(true);
try {
Queue<EventWithHandler> events = eventsToDispatch.get();
EventWithHandler eventWithHandler;
while ((eventWithHandler = events.poll()) != null) {
dispatch(eventWithHandler.event, eventWithHandler.handler);
}
} finally {
isDispatching.set(false);
}
}
/**
* Dispatches {@code event} to the handler in {@code wrapper}. This method
* is an appropriate override point for subclasses that wish to make
* event delivery asynchronous.
*
* @param event event to dispatch.
* @param wrapper wrapper that will call the handler.
*/
void dispatch(Object event, EventHandler wrapper) {
try {
wrapper.handleEvent(event);
} catch (InvocationTargetException e) {
logger.log(Level.SEVERE,
"Could not dispatch event: " + event + " to handler " + wrapper, e);
}
}
/**
* Flattens a class's type hierarchy into a set of Class objects. The set
* will include all superclasses (transitively), and all interfaces
* implemented by these superclasses.
*
* @param concreteClass class whose type hierarchy will be retrieved.
* @return {@code clazz}'s complete type hierarchy, flattened and uniqued.
*/
@VisibleForTesting
Set<Class<?>> flattenHierarchy(Class<?> concreteClass) {
try {
return flattenHierarchyCache.getUnchecked(concreteClass);
} catch (UncheckedExecutionException e) {
throw Throwables.propagate(e.getCause());
}
}
/** simple struct representing an event and it's handler */
static class EventWithHandler {
final Object event;
final EventHandler handler;
public EventWithHandler(Object event, EventHandler handler) {
this.event = event;
this.handler = handler;
}
}
}
| 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.eventbus;
import com.google.common.annotations.Beta;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
/**
* An {@link EventBus} that takes the Executor of your choice and uses it to
* dispatch events, allowing dispatch to occur asynchronously.
*
* @author Cliff Biffle
* @since 10.0
*/
@Beta
public class AsyncEventBus extends EventBus {
private final Executor executor;
/** the queue of events is shared across all threads */
private final ConcurrentLinkedQueue<EventWithHandler> eventsToDispatch =
new ConcurrentLinkedQueue<EventWithHandler>();
/**
* Creates a new AsyncEventBus that will use {@code executor} to dispatch
* events. Assigns {@code identifier} as the bus's name for logging purposes.
*
* @param identifier short name for the bus, for logging purposes.
* @param executor Executor to use to dispatch events. It is the caller's
* responsibility to shut down the executor after the last event has
* been posted to this event bus.
*/
public AsyncEventBus(String identifier, Executor executor) {
super(identifier);
this.executor = executor;
}
/**
* Creates a new AsyncEventBus that will use {@code executor} to dispatch
* events.
*
* @param executor Executor to use to dispatch events. It is the caller's
* responsibility to shut down the executor after the last event has
* been posted to this event bus.
*/
public AsyncEventBus(Executor executor) {
this.executor = executor;
}
@Override
void enqueueEvent(Object event, EventHandler handler) {
eventsToDispatch.offer(new EventWithHandler(event, handler));
}
/**
* Dispatch {@code events} in the order they were posted, regardless of
* the posting thread.
*/
@SuppressWarnings("deprecation") // only deprecated for external subclasses
@Override
protected void dispatchQueuedEvents() {
while (true) {
EventWithHandler eventWithHandler = eventsToDispatch.poll();
if (eventWithHandler == null) {
break;
}
dispatch(eventWithHandler.event, eventWithHandler.handler);
}
}
/**
* Calls the {@link #executor} to dispatch {@code event} to {@code handler}.
*/
@Override
void dispatch(final Object event, final EventHandler handler) {
executor.execute(new Runnable() {
@Override
@SuppressWarnings("synthetic-access")
public void run() {
AsyncEventBus.super.dispatch(event, handler);
}
});
}
}
| 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.eventbus;
import com.google.common.annotations.Beta;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks a method as an event handler, as used by
* {@link AnnotatedHandlerFinder} and {@link EventBus}.
*
* <p>The type of event will be indicated by the method's first (and only)
* parameter. If this annotation is applied to methods with zero parameters,
* or more than one parameter, the object containing the method will not be able
* to register for event delivery from the {@link EventBus}.
*
* <p>Unless also annotated with @{@link AllowConcurrentEvents}, event handler
* methods will be invoked serially by each event bus that they are registered
* with.
*
* @author Cliff Biffle
* @since 10.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Beta
public @interface Subscribe {
}
| 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.
*/
/**
* The EventBus allows publish-subscribe-style communication between components
* without requiring the components to explicitly register with one another
* (and thus be aware of each other). It is designed exclusively to replace
* traditional Java in-process event distribution using explicit registration.
* It is <em>not</em> a general-purpose publish-subscribe system, nor is it
* intended for interprocess communication.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/EventBusExplained">
* {@code EventBus}</a>.
*
* <h2>One-Minute Guide</h2>
*
* Converting an existing EventListener-based system to use the EventBus is
* easy.
*
* <h3>For Listeners</h3>
* To listen for a specific flavor of event (say, a CustomerChangeEvent)...
* <ul>
* <li><strong>...in traditional Java events:</strong> implement an interface
* defined with the event — such as CustomerChangeEventListener.</li>
* <li><strong>...with EventBus:</strong> create a method that accepts
* CustomerChangeEvent as its sole argument, and mark it with the
* {@link com.google.common.eventbus.Subscribe} annotation.</li>
* </ul>
*
* <p>To register your listener methods with the event producers...
* <ul>
* <li><strong>...in traditional Java events:</strong> pass your object to each
* producer's {@code registerCustomerChangeEventListener} method. These
* methods are rarely defined in common interfaces, so in addition to
* knowing every possible producer, you must also know its type.</li>
* <li><strong>...with EventBus:</strong> pass your object to the
* {@link com.google.common.eventbus.EventBus#register(Object)} method on an
* EventBus. You'll need to
* make sure that your object shares an EventBus instance with the event
* producers.</li>
* </ul>
*
* <p>To listen for a common event supertype (such as EventObject or Object)...
* <ul>
* <li><strong>...in traditional Java events:</strong> not easy.</li>
* <li><strong>...with EventBus:</strong> events are automatically dispatched to
* listeners of any supertype, allowing listeners for interface types
* or "wildcard listeners" for Object.</li>
* </ul>
*
* <p>To listen for and detect events that were dispatched without listeners...
* <ul>
* <li><strong>...in traditional Java events:</strong> add code to each
* event-dispatching method (perhaps using AOP).</li>
* <li><strong>...with EventBus:</strong> subscribe to {@link
* com.google.common.eventbus.DeadEvent}. The
* EventBus will notify you of any events that were posted but not
* delivered. (Handy for debugging.)</li>
* </ul>
*
* <h3>For Producers</h3>
* To keep track of listeners to your events...
* <ul>
* <li><strong>...in traditional Java events:</strong> write code to manage
* a list of listeners to your object, including synchronization, or use a
* utility class like EventListenerList.</li>
* <li><strong>...with EventBus:</strong> EventBus does this for you.</li>
* </ul>
*
* <p>To dispatch an event to listeners...
* <ul>
* <li><strong>...in traditional Java events:</strong> write a method to
* dispatch events to each event listener, including error isolation and
* (if desired) asynchronicity.</li>
* <li><strong>...with EventBus:</strong> pass the event object to an EventBus's
* {@link com.google.common.eventbus.EventBus#post(Object)} method.</li>
* </ul>
*
* <h2>Glossary</h2>
*
* The EventBus system and code use the following terms to discuss event
* distribution:
* <dl>
* <dt>Event</dt><dd>Any object that may be <em>posted</em> to a bus.</dd>
* <dt>Subscribing</dt><dd>The act of registering a <em>listener</em> with an
* EventBus, so that its <em>handler methods</em> will receive events.</dd>
* <dt>Listener</dt><dd>An object that wishes to receive events, by exposing
* <em>handler methods</em>.</dt>
* <dt>Handler method</dt><dd>A public method that the EventBus should use to
* deliver <em>posted</em> events. Handler methods are marked by the
* {@link com.google.common.eventbus.Subscribe} annotation.</dd>
* <dt>Posting an event</dt><dd>Making the event available to any
* <em>listeners</em> through the EventBus.</dt>
* </dl>
*
* <h2>FAQ</h2>
* <h3>Why must I create my own Event Bus, rather than using a singleton?</h3>
*
* The Event Bus doesn't specify how you use it; there's nothing stopping your
* application from having separate EventBus instances for each component, or
* using separate instances to separate events by context or topic. This also
* makes it trivial to set up and tear down EventBus objects in your tests.
*
* <p>Of course, if you'd like to have a process-wide EventBus singleton,
* there's nothing stopping you from doing it that way. Simply have your
* container (such as Guice) create the EventBus as a singleton at global scope
* (or stash it in a static field, if you're into that sort of thing).
*
* <p>In short, the EventBus is not a singleton because we'd rather not make
* that decision for you. Use it how you like.
*
* <h3>Why use an annotation to mark handler methods, rather than requiring the
* listener to implement an interface?</h3>
* We feel that the Event Bus's {@code @Subscribe} annotation conveys your
* intentions just as explicitly as implementing an interface (or perhaps more
* so), while leaving you free to place event handler methods wherever you wish
* and give them intention-revealing names.
*
* <p>Traditional Java Events use a listener interface which typically sports
* only a handful of methods -- typically one. This has a number of
* disadvantages:
* <ul>
* <li>Any one class can only implement a single response to a given event.
* <li>Listener interface methods may conflict.
* <li>The method must be named after the event (e.g. {@code
* handleChangeEvent}), rather than its purpose (e.g. {@code
* recordChangeInJournal}).
* <li>Each event usually has its own interface, without a common parent
* interface for a family of events (e.g. all UI events).
* </ul>
*
* <p>The difficulties in implementing this cleanly has given rise to a pattern,
* particularly common in Swing apps, of using tiny anonymous classes to
* implement event listener interfaces.
*
* <p>Compare these two cases: <pre>
* class ChangeRecorder {
* void setCustomer(Customer cust) {
* cust.addChangeListener(new ChangeListener() {
* void customerChanged(ChangeEvent e) {
* recordChange(e.getChange());
* }
* };
* }
* }
*
* // Class is typically registered by the container.
* class EventBusChangeRecorder {
* @Subscribe void recordCustomerChange(ChangeEvent e) {
* recordChange(e.getChange());
* }
* }</pre>
*
* The intent is actually clearer in the second case: there's less noise code,
* and the event handler has a clear and meaningful name.
*
* <h3>What about a generic {@code Handler<T>} interface?</h3>
* Some have proposed a generic {@code Handler<T>} interface for EventBus
* listeners. This runs into issues with Java's use of type erasure, not to
* mention problems in usability.
*
* <p>Let's say the interface looked something like the following: <pre> {@code
* interface Handler<T> {
* void handleEvent(T event);
* }}</pre>
*
* Due to erasure, no single class can implement a generic interface more than
* once with different type parameters. This is a giant step backwards from
* traditional Java Events, where even if {@code actionPerformed} and {@code
* keyPressed} aren't very meaningful names, at least you can implement both
* methods!
*
* <h3>Doesn't EventBus destroy static typing and eliminate automated
* refactoring support?</h3>
* Some have freaked out about EventBus's {@code register(Object)} and {@code
* post(Object)} methods' use of the {@code Object} type.
*
* <p>{@code Object} is used here for a good reason: the Event Bus library
* places no restrictions on the types of either your event listeners (as in
* {@code register(Object)}) or the events themselves (in {@code post(Object)}).
*
* <p>Event handler methods, on the other hand, must explicitly declare their
* argument type -- the type of event desired (or one of its supertypes). Thus,
* searching for references to an event class will instantly find all handler
* methods for that event, and renaming the type will affect all handler methods
* within view of your IDE (and any code that creates the event).
*
* <p>It's true that you can rename your {@code @Subscribed} event handler
* methods at will; Event Bus will not stop this or do anything to propagate the
* rename because, to Event Bus, the names of your handler methods are
* irrelevant. Test code that calls the methods directly, of course, will be
* affected by your renaming -- but that's what your refactoring tools are for.
*
* <h3>What happens if I {@code register} a listener without any handler
* methods?</h3>
* Nothing at all.
*
* <p>The Event Bus was designed to integrate with containers and module
* systems, with Guice as the prototypical example. In these cases, it's
* convenient to have the container/factory/environment pass <i>every</i>
* created object to an EventBus's {@code register(Object)} method.
*
* <p>This way, any object created by the container/factory/environment can
* hook into the system's event model simply by exposing handler methods.
*
* <h3>What Event Bus problems can be detected at compile time?</h3>
* Any problem that can be unambiguously detected by Java's type system. For
* example, defining a handler method for a nonexistent event type.
*
* <h3>What Event Bus problems can be detected immediately at registration?</h3>
* Immediately upon invoking {@code register(Object)} , the listener being
* registered is checked for the <i>well-formedness</i> of its handler methods.
* Specifically, any methods marked with {@code @Subscribe} must take only a
* single argument.
*
* <p>Any violations of this rule will cause an {@code IllegalArgumentException}
* to be thrown.
*
* <p>(This check could be moved to compile-time using APT, a solution we're
* researching.)
*
* <h3>What Event Bus problems may only be detected later, at runtime?</h3>
* If a component posts events with no registered listeners, it <i>may</i>
* indicate an error (typically an indication that you missed a
* {@code @Subscribe} annotation, or that the listening component is not loaded).
*
* <p>(Note that this is <i>not necessarily</i> indicative of a problem. There
* are many cases where an application will deliberately ignore a posted event,
* particularly if the event is coming from code you don't control.)
*
* <p>To handle such events, register a handler method for the {@code DeadEvent}
* class. Whenever EventBus receives an event with no registered handlers, it
* will turn it into a {@code DeadEvent} and pass it your way -- allowing you to
* log it or otherwise recover.
*
* <h3>How do I test event listeners and their handler methods?</h3>
* Because handler methods on your listener classes are normal methods, you can
* simply call them from your test code to simulate the EventBus.
*/
package com.google.common.eventbus;
| 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.eventbus;
import com.google.common.collect.Multimap;
/**
* A method for finding event handler methods in objects, for use by
* {@link EventBus}.
*
* @author Cliff Biffle
*/
interface HandlerFindingStrategy {
/**
* Finds all suitable event handler methods in {@code source}, organizes them
* by the type of event they handle, and wraps them in {@link EventHandler}s.
*
* @param source object whose handlers are desired.
* @return EventHandler objects for each handler method, organized by event
* type.
*
* @throws IllegalArgumentException if {@code source} is not appropriate for
* this strategy (in ways that this interface does not define).
*/
Multimap<Class<?>, EventHandler> findAllHandlers(Object source);
}
| 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.eventbus;
import com.google.common.annotations.Beta;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks an event handling method as being thread-safe. This annotation
* indicates that EventBus may invoke the event handler simultaneously from
* multiple threads.
*
* <p>This does not mark the method as an event handler, and so should be used
* in combination with {@link Subscribe}.
*
* @author Cliff Biffle
* @since 10.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Beta
public @interface AllowConcurrentEvents {
}
| 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.eventbus;
import com.google.common.base.Preconditions;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Wraps a single-argument 'handler' method on a specific object.
*
* <p>This class only verifies the suitability of the method and event type if
* something fails. Callers are expected to verify their uses of this class.
*
* <p>Two EventHandlers are equivalent when they refer to the same method on the
* same object (not class). This property is used to ensure that no handler
* method is registered more than once.
*
* @author Cliff Biffle
*/
class EventHandler {
/** Object sporting the handler method. */
private final Object target;
/** Handler method. */
private final Method method;
/**
* Creates a new EventHandler to wrap {@code method} on @{code target}.
*
* @param target object to which the method applies.
* @param method handler method.
*/
EventHandler(Object target, Method method) {
Preconditions.checkNotNull(target,
"EventHandler target cannot be null.");
Preconditions.checkNotNull(method, "EventHandler method cannot be null.");
this.target = target;
this.method = method;
method.setAccessible(true);
}
/**
* Invokes the wrapped handler method to handle {@code event}.
*
* @param event event to handle
* @throws InvocationTargetException if the wrapped method throws any
* {@link Throwable} that is not an {@link Error} ({@code Error}s are
* propagated as-is).
*/
public void handleEvent(Object event) throws InvocationTargetException {
try {
method.invoke(target, new Object[] { event });
} catch (IllegalArgumentException e) {
throw new Error("Method rejected target/argument: " + event, e);
} catch (IllegalAccessException e) {
throw new Error("Method became inaccessible: " + event, e);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof Error) {
throw (Error) e.getCause();
}
throw e;
}
}
@Override public String toString() {
return "[wrapper " + method + "]";
}
@Override public int hashCode() {
final int PRIME = 31;
return (PRIME + method.hashCode()) * PRIME + target.hashCode();
}
@Override public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj == null) {
return false;
}
if(getClass() != obj.getClass()) {
return false;
}
final EventHandler other = (EventHandler) obj;
return method.equals(other.method) && target == other.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.eventbus;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Wraps a single-argument 'handler' method on a specific object, and ensures
* that only one thread may enter the method at a time.
*
* <p>Beyond synchronization, this class behaves identically to
* {@link EventHandler}.
*
* @author Cliff Biffle
*/
class SynchronizedEventHandler extends EventHandler {
/**
* Creates a new SynchronizedEventHandler to wrap {@code method} on
* {@code target}.
*
* @param target object to which the method applies.
* @param method handler method.
*/
public SynchronizedEventHandler(Object target, Method method) {
super(target, method);
}
@Override public synchronized void handleEvent(Object event)
throws InvocationTargetException {
super.handleEvent(event);
}
}
| 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.eventbus;
import com.google.common.annotations.Beta;
/**
* Wraps an event that was posted, but which had no subscribers and thus could
* not be delivered.
*
* <p>Subscribing a DeadEvent handler is useful for debugging or logging, as it
* can detect misconfigurations in a system's event distribution.
*
* @author Cliff Biffle
* @since 10.0
*/
@Beta
public class DeadEvent {
private final Object source;
private final Object event;
/**
* Creates a new DeadEvent.
*
* @param source object broadcasting the DeadEvent (generally the
* {@link EventBus}).
* @param event the event that could not be delivered.
*/
public DeadEvent(Object source, Object event) {
this.source = source;
this.event = event;
}
/**
* Returns the object that originated this event (<em>not</em> the object that
* originated the wrapped event). This is generally an {@link EventBus}.
*
* @return the source of this event.
*/
public Object getSource() {
return source;
}
/**
* Returns the wrapped, 'dead' event, which the system was unable to deliver
* to any registered handler.
*
* @return the 'dead' event that could not be delivered.
*/
public Object getEvent() {
return event;
}
}
| 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.eventbus;
import com.google.common.base.Throwables;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
import com.google.common.reflect.TypeToken;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.lang.reflect.Method;
import java.util.Set;
/**
* A {@link HandlerFindingStrategy} for collecting all event handler methods that are marked with
* the {@link Subscribe} annotation.
*
* @author Cliff Biffle
* @author Louis Wasserman
*/
class AnnotatedHandlerFinder implements HandlerFindingStrategy {
/**
* A thread-safe cache that contains the mapping from each class to all methods in that class and
* all super-classes, that are annotated with {@code @Subscribe}. The cache is shared across all
* instances of this class; this greatly improves performance if multiple EventBus instances are
* created and objects of the same class are registered on all of them.
*/
private static final LoadingCache<Class<?>, ImmutableList<Method>> handlerMethodsCache =
CacheBuilder.newBuilder()
.weakKeys()
.build(new CacheLoader<Class<?>, ImmutableList<Method>>() {
@Override
public ImmutableList<Method> load(Class<?> concreteClass) throws Exception {
return getAnnotatedMethodsInternal(concreteClass);
}
});
/**
* {@inheritDoc}
*
* This implementation finds all methods marked with a {@link Subscribe} annotation.
*/
@Override
public Multimap<Class<?>, EventHandler> findAllHandlers(Object listener) {
Multimap<Class<?>, EventHandler> methodsInListener = HashMultimap.create();
Class<?> clazz = listener.getClass();
for (Method method : getAnnotatedMethods(clazz)) {
Class<?>[] parameterTypes = method.getParameterTypes();
Class<?> eventType = parameterTypes[0];
EventHandler handler = makeHandler(listener, method);
methodsInListener.put(eventType, handler);
}
return methodsInListener;
}
private static ImmutableList<Method> getAnnotatedMethods(Class<?> clazz) {
try {
return handlerMethodsCache.getUnchecked(clazz);
} catch (UncheckedExecutionException e) {
throw Throwables.propagate(e.getCause());
}
}
private static ImmutableList<Method> getAnnotatedMethodsInternal(Class<?> clazz) {
Set<? extends Class<?>> supers = TypeToken.of(clazz).getTypes().rawTypes();
ImmutableList.Builder<Method> result = ImmutableList.builder();
for (Method method : clazz.getMethods()) {
/*
* Iterate over each distinct method of {@code clazz}, checking if it is annotated with
* @Subscribe by any of the superclasses or superinterfaces that declare it.
*/
for (Class<?> c : supers) {
try {
Method m = c.getMethod(method.getName(), method.getParameterTypes());
if (m.isAnnotationPresent(Subscribe.class)) {
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length != 1) {
throw new IllegalArgumentException("Method " + method
+ " has @Subscribe annotation, but requires " + parameterTypes.length
+ " arguments. Event handler methods must require a single argument.");
}
Class<?> eventType = parameterTypes[0];
result.add(method);
break;
}
} catch (NoSuchMethodException ignored) {
// Move on.
}
}
}
return result.build();
}
/**
* Creates an {@code EventHandler} for subsequently calling {@code method} on
* {@code listener}.
* Selects an EventHandler implementation based on the annotations on
* {@code method}.
*
* @param listener object bearing the event handler method.
* @param method the event handler method to wrap in an EventHandler.
* @return an EventHandler that will call {@code method} on {@code listener}
* when invoked.
*/
private static EventHandler makeHandler(Object listener, Method method) {
EventHandler wrapper;
if (methodIsDeclaredThreadSafe(method)) {
wrapper = new EventHandler(listener, method);
} else {
wrapper = new SynchronizedEventHandler(listener, method);
}
return wrapper;
}
/**
* Checks whether {@code method} is thread-safe, as indicated by the
* {@link AllowConcurrentEvents} annotation.
*
* @param method handler method to check.
* @return {@code true} if {@code handler} is marked as thread-safe,
* {@code false} otherwise.
*/
private static boolean methodIsDeclaredThreadSafe(Method method) {
return method.getAnnotation(AllowConcurrentEvents.class) != 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.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.Nullable;
/**
* Helper functions that can operate on any {@code Object}.
*
* <p>See the Guava User Guide on <a
* href="http://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained">writing
* {@code Object} methods with {@code Objects}</a>.
*
* @author Laurence Gonsalves
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public final class Objects {
private Objects() {}
/**
* Determines whether two possibly-null objects are equal. Returns:
*
* <ul>
* <li>{@code true} if {@code a} and {@code b} are both null.
* <li>{@code true} if {@code a} and {@code b} are both non-null and they are
* equal according to {@link Object#equals(Object)}.
* <li>{@code false} in all other situations.
* </ul>
*
* <p>This assumes that any non-null objects passed to this function conform
* to the {@code equals()} contract.
*/
public static boolean equal(@Nullable Object a, @Nullable Object b) {
return a == b || (a != null && a.equals(b));
}
/**
* Generates a hash code for multiple values. The hash code is generated by
* calling {@link Arrays#hashCode(Object[])}.
*
* <p>This is useful for implementing {@link Object#hashCode()}. For example,
* in an object that has three properties, {@code x}, {@code y}, and
* {@code z}, one could write:
* <pre>
* public int hashCode() {
* return Objects.hashCode(getX(), getY(), getZ());
* }</pre>
*
* <b>Warning</b>: When a single object is supplied, the returned hash code
* does not equal the hash code of that object.
*/
public static int hashCode(@Nullable Object... objects) {
return Arrays.hashCode(objects);
}
/**
* Creates an instance of {@link ToStringHelper}.
*
* <p>This is helpful for implementing {@link Object#toString()}.
* Specification by example: <pre> {@code
* // Returns "ClassName{}"
* Objects.toStringHelper(this)
* .toString();
*
* // Returns "ClassName{x=1}"
* Objects.toStringHelper(this)
* .add("x", 1)
* .toString();
*
* // Returns "MyObject{x=1}"
* Objects.toStringHelper("MyObject")
* .add("x", 1)
* .toString();
*
* // Returns "ClassName{x=1, y=foo}"
* Objects.toStringHelper(this)
* .add("x", 1)
* .add("y", "foo")
* .toString();
* }}
*
* // Returns "ClassName{x=1}"
* Objects.toStringHelper(this)
* .omitNullValues()
* .add("x", 1)
* .add("y", null)
* .toString();
* }}</pre>
*
* <p>Note that in GWT, class names are often obfuscated.
*
* @param self the object to generate the string for (typically {@code this}),
* used only for its class name
* @since 2.0
*/
public static ToStringHelper toStringHelper(Object self) {
return new ToStringHelper(simpleName(self.getClass()));
}
/**
* Creates an instance of {@link ToStringHelper} in the same manner as
* {@link Objects#toStringHelper(Object)}, but using the name of {@code clazz}
* instead of using an instance's {@link Object#getClass()}.
*
* <p>Note that in GWT, class names are often obfuscated.
*
* @param clazz the {@link Class} of the instance
* @since 7.0 (source-compatible since 2.0)
*/
public static ToStringHelper toStringHelper(Class<?> clazz) {
return new ToStringHelper(simpleName(clazz));
}
/**
* Creates an instance of {@link ToStringHelper} in the same manner as
* {@link Objects#toStringHelper(Object)}, but using {@code className} instead
* of using an instance's {@link Object#getClass()}.
*
* @param className the name of the instance type
* @since 7.0 (source-compatible since 2.0)
*/
public static ToStringHelper toStringHelper(String className) {
return new ToStringHelper(className);
}
/**
* {@link Class#getSimpleName()} is not GWT compatible yet, so we
* provide our own implementation.
*/
private static String simpleName(Class<?> clazz) {
String name = clazz.getName();
// the nth anonymous class has a class name ending in "Outer$n"
// and local inner classes have names ending in "Outer.$1Inner"
name = name.replaceAll("\\$[0-9]+", "\\$");
// we want the name of the inner class all by its lonesome
int start = name.lastIndexOf('$');
// if this isn't an inner class, just find the start of the
// top level class name.
if (start == -1) {
start = name.lastIndexOf('.');
}
return name.substring(start + 1);
}
/**
* Returns the first of two given parameters that is not {@code null}, if
* either is, or otherwise throws a {@link NullPointerException}.
*
* <p><b>Note:</b> if {@code first} is represented as an {@code Optional<T>},
* this can be accomplished with {@code first.or(second)}. That approach also
* allows for lazy evaluation of the fallback instance, using
* {@code first.or(Supplier)}.
*
* @return {@code first} if {@code first} is not {@code null}, or
* {@code second} if {@code first} is {@code null} and {@code second} is
* not {@code null}
* @throws NullPointerException if both {@code first} and {@code second} were
* {@code null}
* @since 3.0
*/
public static <T> T firstNonNull(@Nullable T first, @Nullable T second) {
return first != null ? first : checkNotNull(second);
}
/**
* Support class for {@link Objects#toStringHelper}.
*
* @author Jason Lee
* @since 2.0
*/
public static final class ToStringHelper {
private final String className;
private final List<ValueHolder> valueHolders =
new LinkedList<ValueHolder>();
private boolean omitNullValues = false;
/**
* Use {@link Objects#toStringHelper(Object)} to create an instance.
*/
private ToStringHelper(String className) {
this.className = checkNotNull(className);
}
/**
* When called, the formatted output returned by {@link #toString()} will
* ignore {@code null} values.
*
* @since 12.0
*/
@Beta
public ToStringHelper omitNullValues() {
omitNullValues = true;
return this;
}
/**
* Adds a name/value pair to the formatted output in {@code name=value}
* format. If {@code value} is {@code null}, the string {@code "null"}
* is used, unless {@link #omitNullValues()} is called, in which case this
* name/value pair will not be added.
*/
public ToStringHelper add(String name, @Nullable Object value) {
checkNotNull(name);
addHolder(value).builder.append(name).append('=').append(value);
return this;
}
/**
* Adds a name/value pair to the formatted output in {@code name=value}
* format.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper add(String name, boolean value) {
checkNameAndAppend(name).append(value);
return this;
}
/**
* Adds a name/value pair to the formatted output in {@code name=value}
* format.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper add(String name, char value) {
checkNameAndAppend(name).append(value);
return this;
}
/**
* Adds a name/value pair to the formatted output in {@code name=value}
* format.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper add(String name, double value) {
checkNameAndAppend(name).append(value);
return this;
}
/**
* Adds a name/value pair to the formatted output in {@code name=value}
* format.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper add(String name, float value) {
checkNameAndAppend(name).append(value);
return this;
}
/**
* Adds a name/value pair to the formatted output in {@code name=value}
* format.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper add(String name, int value) {
checkNameAndAppend(name).append(value);
return this;
}
/**
* Adds a name/value pair to the formatted output in {@code name=value}
* format.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper add(String name, long value) {
checkNameAndAppend(name).append(value);
return this;
}
private StringBuilder checkNameAndAppend(String name) {
checkNotNull(name);
return addHolder().builder.append(name).append('=');
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, Object)} instead
* and give value a readable name.
*/
public ToStringHelper addValue(@Nullable Object value) {
addHolder(value).builder.append(value);
return this;
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, boolean)} instead
* and give value a readable name.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper addValue(boolean value) {
addHolder().builder.append(value);
return this;
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, char)} instead
* and give value a readable name.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper addValue(char value) {
addHolder().builder.append(value);
return this;
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, double)} instead
* and give value a readable name.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper addValue(double value) {
addHolder().builder.append(value);
return this;
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, float)} instead
* and give value a readable name.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper addValue(float value) {
addHolder().builder.append(value);
return this;
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, int)} instead
* and give value a readable name.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper addValue(int value) {
addHolder().builder.append(value);
return this;
}
/**
* Adds an unnamed value to the formatted output.
*
* <p>It is strongly encouraged to use {@link #add(String, long)} instead
* and give value a readable name.
*
* @since 11.0 (source-compatible since 2.0)
*/
public ToStringHelper addValue(long value) {
addHolder().builder.append(value);
return this;
}
/**
* Returns a string in the format specified by {@link
* Objects#toStringHelper(Object)}.
*/
@Override public String toString() {
// create a copy to keep it consistent in case value changes
boolean omitNullValuesSnapshot = omitNullValues;
boolean needsSeparator = false;
StringBuilder builder = new StringBuilder(32).append(className)
.append('{');
for (ValueHolder valueHolder : valueHolders) {
if (!omitNullValuesSnapshot || !valueHolder.isNull) {
if (needsSeparator) {
builder.append(", ");
} else {
needsSeparator = true;
}
// must explicitly cast it, otherwise GWT tests might fail because
// it tries to access StringBuilder.append(StringBuilder), which is
// a private method
// TODO(user): change once 5904010 is fixed
CharSequence sequence = valueHolder.builder;
builder.append(sequence);
}
}
return builder.append('}').toString();
}
private ValueHolder addHolder() {
ValueHolder valueHolder = new ValueHolder();
valueHolders.add(valueHolder);
return valueHolder;
}
private ValueHolder addHolder(@Nullable Object value) {
ValueHolder valueHolder = addHolder();
valueHolder.isNull = (value == null);
return valueHolder;
}
private static final class ValueHolder {
final StringBuilder builder = new StringBuilder();
boolean isNull;
}
}
}
| Java |
/*
* Copyright (C) 2012 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.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher.FastMatcher;
import java.util.BitSet;
/**
* An immutable version of CharMatcher for medium-sized sets of characters that uses a hash table
* with linear probing to check for matches.
*
* @author Christopher Swenson
*/
@GwtCompatible(emulated = true)
final class MediumCharMatcher extends FastMatcher {
static final int MAX_SIZE = 1023;
private final char[] table;
private final boolean containsZero;
private final long filter;
private MediumCharMatcher(char[] table, long filter, boolean containsZero,
String description) {
super(description);
this.table = table;
this.filter = filter;
this.containsZero = containsZero;
}
private boolean checkFilter(int c) {
return 1 == (1 & (filter >> c));
}
// This is all essentially copied from ImmutableSet, but we have to duplicate because
// of dependencies.
// Represents how tightly we can pack things, as a maximum.
private static final double DESIRED_LOAD_FACTOR = 0.5;
/**
* Returns an array size suitable for the backing array of a hash table that
* uses open addressing with linear probing in its implementation. The
* returned size is the smallest power of two that can hold setSize elements
* with the desired load factor.
*/
@VisibleForTesting static int chooseTableSize(int setSize) {
if (setSize == 1) {
return 2;
}
// Correct the size for open addressing to match desired load factor.
// Round up to the next highest power of 2.
int tableSize = Integer.highestOneBit(setSize - 1) << 1;
while (tableSize * DESIRED_LOAD_FACTOR < setSize) {
tableSize <<= 1;
}
return tableSize;
}
@GwtIncompatible("java.util.BitSet")
static CharMatcher from(BitSet chars, String description) {
// Compute the filter.
long filter = 0;
int size = chars.cardinality();
boolean containsZero = chars.get(0);
// Compute the hash table.
char[] table = new char[chooseTableSize(size)];
int mask = table.length - 1;
for (int c = chars.nextSetBit(0); c != -1; c = chars.nextSetBit(c + 1)) {
// Compute the filter at the same time.
filter |= 1L << c;
int index = c & mask;
while (true) {
// Check for empty.
if (table[index] == 0) {
table[index] = (char) c;
break;
}
// Linear probing.
index = (index + 1) & mask;
}
}
return new MediumCharMatcher(table, filter, containsZero, description);
}
@Override
public boolean matches(char c) {
if (c == 0) {
return containsZero;
}
if (!checkFilter(c)) {
return false;
}
int mask = table.length - 1;
int startingIndex = c & mask;
int index = startingIndex;
do {
// Check for empty.
if (table[index] == 0) {
return false;
// Check for match.
} else if (table[index] == c) {
return true;
} else {
// Linear probing.
index = (index + 1) & mask;
}
// Check to see if we wrapped around the whole table.
} while (index != startingIndex);
return false;
}
@GwtIncompatible("java.util.BitSet")
@Override
void setBits(BitSet table) {
if (containsZero) {
table.set(0);
}
for (char c : this.table) {
if (c != 0) {
table.set(c);
}
}
}
}
| 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.base;
import com.google.common.annotations.GwtCompatible;
import javax.annotation.Nullable;
/**
* Determines an output value based on an input value.
*
* <p>The {@link Functions} class provides common functions and related utilites.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the use of {@code
* Function}</a>.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public interface Function<F, T> {
/**
* Returns the result of applying this function to {@code input}. This method is <i>generally
* expected</i>, but not absolutely required, to have the following properties:
*
* <ul>
* <li>Its execution does not cause any observable side effects.
* <li>The computation is <i>consistent with equals</i>; that is, {@link Objects#equal
* Objects.equal}{@code (a, b)} implies that {@code Objects.equal(function.apply(a),
* function.apply(b))}.
* </ul>
*
* @throws NullPointerException if {@code input} is null and this function does not accept null
* arguments
*/
@Nullable T apply(@Nullable F input);
/**
* Indicates whether another object is equal to this function.
*
* <p>Most implementations will have no reason to override the behavior of {@link Object#equals}.
* However, an implementation may also choose to return {@code true} whenever {@code object} is a
* {@link Function} that it considers <i>interchangeable</i> with this one. "Interchangeable"
* <i>typically</i> means that {@code Objects.equal(this.apply(f), that.apply(f))} is true for all
* {@code f} of type {@code F}. Note that a {@code false} result from this method does not imply
* that the functions are known <i>not</i> to be interchangeable.
*/
@Override
boolean equals(@Nullable Object object);
}
| 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.base;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
/**
* Phantom reference with a {@code finalizeReferent()} method which a background thread invokes
* after the garbage collector reclaims the referent. This is a simpler alternative to using a
* {@link ReferenceQueue}.
*
* <p>Unlike a normal phantom reference, this reference will be cleared automatically.
*
* @author Bob Lee
* @since 2.0 (imported from Google Collections Library)
*/
public abstract class FinalizablePhantomReference<T> extends PhantomReference<T>
implements FinalizableReference {
/**
* Constructs a new finalizable phantom reference.
*
* @param referent to phantom reference
* @param queue that should finalize the referent
*/
protected FinalizablePhantomReference(T referent, FinalizableReferenceQueue queue) {
super(referent, queue.queue);
queue.cleanUp();
}
}
| 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.base;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.Iterator;
import javax.annotation.Nullable;
@GwtCompatible(serializable = true)
final class PairwiseEquivalence<T> extends Equivalence<Iterable<T>>
implements Serializable {
final Equivalence<? super T> elementEquivalence;
PairwiseEquivalence(Equivalence<? super T> elementEquivalence) {
this.elementEquivalence = Preconditions.checkNotNull(elementEquivalence);
}
@Override
protected boolean doEquivalent(Iterable<T> iterableA, Iterable<T> iterableB) {
Iterator<T> iteratorA = iterableA.iterator();
Iterator<T> iteratorB = iterableB.iterator();
while (iteratorA.hasNext() && iteratorB.hasNext()) {
if (!elementEquivalence.equivalent(iteratorA.next(), iteratorB.next())) {
return false;
}
}
return !iteratorA.hasNext() && !iteratorB.hasNext();
}
@Override
protected int doHash(Iterable<T> iterable) {
int hash = 78721;
for (T element : iterable) {
hash = hash * 24943 + elementEquivalence.hash(element);
}
return hash;
}
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof PairwiseEquivalence) {
PairwiseEquivalence<?> that = (PairwiseEquivalence<?>) object;
return this.elementEquivalence.equals(that.elementEquivalence);
}
return false;
}
@Override
public int hashCode() {
return elementEquivalence.hashCode() ^ 0x46a3eb07;
}
@Override
public String toString() {
return elementEquivalence + ".pairwise()";
}
private static final long serialVersionUID = 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.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
/**
* Simple static methods to be called at the start of your own methods to verify
* correct arguments and state. This allows constructs such as
* <pre>
* if (count <= 0) {
* throw new IllegalArgumentException("must be positive: " + count);
* }</pre>
*
* to be replaced with the more compact
* <pre>
* checkArgument(count > 0, "must be positive: %s", count);</pre>
*
* Note that the sense of the expression is inverted; with {@code Preconditions}
* you declare what you expect to be <i>true</i>, just as you do with an
* <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html">
* {@code assert}</a> or a JUnit {@code assertTrue} call.
*
* <p><b>Warning:</b> only the {@code "%s"} specifier is recognized as a
* placeholder in these messages, not the full range of {@link
* String#format(String, Object[])} specifiers.
*
* <p>Take care not to confuse precondition checking with other similar types
* of checks! Precondition exceptions -- including those provided here, but also
* {@link IndexOutOfBoundsException}, {@link NoSuchElementException}, {@link
* UnsupportedOperationException} and others -- are used to signal that the
* <i>calling method</i> has made an error. This tells the caller that it should
* not have invoked the method when it did, with the arguments it did, or
* perhaps ever. Postcondition or other invariant failures should not throw
* these types of exceptions.
*
* <p>See the Guava User Guide on <a href=
* "http://code.google.com/p/guava-libraries/wiki/PreconditionsExplained">
* using {@code Preconditions}</a>.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public final class Preconditions {
private Preconditions() {}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
*
* @param expression a boolean expression
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(
boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the
* calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @throws IllegalArgumentException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code
* errorMessageTemplate} or {@code errorMessageArgs} is null (don't let
* this happen)
*/
public static void checkArgument(boolean expression,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(
format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(
boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving the state of the calling
* instance, but not involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @throws IllegalStateException if {@code expression} is false
* @throws NullPointerException if the check fails and either {@code
* errorMessageTemplate} or {@code errorMessageArgs} is null (don't let
* this happen)
*/
public static void checkState(boolean expression,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (!expression) {
throw new IllegalStateException(
format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will
* be converted to a string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
/**
* Ensures that an object reference passed as a parameter to the calling
* method is not null.
*
* @param reference an object reference
* @param errorMessageTemplate a template for the exception message should the
* check fail. The message is formed by replacing each {@code %s}
* placeholder in the template with an argument. These are matched by
* position - the first {@code %s} gets {@code errorMessageArgs[0]}, etc.
* Unmatched arguments will be appended to the formatted message in square
* braces. Unmatched placeholders will be left as-is.
* @param errorMessageArgs the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}.
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (reference == null) {
// If either of these parameters is null, the right thing happens anyway
throw new NullPointerException(
format(errorMessageTemplate, errorMessageArgs));
}
return reference;
}
/*
* All recent hotspots (as of 2009) *really* like to have the natural code
*
* if (guardExpression) {
* throw new BadException(messageExpression);
* }
*
* refactored so that messageExpression is moved to a separate
* String-returning method.
*
* if (guardExpression) {
* throw new BadException(badMsg(...));
* }
*
* The alternative natural refactorings into void or Exception-returning
* methods are much slower. This is a big deal - we're talking factors of
* 2-8 in microbenchmarks, not just 10-20%. (This is a hotspot optimizer
* bug, which should be fixed, but that's a separate, big project).
*
* The coding pattern above is heavily used in java.util, e.g. in ArrayList.
* There is a RangeCheckMicroBenchmark in the JDK that was used to test this.
*
* But the methods in this class want to throw different exceptions,
* depending on the args, so it appears that this pattern is not directly
* applicable. But we can use the ridiculous, devious trick of throwing an
* exception in the middle of the construction of another exception.
* Hotspot is fine with that.
*/
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array,
* list or string of size {@code size}. An element index may range from zero,
* inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list
* or string
* @param size the size of that array, list or string
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is not
* less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkElementIndex(int index, int size) {
return checkElementIndex(index, size, "index");
}
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array,
* list or string of size {@code size}. An element index may range from zero,
* inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list
* or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is not
* less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkElementIndex(
int index, int size, @Nullable String desc) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(badElementIndex(index, size, desc));
}
return index;
}
private static String badElementIndex(int index, int size, String desc) {
if (index < 0) {
return format("%s (%s) must not be negative", desc, index);
} else if (size < 0) {
throw new IllegalArgumentException("negative size: " + size);
} else { // index >= size
return format("%s (%s) must be less than size (%s)", desc, index, size);
}
}
/**
* Ensures that {@code index} specifies a valid <i>position</i> in an array,
* list or string of size {@code size}. A position index may range from zero
* to {@code size}, inclusive.
*
* @param index a user-supplied index identifying a position in an array, list
* or string
* @param size the size of that array, list or string
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is
* greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkPositionIndex(int index, int size) {
return checkPositionIndex(index, size, "index");
}
/**
* Ensures that {@code index} specifies a valid <i>position</i> in an array,
* list or string of size {@code size}. A position index may range from zero
* to {@code size}, inclusive.
*
* @param index a user-supplied index identifying a position in an array, list
* or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is
* greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkPositionIndex(
int index, int size, @Nullable String desc) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc));
}
return index;
}
private static String badPositionIndex(int index, int size, String desc) {
if (index < 0) {
return format("%s (%s) must not be negative", desc, index);
} else if (size < 0) {
throw new IllegalArgumentException("negative size: " + size);
} else { // index > size
return format("%s (%s) must not be greater than size (%s)",
desc, index, size);
}
}
/**
* Ensures that {@code start} and {@code end} specify a valid <i>positions</i>
* in an array, list or string of size {@code size}, and are in order. A
* position index may range from zero to {@code size}, inclusive.
*
* @param start a user-supplied index identifying a starting position in an
* array, list or string
* @param end a user-supplied index identifying a ending position in an array,
* list or string
* @param size the size of that array, list or string
* @throws IndexOutOfBoundsException if either index is negative or is
* greater than {@code size}, or if {@code end} is less than {@code start}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static void checkPositionIndexes(int start, int end, int size) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (start < 0 || end < start || end > size) {
throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size));
}
}
private static String badPositionIndexes(int start, int end, int size) {
if (start < 0 || start > size) {
return badPositionIndex(start, size, "start index");
}
if (end < 0 || end > size) {
return badPositionIndex(end, size, "end index");
}
// end < start
return format("end index (%s) must not be less than start index (%s)",
end, start);
}
/**
* Substitutes each {@code %s} in {@code template} with an argument. These
* are matched by position - the first {@code %s} gets {@code args[0]}, etc.
* If there are more arguments than placeholders, the unmatched arguments will
* be appended to the end of the formatted message in square braces.
*
* @param template a non-null string containing 0 or more {@code %s}
* placeholders.
* @param args the arguments to be substituted into the message
* template. Arguments are converted to strings using
* {@link String#valueOf(Object)}. Arguments can be null.
*/
@VisibleForTesting static String format(String template,
@Nullable Object... args) {
template = String.valueOf(template); // null -> "null"
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(
template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.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.base;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.GwtCompatible;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Note this class is a copy of
* {@link com.google.common.collect.AbstractIterator} (for dependency reasons).
*/
@GwtCompatible
abstract class AbstractIterator<T> implements Iterator<T> {
private State state = State.NOT_READY;
protected AbstractIterator() {}
private enum State {
READY, NOT_READY, DONE, FAILED,
}
private T next;
protected abstract T computeNext();
protected final T endOfData() {
state = State.DONE;
return null;
}
@Override
public final boolean hasNext() {
checkState(state != State.FAILED);
switch (state) {
case DONE:
return false;
case READY:
return true;
default:
}
return tryToComputeNext();
}
private boolean tryToComputeNext() {
state = State.FAILED; // temporary pessimism
next = computeNext();
if (state != State.DONE) {
state = State.READY;
return true;
}
return false;
}
@Override
public final T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
state = State.NOT_READY;
return next;
}
@Override public final void remove() {
throw new UnsupportedOperationException();
}
}
| 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.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import javax.annotation.Nullable;
/**
* A strategy for determining whether two instances are considered equivalent. Examples of
* equivalences are the {@linkplain #identity() identity equivalence} and {@linkplain #equals equals
* equivalence}.
*
* @author Bob Lee
* @author Ben Yu
* @author Gregory Kick
* @since 10.0 (<a href="http://code.google.com/p/guava-libraries/wiki/Compatibility"
* >mostly source-compatible</a> since 4.0)
*/
@GwtCompatible
public abstract class Equivalence<T> {
/**
* Constructor for use by subclasses.
*/
protected Equivalence() {}
/**
* Returns {@code true} if the given objects are considered equivalent.
*
* <p>The {@code equivalent} method implements an equivalence relation on object references:
*
* <ul>
* <li>It is <i>reflexive</i>: for any reference {@code x}, including null, {@code
* equivalent(x, x)} returns {@code true}.
* <li>It is <i>symmetric</i>: for any references {@code x} and {@code y}, {@code
* equivalent(x, y) == equivalent(y, x)}.
* <li>It is <i>transitive</i>: for any references {@code x}, {@code y}, and {@code z}, if
* {@code equivalent(x, y)} returns {@code true} and {@code equivalent(y, z)} returns {@code
* true}, then {@code equivalent(x, z)} returns {@code true}.
* <li>It is <i>consistent</i>: for any references {@code x} and {@code y}, multiple invocations
* of {@code equivalent(x, y)} consistently return {@code true} or consistently return {@code
* false} (provided that neither {@code x} nor {@code y} is modified).
* </ul>
*/
public final boolean equivalent(@Nullable T a, @Nullable T b) {
if (a == b) {
return true;
}
if (a == null || b == null) {
return false;
}
return doEquivalent(a, b);
}
/**
* Returns {@code true} if {@code a} and {@code b} are considered equivalent.
*
* <p>Called by {@link #equivalent}. {@code a} and {@code b} are not the same
* object and are not nulls.
*
* @since 10.0 (previously, subclasses would override equivalent())
*/
protected abstract boolean doEquivalent(T a, T b);
/**
* Returns a hash code for {@code t}.
*
* <p>The {@code hash} has the following properties:
* <ul>
* <li>It is <i>consistent</i>: for any reference {@code x}, multiple invocations of
* {@code hash(x}} consistently return the same value provided {@code x} remains unchanged
* according to the definition of the equivalence. The hash need not remain consistent from
* one execution of an application to another execution of the same application.
* <li>It is <i>distributable accross equivalence</i>: for any references {@code x} and {@code y},
* if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i> necessary
* that the hash be distributable accorss <i>inequivalence</i>. If {@code equivalence(x, y)}
* is false, {@code hash(x) == hash(y)} may still be true.
* <li>{@code hash(null)} is {@code 0}.
* </ul>
*/
public final int hash(@Nullable T t) {
if (t == null) {
return 0;
}
return doHash(t);
}
/**
* Returns a hash code for non-null object {@code t}.
*
* <p>Called by {@link #hash}.
*
* @since 10.0 (previously, subclasses would override hash())
*/
protected abstract int doHash(T t);
/**
* Returns a new equivalence relation for {@code F} which evaluates equivalence by first applying
* {@code function} to the argument, then evaluating using {@code this}. That is, for any pair of
* non-null objects {@code x} and {@code y}, {@code
* equivalence.onResultOf(function).equivalent(a, b)} is true if and only if {@code
* equivalence.equivalent(function.apply(a), function.apply(b))} is true.
*
* <p>For example: <pre> {@code
*
* Equivalence<Person> SAME_AGE = Equivalence.equals().onResultOf(GET_PERSON_AGE);
* }</pre>
*
* <p>{@code function} will never be invoked with a null value.
*
* <p>Note that {@code function} must be consistent according to {@code this} equivalence
* relation. That is, invoking {@link Function#apply} multiple times for a given value must return
* equivalent results.
* For example, {@code Equivalence.identity().onResultOf(Functions.toStringFunction())} is broken
* because it's not guaranteed that {@link Object#toString}) always returns the same string
* instance.
*
* @since 10.0
*/
public final <F> Equivalence<F> onResultOf(Function<F, ? extends T> function) {
return new FunctionalEquivalence<F, T>(function, this);
}
/**
* Returns a wrapper of {@code reference} that implements
* {@link Wrapper#equals(Object) Object.equals()} such that
* {@code wrap(this, a).equals(wrap(this, b))} if and only if {@code this.equivalent(a, b)}.
*
* @since 10.0
*/
public final <S extends T> Wrapper<S> wrap(@Nullable S reference) {
return new Wrapper<S>(this, reference);
}
/**
* Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an
* {@link Equivalence}.
*
* <p>For example, given an {@link Equivalence} for {@link String strings} named {@code equiv}
* that tests equivalence using their lengths:
*
* <pre> {@code
* equiv.wrap("a").equals(equiv.wrap("b")) // true
* equiv.wrap("a").equals(equiv.wrap("hello")) // false
* }</pre>
*
* <p>Note in particular that an equivalence wrapper is never equal to the object it wraps.
*
* <pre> {@code
* equiv.wrap(obj).equals(obj) // always false
* }</pre>
*
* @since 10.0
*/
public static final class Wrapper<T> implements Serializable {
private final Equivalence<? super T> equivalence;
@Nullable private final T reference;
private Wrapper(Equivalence<? super T> equivalence, @Nullable T reference) {
this.equivalence = checkNotNull(equivalence);
this.reference = reference;
}
/** Returns the (possibly null) reference wrapped by this instance. */
@Nullable public T get() {
return reference;
}
/**
* Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped
* references is {@code true} and both wrappers use the {@link Object#equals(Object) same}
* equivalence.
*/
@Override public boolean equals(@Nullable Object obj) {
if (obj == this) {
return true;
} else if (obj instanceof Wrapper) {
Wrapper<?> that = (Wrapper<?>) obj;
/*
* We cast to Equivalence<Object> here because we can't check the type of the reference held
* by the other wrapper. But, by checking that the Equivalences are equal, we know that
* whatever type it is, it is assignable to the type handled by this wrapper's equivalence.
*/
@SuppressWarnings("unchecked")
Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence;
return equivalence.equals(that.equivalence)
&& equivalence.equivalent(this.reference, that.reference);
} else {
return false;
}
}
/**
* Returns the result of {@link Equivalence#hash(Object)} applied to the the wrapped reference.
*/
@Override public int hashCode() {
return equivalence.hash(reference);
}
/**
* Returns a string representation for this equivalence wrapper. The form of this string
* representation is not specified.
*/
@Override public String toString() {
return equivalence + ".wrap(" + reference + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns an equivalence over iterables based on the equivalence of their elements. More
* specifically, two iterables are considered equivalent if they both contain the same number of
* elements, and each pair of corresponding elements is equivalent according to
* {@code this}. Null iterables are equivalent to one another.
*
* <p>Note that this method performs a similar function for equivalences as {@link
* com.google.common.collect.Ordering#lexicographical} does for orderings.
*
* @since 10.0
*/
@GwtCompatible(serializable = true)
public final <S extends T> Equivalence<Iterable<S>> pairwise() {
// Ideally, the returned equivalence would support Iterable<? extends T>. However,
// the need for this is so rare that it's not worth making callers deal with the ugly wildcard.
return new PairwiseEquivalence<S>(this);
}
/**
* Returns a predicate that evaluates to true if and only if the input is
* equivalent to {@code target} according to this equivalence relation.
*
* @since 10.0
*/
@Beta
public final Predicate<T> equivalentTo(@Nullable T target) {
return new EquivalentToPredicate<T>(this, target);
}
private static final class EquivalentToPredicate<T> implements Predicate<T>, Serializable {
private final Equivalence<T> equivalence;
@Nullable private final T target;
EquivalentToPredicate(Equivalence<T> equivalence, @Nullable T target) {
this.equivalence = checkNotNull(equivalence);
this.target = target;
}
@Override public boolean apply(@Nullable T input) {
return equivalence.equivalent(input, target);
}
@Override public boolean equals(@Nullable Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof EquivalentToPredicate) {
EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj;
return equivalence.equals(that.equivalence)
&& Objects.equal(target, that.target);
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(equivalence, target);
}
@Override public String toString() {
return equivalence + ".equivalentTo(" + target + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}.
* {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither
* value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns
* {@code 0} if passed a null value.
*
* @since 13.0
* @since 8.0 (in Equivalences with null-friendly behavior)
* @since 4.0 (in Equivalences)
*/
public static Equivalence<Object> equals() {
return Equals.INSTANCE;
}
/**
* Returns an equivalence that uses {@code ==} to compare values and {@link
* System#identityHashCode(Object)} to compute the hash code. {@link Equivalence#equivalent}
* returns {@code true} if {@code a == b}, including in the case that a and b are both null.
*
* @since 13.0
* @since 4.0 (in Equivalences)
*/
public static Equivalence<Object> identity() {
return Identity.INSTANCE;
}
static final class Equals extends Equivalence<Object>
implements Serializable {
static final Equals INSTANCE = new Equals();
@Override protected boolean doEquivalent(Object a, Object b) {
return a.equals(b);
}
@Override public int doHash(Object o) {
return o.hashCode();
}
private Object readResolve() {
return INSTANCE;
}
private static final long serialVersionUID = 1;
}
static final class Identity extends Equivalence<Object>
implements Serializable {
static final Identity INSTANCE = new Identity();
@Override protected boolean doEquivalent(Object a, Object b) {
return false;
}
@Override protected int doHash(Object o) {
return System.identityHashCode(o);
}
private Object readResolve() {
return INSTANCE;
}
private static final long serialVersionUID = 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.
*/
/**
* Basic utility libraries and interfaces.
*
* <p>This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*
* <h2>Contents</h2>
*
* <h3>String-related utilities</h3>
*
* <ul>
* <li>{@link com.google.common.base.Ascii}
* <li>{@link com.google.common.base.CaseFormat}
* <li>{@link com.google.common.base.CharMatcher}
* <li>{@link com.google.common.base.Charsets}
* <li>{@link com.google.common.base.Joiner}
* <li>{@link com.google.common.base.Splitter}
* <li>{@link com.google.common.base.Strings}
* </ul>
*
* <h3>Function types</h3>
*
* <ul>
* <li>{@link com.google.common.base.Function},
* {@link com.google.common.base.Functions}
* <li>{@link com.google.common.base.Predicate},
* {@link com.google.common.base.Predicates}
* <li>{@link com.google.common.base.Equivalence}
* <li>{@link com.google.common.base.Supplier},
* {@link com.google.common.base.Suppliers}
* </ul>
*
* <h3>Other</h3>
*
* <ul>
* <li>{@link com.google.common.base.Defaults}
* <li>{@link com.google.common.base.Enums}
* <li>{@link com.google.common.base.Objects}
* <li>{@link com.google.common.base.Optional}
* <li>{@link com.google.common.base.Preconditions}
* <li>{@link com.google.common.base.Stopwatch}
* <li>{@link com.google.common.base.Throwables}
* </ul>
*
*/
@ParametersAreNonnullByDefault
package com.google.common.base;
import javax.annotation.ParametersAreNonnullByDefault;
| 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.base;
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.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.util.Arrays;
import java.util.BitSet;
import javax.annotation.CheckReturnValue;
/**
* Determines a true or false value for any Java {@code char} value, just as {@link Predicate} does
* for any {@link Object}. Also offers basic text processing methods based on this function.
* Implementations are strongly encouraged to be side-effect-free and immutable.
*
* <p>Throughout the documentation of this class, the phrase "matching character" is used to mean
* "any character {@code c} for which {@code this.matches(c)} returns {@code true}".
*
* <p><b>Note:</b> This class deals only with {@code char} values; it does not understand
* supplementary Unicode code points in the range {@code 0x10000} to {@code 0x10FFFF}. Such logical
* characters are encoded into a {@code String} using surrogate pairs, and a {@code CharMatcher}
* treats these just as two separate characters.
*
* <p>Example usages: <pre>
* String trimmed = {@link #WHITESPACE WHITESPACE}.{@link #trimFrom trimFrom}(userInput);
* if ({@link #ASCII ASCII}.{@link #matchesAllOf matchesAllOf}(s)) { ... }</pre>
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/StringsExplained#CharMatcher">
* {@code CharMatcher}</a>.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@Beta // Possibly change from chars to code points; decide constants vs. methods
@GwtCompatible(emulated = true)
public abstract class CharMatcher implements Predicate<Character> {
// Constants
/**
* Determines whether a character is a breaking whitespace (that is, a whitespace which can be
* interpreted as a break between words for formatting purposes). See {@link #WHITESPACE} for a
* discussion of that term.
*
* @since 2.0
*/
public static final CharMatcher BREAKING_WHITESPACE =
anyOf("\t\n\013\f\r \u0085\u1680\u2028\u2029\u205f\u3000")
.or(inRange('\u2000', '\u2006'))
.or(inRange('\u2008', '\u200a'))
.withToString("CharMatcher.BREAKING_WHITESPACE")
.precomputed();
/**
* Determines whether a character is ASCII, meaning that its code point is less than 128.
*/
public static final CharMatcher ASCII = inRange('\0', '\u007f', "CharMatcher.ASCII");
/**
* Determines whether a character is a digit according to
* <a href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5Cp%7Bdigit%7D">Unicode</a>.
*/
public static final CharMatcher DIGIT;
static {
CharMatcher digit = inRange('0', '9');
String zeroes =
"\u0660\u06f0\u07c0\u0966\u09e6\u0a66\u0ae6\u0b66\u0be6\u0c66"
+ "\u0ce6\u0d66\u0e50\u0ed0\u0f20\u1040\u1090\u17e0\u1810\u1946"
+ "\u19d0\u1b50\u1bb0\u1c40\u1c50\ua620\ua8d0\ua900\uaa50\uff10";
for (char base : zeroes.toCharArray()) {
digit = digit.or(inRange(base, (char) (base + 9)));
}
DIGIT = digit.withToString("CharMatcher.DIGIT").precomputed();
}
/**
* Determines whether a character is a digit according to {@link Character#isDigit(char) Java's
* definition}. If you only care to match ASCII digits, you can use {@code inRange('0', '9')}.
*/
public static final CharMatcher JAVA_DIGIT = new CharMatcher("CharMatcher.JAVA_DIGIT") {
@Override public boolean matches(char c) {
return Character.isDigit(c);
}
};
/**
* Determines whether a character is a letter according to {@link Character#isLetter(char) Java's
* definition}. If you only care to match letters of the Latin alphabet, you can use {@code
* inRange('a', 'z').or(inRange('A', 'Z'))}.
*/
public static final CharMatcher JAVA_LETTER = new CharMatcher("CharMatcher.JAVA_LETTER") {
@Override public boolean matches(char c) {
return Character.isLetter(c);
}
};
/**
* Determines whether a character is a letter or digit according to {@link
* Character#isLetterOrDigit(char) Java's definition}.
*/
public static final CharMatcher JAVA_LETTER_OR_DIGIT =
new CharMatcher("CharMatcher.JAVA_LETTER_OR_DIGIT") {
@Override public boolean matches(char c) {
return Character.isLetterOrDigit(c);
}
};
/**
* Determines whether a character is upper case according to {@link Character#isUpperCase(char)
* Java's definition}.
*/
public static final CharMatcher JAVA_UPPER_CASE =
new CharMatcher("CharMatcher.JAVA_UPPER_CASE") {
@Override public boolean matches(char c) {
return Character.isUpperCase(c);
}
};
/**
* Determines whether a character is lower case according to {@link Character#isLowerCase(char)
* Java's definition}.
*/
public static final CharMatcher JAVA_LOWER_CASE =
new CharMatcher("CharMatcher.JAVA_LOWER_CASE") {
@Override public boolean matches(char c) {
return Character.isLowerCase(c);
}
};
/**
* Determines whether a character is an ISO control character as specified by {@link
* Character#isISOControl(char)}.
*/
public static final CharMatcher JAVA_ISO_CONTROL =
inRange('\u0000', '\u001f')
.or(inRange('\u007f', '\u009f'))
.withToString("CharMatcher.JAVA_ISO_CONTROL");
/**
* Determines whether a character is invisible; that is, if its Unicode category is any of
* SPACE_SEPARATOR, LINE_SEPARATOR, PARAGRAPH_SEPARATOR, CONTROL, FORMAT, SURROGATE, and
* PRIVATE_USE according to ICU4J.
*/
public static final CharMatcher INVISIBLE = inRange('\u0000', '\u0020')
.or(inRange('\u007f', '\u00a0'))
.or(is('\u00ad'))
.or(inRange('\u0600', '\u0604'))
.or(anyOf("\u06dd\u070f\u1680\u180e"))
.or(inRange('\u2000', '\u200f'))
.or(inRange('\u2028', '\u202f'))
.or(inRange('\u205f', '\u2064'))
.or(inRange('\u206a', '\u206f'))
.or(is('\u3000'))
.or(inRange('\ud800', '\uf8ff'))
.or(anyOf("\ufeff\ufff9\ufffa\ufffb"))
.withToString("CharMatcher.INVISIBLE")
.precomputed();
/**
* Determines whether a character is single-width (not double-width). When in doubt, this matcher
* errs on the side of returning {@code false} (that is, it tends to assume a character is
* double-width).
*
* <p><b>Note:</b> as the reference file evolves, we will modify this constant to keep it up to
* date.
*/
public static final CharMatcher SINGLE_WIDTH = inRange('\u0000', '\u04f9')
.or(is('\u05be'))
.or(inRange('\u05d0', '\u05ea'))
.or(is('\u05f3'))
.or(is('\u05f4'))
.or(inRange('\u0600', '\u06ff'))
.or(inRange('\u0750', '\u077f'))
.or(inRange('\u0e00', '\u0e7f'))
.or(inRange('\u1e00', '\u20af'))
.or(inRange('\u2100', '\u213a'))
.or(inRange('\ufb50', '\ufdff'))
.or(inRange('\ufe70', '\ufeff'))
.or(inRange('\uff61', '\uffdc'))
.withToString("CharMatcher.SINGLE_WIDTH")
.precomputed();
/** Matches any character. */
public static final CharMatcher ANY =
new FastMatcher("CharMatcher.ANY") {
@Override public boolean matches(char c) {
return true;
}
@Override public int indexIn(CharSequence sequence) {
return (sequence.length() == 0) ? -1 : 0;
}
@Override public int indexIn(CharSequence sequence, int start) {
int length = sequence.length();
Preconditions.checkPositionIndex(start, length);
return (start == length) ? -1 : start;
}
@Override public int lastIndexIn(CharSequence sequence) {
return sequence.length() - 1;
}
@Override public boolean matchesAllOf(CharSequence sequence) {
checkNotNull(sequence);
return true;
}
@Override public boolean matchesNoneOf(CharSequence sequence) {
return sequence.length() == 0;
}
@Override public String removeFrom(CharSequence sequence) {
checkNotNull(sequence);
return "";
}
@Override public String replaceFrom(CharSequence sequence, char replacement) {
char[] array = new char[sequence.length()];
Arrays.fill(array, replacement);
return new String(array);
}
@Override public String replaceFrom(CharSequence sequence, CharSequence replacement) {
StringBuilder retval = new StringBuilder(sequence.length() * replacement.length());
for (int i = 0; i < sequence.length(); i++) {
retval.append(replacement);
}
return retval.toString();
}
@Override public String collapseFrom(CharSequence sequence, char replacement) {
return (sequence.length() == 0) ? "" : String.valueOf(replacement);
}
@Override public String trimFrom(CharSequence sequence) {
checkNotNull(sequence);
return "";
}
@Override public int countIn(CharSequence sequence) {
return sequence.length();
}
@Override public CharMatcher and(CharMatcher other) {
return checkNotNull(other);
}
@Override public CharMatcher or(CharMatcher other) {
checkNotNull(other);
return this;
}
@Override public CharMatcher negate() {
return NONE;
}
};
/** Matches no characters. */
public static final CharMatcher NONE =
new FastMatcher("CharMatcher.NONE") {
@Override public boolean matches(char c) {
return false;
}
@Override public int indexIn(CharSequence sequence) {
checkNotNull(sequence);
return -1;
}
@Override public int indexIn(CharSequence sequence, int start) {
int length = sequence.length();
Preconditions.checkPositionIndex(start, length);
return -1;
}
@Override public int lastIndexIn(CharSequence sequence) {
checkNotNull(sequence);
return -1;
}
@Override public boolean matchesAllOf(CharSequence sequence) {
return sequence.length() == 0;
}
@Override public boolean matchesNoneOf(CharSequence sequence) {
checkNotNull(sequence);
return true;
}
@Override public String removeFrom(CharSequence sequence) {
return sequence.toString();
}
@Override public String replaceFrom(CharSequence sequence, char replacement) {
return sequence.toString();
}
@Override public String replaceFrom(CharSequence sequence, CharSequence replacement) {
checkNotNull(replacement);
return sequence.toString();
}
@Override public String collapseFrom(CharSequence sequence, char replacement) {
return sequence.toString();
}
@Override public String trimFrom(CharSequence sequence) {
return sequence.toString();
}
@Override public int countIn(CharSequence sequence) {
checkNotNull(sequence);
return 0;
}
@Override public CharMatcher and(CharMatcher other) {
checkNotNull(other);
return this;
}
@Override public CharMatcher or(CharMatcher other) {
return checkNotNull(other);
}
@Override public CharMatcher negate() {
return ANY;
}
};
// Static factories
/**
* Returns a {@code char} matcher that matches only one specified character.
*/
public static CharMatcher is(final char match) {
String description = "CharMatcher.is(" + Integer.toHexString(match) + ")";
return new FastMatcher(description) {
@Override public boolean matches(char c) {
return c == match;
}
@Override public String replaceFrom(CharSequence sequence, char replacement) {
return sequence.toString().replace(match, replacement);
}
@Override public CharMatcher and(CharMatcher other) {
return other.matches(match) ? this : NONE;
}
@Override public CharMatcher or(CharMatcher other) {
return other.matches(match) ? other : super.or(other);
}
@Override public CharMatcher negate() {
return isNot(match);
}
@GwtIncompatible("java.util.BitSet")
@Override
void setBits(BitSet table) {
table.set(match);
}
};
}
/**
* Returns a {@code char} matcher that matches any character except the one specified.
*
* <p>To negate another {@code CharMatcher}, use {@link #negate()}.
*/
public static CharMatcher isNot(final char match) {
String description = "CharMatcher.isNot(" + Integer.toHexString(match) + ")";
return new FastMatcher(description) {
@Override public boolean matches(char c) {
return c != match;
}
@Override public CharMatcher and(CharMatcher other) {
return other.matches(match) ? super.and(other) : other;
}
@Override public CharMatcher or(CharMatcher other) {
return other.matches(match) ? ANY : this;
}
@GwtIncompatible("java.util.BitSet")
@Override
void setBits(BitSet table) {
table.set(0, match);
table.set(match + 1, Character.MAX_VALUE + 1);
}
@Override public CharMatcher negate() {
return is(match);
}
};
}
/**
* Returns a {@code char} matcher that matches any character present in the given character
* sequence.
*/
public static CharMatcher anyOf(final CharSequence sequence) {
switch (sequence.length()) {
case 0:
return NONE;
case 1:
return is(sequence.charAt(0));
case 2:
return isEither(sequence.charAt(0), sequence.charAt(1));
}
// TODO(user): is it potentially worth just going ahead and building a precomputed matcher?
final char[] chars = sequence.toString().toCharArray();
Arrays.sort(chars);
String description = "CharMatcher.anyOf(\"" + String.valueOf(chars) + "\")";
return new CharMatcher(description) {
@Override public boolean matches(char c) {
return Arrays.binarySearch(chars, c) >= 0;
}
};
}
private static CharMatcher isEither(
final char match1,
final char match2) {
String description = "CharMatcher.anyOf(\"" + match1 + match2 + "\")";
return new FastMatcher(description) {
@Override public boolean matches(char c) {
return c == match1 || c == match2;
}
@GwtIncompatible("java.util.BitSet")
@Override void setBits(BitSet table) {
table.set(match1);
table.set(match2);
}
};
}
/**
* Returns a {@code char} matcher that matches any character not present in the given character
* sequence.
*/
public static CharMatcher noneOf(CharSequence sequence) {
return anyOf(sequence).negate();
}
/**
* Returns a {@code char} matcher that matches any character in a given range (both endpoints are
* inclusive). For example, to match any lowercase letter of the English alphabet, use {@code
* CharMatcher.inRange('a', 'z')}.
*
* @throws IllegalArgumentException if {@code endInclusive < startInclusive}
*/
public static CharMatcher inRange(final char startInclusive, final char endInclusive) {
checkArgument(endInclusive >= startInclusive);
String description = "CharMatcher.inRange(" +
Integer.toHexString(startInclusive) + ", " +
Integer.toHexString(endInclusive) + ")";
return inRange(startInclusive, endInclusive, description);
}
static CharMatcher inRange(final char startInclusive, final char endInclusive,
String description) {
return new FastMatcher(description) {
@Override public boolean matches(char c) {
return startInclusive <= c && c <= endInclusive;
}
@GwtIncompatible("java.util.BitSet")
@Override void setBits(BitSet table) {
table.set(startInclusive, endInclusive + 1);
}
};
}
/**
* Returns a matcher with identical behavior to the given {@link Character}-based predicate, but
* which operates on primitive {@code char} instances instead.
*/
public static CharMatcher forPredicate(final Predicate<? super Character> predicate) {
checkNotNull(predicate);
if (predicate instanceof CharMatcher) {
return (CharMatcher) predicate;
}
String description = "CharMatcher.forPredicate(" + predicate + ")";
return new CharMatcher(description) {
@Override public boolean matches(char c) {
return predicate.apply(c);
}
@Override public boolean apply(Character character) {
return predicate.apply(checkNotNull(character));
}
};
}
// State
final String description;
// Constructors
/**
* Sets the {@code toString()} from the given description.
*/
CharMatcher(String description) {
this.description = description;
}
/**
* Constructor for use by subclasses. When subclassing, you may want to override
* {@code toString()} to provide a useful description.
*/
protected CharMatcher() {
description = "UnknownCharMatcher";
}
// Abstract methods
/** Determines a true or false value for the given character. */
public abstract boolean matches(char c);
// Non-static factories
/**
* Returns a matcher that matches any character not matched by this matcher.
*/
public CharMatcher negate() {
return new NegatedMatcher(this);
}
private static class NegatedMatcher extends CharMatcher {
final CharMatcher original;
NegatedMatcher(String toString, CharMatcher original) {
super(toString);
this.original = original;
}
NegatedMatcher(CharMatcher original) {
this(original + ".negate()", original);
}
@Override public boolean matches(char c) {
return !original.matches(c);
}
@Override public boolean matchesAllOf(CharSequence sequence) {
return original.matchesNoneOf(sequence);
}
@Override public boolean matchesNoneOf(CharSequence sequence) {
return original.matchesAllOf(sequence);
}
@Override public int countIn(CharSequence sequence) {
return sequence.length() - original.countIn(sequence);
}
@GwtIncompatible("java.util.BitSet")
@Override
void setBits(BitSet table) {
BitSet tmp = new BitSet();
original.setBits(tmp);
tmp.flip(Character.MIN_VALUE, Character.MAX_VALUE + 1);
table.or(tmp);
}
@Override public CharMatcher negate() {
return original;
}
@Override
CharMatcher withToString(String description) {
return new NegatedMatcher(description, original);
}
}
/**
* Returns a matcher that matches any character matched by both this matcher and {@code other}.
*/
public CharMatcher and(CharMatcher other) {
return new And(this, checkNotNull(other));
}
private static class And extends CharMatcher {
final CharMatcher first;
final CharMatcher second;
And(CharMatcher a, CharMatcher b) {
this(a, b, "CharMatcher.and(" + a + ", " + b + ")");
}
And(CharMatcher a, CharMatcher b, String description) {
super(description);
first = checkNotNull(a);
second = checkNotNull(b);
}
@Override
public boolean matches(char c) {
return first.matches(c) && second.matches(c);
}
@GwtIncompatible("java.util.BitSet")
@Override
void setBits(BitSet table) {
BitSet tmp1 = new BitSet();
first.setBits(tmp1);
BitSet tmp2 = new BitSet();
second.setBits(tmp2);
tmp1.and(tmp2);
table.or(tmp1);
}
@Override
CharMatcher withToString(String description) {
return new And(first, second, description);
}
}
/**
* Returns a matcher that matches any character matched by either this matcher or {@code other}.
*/
public CharMatcher or(CharMatcher other) {
return new Or(this, checkNotNull(other));
}
private static class Or extends CharMatcher {
final CharMatcher first;
final CharMatcher second;
Or(CharMatcher a, CharMatcher b, String description) {
super(description);
first = checkNotNull(a);
second = checkNotNull(b);
}
Or(CharMatcher a, CharMatcher b) {
this(a, b, "CharMatcher.or(" + a + ", " + b + ")");
}
@GwtIncompatible("java.util.BitSet")
@Override
void setBits(BitSet table) {
first.setBits(table);
second.setBits(table);
}
@Override
public boolean matches(char c) {
return first.matches(c) || second.matches(c);
}
@Override
CharMatcher withToString(String description) {
return new Or(first, second, description);
}
}
/**
* Returns a {@code char} matcher functionally equivalent to this one, but which may be faster to
* query than the original; your mileage may vary. Precomputation takes time and is likely to be
* worthwhile only if the precomputed matcher is queried many thousands of times.
*
* <p>This method has no effect (returns {@code this}) when called in GWT: it's unclear whether a
* precomputed matcher is faster, but it certainly consumes more memory, which doesn't seem like a
* worthwhile tradeoff in a browser.
*/
public CharMatcher precomputed() {
return Platform.precomputeCharMatcher(this);
}
/**
* Subclasses should provide a new CharMatcher with the same characteristics as {@code this},
* but with their {@code toString} method overridden with the new description.
*
* <p>This is unsupported by default.
*/
CharMatcher withToString(String description) {
throw new UnsupportedOperationException();
}
private static final int DISTINCT_CHARS = Character.MAX_VALUE - Character.MIN_VALUE + 1;
/**
* This is the actual implementation of {@link #precomputed}, but we bounce calls through a
* method on {@link Platform} so that we can have different behavior in GWT.
*
* <p>This implementation tries to be smart in a number of ways. It recognizes cases where
* the negation is cheaper to precompute than the matcher itself; it tries to build small
* hash tables for matchers that only match a few characters, and so on. In the worst-case
* scenario, it constructs an eight-kilobyte bit array and queries that.
* In many situations this produces a matcher which is faster to query than the original.
*/
@GwtIncompatible("java.util.BitSet")
CharMatcher precomputedInternal() {
final BitSet table = new BitSet();
setBits(table);
int totalCharacters = table.cardinality();
if (totalCharacters * 2 <= DISTINCT_CHARS) {
return precomputedPositive(totalCharacters, table, description);
} else {
// TODO(user): is it worth it to worry about the last character of large matchers?
table.flip(Character.MIN_VALUE, Character.MAX_VALUE + 1);
int negatedCharacters = DISTINCT_CHARS - totalCharacters;
return new NegatedFastMatcher(toString(),
precomputedPositive(negatedCharacters, table, description + ".negate()"));
}
}
/**
* A matcher for which precomputation will not yield any significant benefit.
*/
abstract static class FastMatcher extends CharMatcher {
FastMatcher() {
super();
}
FastMatcher(String description) {
super(description);
}
@Override
public final CharMatcher precomputed() {
return this;
}
@Override
public CharMatcher negate() {
return new NegatedFastMatcher(this);
}
}
static final class NegatedFastMatcher extends NegatedMatcher {
NegatedFastMatcher(CharMatcher original) {
super(original);
}
NegatedFastMatcher(String toString, CharMatcher original) {
super(toString, original);
}
@Override
public final CharMatcher precomputed() {
return this;
}
@Override
CharMatcher withToString(String description) {
return new NegatedFastMatcher(description, original);
}
}
/**
* Helper method for {@link #precomputedInternal} that doesn't test if the negation is cheaper.
*/
@GwtIncompatible("java.util.BitSet")
private static CharMatcher precomputedPositive(
int totalCharacters,
BitSet table,
String description) {
switch (totalCharacters) {
case 0:
return NONE;
case 1:
return is((char) table.nextSetBit(0));
case 2: {
char c1 = (char) table.nextSetBit(0);
char c2 = (char) table.nextSetBit(c1 + 1);
return isEither(c1, c2);
}
}
if (totalCharacters <= SmallCharMatcher.MAX_SIZE) {
return SmallCharMatcher.from(table, description);
} else if (totalCharacters <= MediumCharMatcher.MAX_SIZE) {
return MediumCharMatcher.from(table, description);
} else {
if (table.length() + Long.SIZE < table.size()) {
table = (BitSet) table.clone();
// If only we could actually call BitSet.trimToSize() ourselves...
}
return new BitSetMatcher(table, description);
}
}
@GwtIncompatible("java.util.BitSet")
private static class BitSetMatcher extends FastMatcher {
private final BitSet table;
private BitSetMatcher(BitSet table, String description) {
super(description);
this.table = table;
}
@Override public boolean matches(char c) {
return table.get(c);
}
@Override
void setBits(BitSet bitSet) {
bitSet.or(table);
}
}
/**
* Sets bits in {@code table} matched by this matcher.
*/
@GwtIncompatible("java.util.BitSet")
void setBits(BitSet table) {
for (int c = Character.MAX_VALUE; c >= Character.MIN_VALUE; c--) {
if (matches((char) c)) {
table.set(c);
}
}
}
// Text processing routines
/**
* Returns {@code true} if a character sequence contains at least one matching character.
* Equivalent to {@code !matchesNoneOf(sequence)}.
*
* <p>The default implementation iterates over the sequence, invoking {@link #matches} for each
* character, until this returns {@code true} or the end is reached.
*
* @param sequence the character sequence to examine, possibly empty
* @return {@code true} if this matcher matches at least one character in the sequence
* @since 8.0
*/
public boolean matchesAnyOf(CharSequence sequence) {
return !matchesNoneOf(sequence);
}
/**
* Returns {@code true} if a character sequence contains only matching characters.
*
* <p>The default implementation iterates over the sequence, invoking {@link #matches} for each
* character, until this returns {@code false} or the end is reached.
*
* @param sequence the character sequence to examine, possibly empty
* @return {@code true} if this matcher matches every character in the sequence, including when
* the sequence is empty
*/
public boolean matchesAllOf(CharSequence sequence) {
for (int i = sequence.length() - 1; i >= 0; i--) {
if (!matches(sequence.charAt(i))) {
return false;
}
}
return true;
}
/**
* Returns {@code true} if a character sequence contains no matching characters. Equivalent to
* {@code !matchesAnyOf(sequence)}.
*
* <p>The default implementation iterates over the sequence, invoking {@link #matches} for each
* character, until this returns {@code false} or the end is reached.
*
* @param sequence the character sequence to examine, possibly empty
* @return {@code true} if this matcher matches every character in the sequence, including when
* the sequence is empty
*/
public boolean matchesNoneOf(CharSequence sequence) {
return indexIn(sequence) == -1;
}
/**
* Returns the index of the first matching character in a character sequence, or {@code -1} if no
* matching character is present.
*
* <p>The default implementation iterates over the sequence in forward order calling {@link
* #matches} for each character.
*
* @param sequence the character sequence to examine from the beginning
* @return an index, or {@code -1} if no character matches
*/
public int indexIn(CharSequence sequence) {
int length = sequence.length();
for (int i = 0; i < length; i++) {
if (matches(sequence.charAt(i))) {
return i;
}
}
return -1;
}
/**
* Returns the index of the first matching character in a character sequence, starting from a
* given position, or {@code -1} if no character matches after that position.
*
* <p>The default implementation iterates over the sequence in forward order, beginning at {@code
* start}, calling {@link #matches} for each character.
*
* @param sequence the character sequence to examine
* @param start the first index to examine; must be nonnegative and no greater than {@code
* sequence.length()}
* @return the index of the first matching character, guaranteed to be no less than {@code start},
* or {@code -1} if no character matches
* @throws IndexOutOfBoundsException if start is negative or greater than {@code
* sequence.length()}
*/
public int indexIn(CharSequence sequence, int start) {
int length = sequence.length();
Preconditions.checkPositionIndex(start, length);
for (int i = start; i < length; i++) {
if (matches(sequence.charAt(i))) {
return i;
}
}
return -1;
}
/**
* Returns the index of the last matching character in a character sequence, or {@code -1} if no
* matching character is present.
*
* <p>The default implementation iterates over the sequence in reverse order calling {@link
* #matches} for each character.
*
* @param sequence the character sequence to examine from the end
* @return an index, or {@code -1} if no character matches
*/
public int lastIndexIn(CharSequence sequence) {
for (int i = sequence.length() - 1; i >= 0; i--) {
if (matches(sequence.charAt(i))) {
return i;
}
}
return -1;
}
/**
* Returns the number of matching characters found in a character sequence.
*/
public int countIn(CharSequence sequence) {
int count = 0;
for (int i = 0; i < sequence.length(); i++) {
if (matches(sequence.charAt(i))) {
count++;
}
}
return count;
}
/**
* Returns a string containing all non-matching characters of a character sequence, in order. For
* example: <pre> {@code
*
* CharMatcher.is('a').removeFrom("bazaar")}</pre>
*
* ... returns {@code "bzr"}.
*/
@CheckReturnValue
public String removeFrom(CharSequence sequence) {
String string = sequence.toString();
int pos = indexIn(string);
if (pos == -1) {
return string;
}
char[] chars = string.toCharArray();
int spread = 1;
// This unusual loop comes from extensive benchmarking
OUT: while (true) {
pos++;
while (true) {
if (pos == chars.length) {
break OUT;
}
if (matches(chars[pos])) {
break;
}
chars[pos - spread] = chars[pos];
pos++;
}
spread++;
}
return new String(chars, 0, pos - spread);
}
/**
* Returns a string containing all matching characters of a character sequence, in order. For
* example: <pre> {@code
*
* CharMatcher.is('a').retainFrom("bazaar")}</pre>
*
* ... returns {@code "aaa"}.
*/
@CheckReturnValue
public String retainFrom(CharSequence sequence) {
return negate().removeFrom(sequence);
}
/**
* Returns a string copy of the input character sequence, with each character that matches this
* matcher replaced by a given replacement character. For example: <pre> {@code
*
* CharMatcher.is('a').replaceFrom("radar", 'o')}</pre>
*
* ... returns {@code "rodor"}.
*
* <p>The default implementation uses {@link #indexIn(CharSequence)} to find the first matching
* character, then iterates the remainder of the sequence calling {@link #matches(char)} for each
* character.
*
* @param sequence the character sequence to replace matching characters in
* @param replacement the character to append to the result string in place of each matching
* character in {@code sequence}
* @return the new string
*/
@CheckReturnValue
public String replaceFrom(CharSequence sequence, char replacement) {
String string = sequence.toString();
int pos = indexIn(string);
if (pos == -1) {
return string;
}
char[] chars = string.toCharArray();
chars[pos] = replacement;
for (int i = pos + 1; i < chars.length; i++) {
if (matches(chars[i])) {
chars[i] = replacement;
}
}
return new String(chars);
}
/**
* Returns a string copy of the input character sequence, with each character that matches this
* matcher replaced by a given replacement sequence. For example: <pre> {@code
*
* CharMatcher.is('a').replaceFrom("yaha", "oo")}</pre>
*
* ... returns {@code "yoohoo"}.
*
* <p><b>Note:</b> If the replacement is a fixed string with only one character, you are better
* off calling {@link #replaceFrom(CharSequence, char)} directly.
*
* @param sequence the character sequence to replace matching characters in
* @param replacement the characters to append to the result string in place of each matching
* character in {@code sequence}
* @return the new string
*/
@CheckReturnValue
public String replaceFrom(CharSequence sequence, CharSequence replacement) {
int replacementLen = replacement.length();
if (replacementLen == 0) {
return removeFrom(sequence);
}
if (replacementLen == 1) {
return replaceFrom(sequence, replacement.charAt(0));
}
String string = sequence.toString();
int pos = indexIn(string);
if (pos == -1) {
return string;
}
int len = string.length();
StringBuilder buf = new StringBuilder((len * 3 / 2) + 16);
int oldpos = 0;
do {
buf.append(string, oldpos, pos);
buf.append(replacement);
oldpos = pos + 1;
pos = indexIn(string, oldpos);
} while (pos != -1);
buf.append(string, oldpos, len);
return buf.toString();
}
/**
* Returns a substring of the input character sequence that omits all characters this matcher
* matches from the beginning and from the end of the string. For example: <pre> {@code
*
* CharMatcher.anyOf("ab").trimFrom("abacatbab")}</pre>
*
* ... returns {@code "cat"}.
*
* <p>Note that: <pre> {@code
*
* CharMatcher.inRange('\0', ' ').trimFrom(str)}</pre>
*
* ... is equivalent to {@link String#trim()}.
*/
@CheckReturnValue
public String trimFrom(CharSequence sequence) {
int len = sequence.length();
int first;
int last;
for (first = 0; first < len; first++) {
if (!matches(sequence.charAt(first))) {
break;
}
}
for (last = len - 1; last > first; last--) {
if (!matches(sequence.charAt(last))) {
break;
}
}
return sequence.subSequence(first, last + 1).toString();
}
/**
* Returns a substring of the input character sequence that omits all characters this matcher
* matches from the beginning of the string. For example: <pre> {@code
*
* CharMatcher.anyOf("ab").trimLeadingFrom("abacatbab")}</pre>
*
* ... returns {@code "catbab"}.
*/
@CheckReturnValue
public String trimLeadingFrom(CharSequence sequence) {
int len = sequence.length();
int first;
for (first = 0; first < len; first++) {
if (!matches(sequence.charAt(first))) {
break;
}
}
return sequence.subSequence(first, len).toString();
}
/**
* Returns a substring of the input character sequence that omits all characters this matcher
* matches from the end of the string. For example: <pre> {@code
*
* CharMatcher.anyOf("ab").trimTrailingFrom("abacatbab")}</pre>
*
* ... returns {@code "abacat"}.
*/
@CheckReturnValue
public String trimTrailingFrom(CharSequence sequence) {
int len = sequence.length();
int last;
for (last = len - 1; last >= 0; last--) {
if (!matches(sequence.charAt(last))) {
break;
}
}
return sequence.subSequence(0, last + 1).toString();
}
/**
* Returns a string copy of the input character sequence, with each group of consecutive
* characters that match this matcher replaced by a single replacement character. For example:
* <pre> {@code
*
* CharMatcher.anyOf("eko").collapseFrom("bookkeeper", '-')}</pre>
*
* ... returns {@code "b-p-r"}.
*
* <p>The default implementation uses {@link #indexIn(CharSequence)} to find the first matching
* character, then iterates the remainder of the sequence calling {@link #matches(char)} for each
* character.
*
* @param sequence the character sequence to replace matching groups of characters in
* @param replacement the character to append to the result string in place of each group of
* matching characters in {@code sequence}
* @return the new string
*/
@CheckReturnValue
public String collapseFrom(CharSequence sequence, char replacement) {
int first = indexIn(sequence);
if (first == -1) {
return sequence.toString();
}
// TODO(kevinb): see if this implementation can be made faster
StringBuilder builder = new StringBuilder(sequence.length())
.append(sequence.subSequence(0, first))
.append(replacement);
boolean in = true;
for (int i = first + 1; i < sequence.length(); i++) {
char c = sequence.charAt(i);
if (matches(c)) {
if (!in) {
builder.append(replacement);
in = true;
}
} else {
builder.append(c);
in = false;
}
}
return builder.toString();
}
/**
* Collapses groups of matching characters exactly as {@link #collapseFrom} does, except that
* groups of matching characters at the start or end of the sequence are removed without
* replacement.
*/
@CheckReturnValue
public String trimAndCollapseFrom(CharSequence sequence, char replacement) {
int first = negate().indexIn(sequence);
if (first == -1) {
return ""; // everything matches. nothing's left.
}
StringBuilder builder = new StringBuilder(sequence.length());
boolean inMatchingGroup = false;
for (int i = first; i < sequence.length(); i++) {
char c = sequence.charAt(i);
if (matches(c)) {
inMatchingGroup = true;
} else {
if (inMatchingGroup) {
builder.append(replacement);
inMatchingGroup = false;
}
builder.append(c);
}
}
return builder.toString();
}
// Predicate interface
/**
* Returns {@code true} if this matcher matches the given character.
*
* @throws NullPointerException if {@code character} is null
*/
@Override public boolean apply(Character character) {
return matches(character);
}
/**
* Returns a string representation of this {@code CharMatcher}, such as
* {@code CharMatcher.or(WHITESPACE, JAVA_DIGIT)}.
*/
@Override
public String toString() {
return description;
}
/**
* Determines whether a character is whitespace according to the latest Unicode standard, as
* illustrated
* <a href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5Cp%7Bwhitespace%7D">here</a>.
* This is not the same definition used by other Java APIs. (See a
* <a href="http://spreadsheets.google.com/pub?key=pd8dAQyHbdewRsnE5x5GzKQ">comparison of several
* definitions of "whitespace"</a>.)
*
* <p><b>Note:</b> as the Unicode definition evolves, we will modify this constant to keep it up
* to date.
*/
public static final CharMatcher WHITESPACE = new FastMatcher("CharMatcher.WHITESPACE") {
/**
* A special-case CharMatcher for Unicode whitespace characters that is extremely
* efficient both in space required and in time to check for matches.
*
* Implementation details.
* It turns out that all current (early 2012) Unicode characters are unique modulo 79:
* so we can construct a lookup table of exactly 79 entries, and just check the character code
* mod 79, and see if that character is in the table.
*
* There is a 1 at the beginning of the table so that the null character is not listed
* as whitespace.
*
* Other things we tried that did not prove to be beneficial, mostly due to speed concerns:
*
* * Binary search into the sorted list of characters, i.e., what
* CharMatcher.anyOf() does</li>
* * Perfect hash function into a table of size 26 (using an offset table and a special
* Jenkins hash function)</li>
* * Perfect-ish hash function that required two lookups into a single table of size 26.</li>
* * Using a power-of-2 sized hash table (size 64) with linear probing.</li>
*
* --Christopher Swenson, February 2012.
*/
// Mod-79 lookup table.
private final char[] table = {1, 0, 160, 0, 0, 0, 0, 0, 0, 9, 10, 11, 12, 13, 0, 0,
8232, 8233, 0, 0, 0, 0, 0, 8239, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
12288, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 133, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199,
8200, 8201, 8202, 0, 0, 0, 0, 0, 8287, 5760, 0, 0, 6158, 0, 0, 0};
@Override public boolean matches(char c) {
return table[c % 79] == c;
}
};
}
| 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.base;
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.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.CheckReturnValue;
/**
* An object that divides strings (or other instances of {@code CharSequence})
* into substrings, by recognizing a <i>separator</i> (a.k.a. "delimiter")
* which can be expressed as a single character, literal string, regular
* expression, {@code CharMatcher}, or by using a fixed substring length. This
* class provides the complementary functionality to {@link Joiner}.
*
* <p>Here is the most basic example of {@code Splitter} usage: <pre> {@code
*
* Splitter.on(',').split("foo,bar")}</pre>
*
* This invocation returns an {@code Iterable<String>} containing {@code "foo"}
* and {@code "bar"}, in that order.
*
* <p>By default {@code Splitter}'s behavior is very simplistic: <pre> {@code
*
* Splitter.on(',').split("foo,,bar, quux")}</pre>
*
* This returns an iterable containing {@code ["foo", "", "bar", " quux"]}.
* Notice that the splitter does not assume that you want empty strings removed,
* or that you wish to trim whitespace. If you want features like these, simply
* ask for them: <pre> {@code
*
* private static final Splitter MY_SPLITTER = Splitter.on(',')
* .trimResults()
* .omitEmptyStrings();}</pre>
*
* Now {@code MY_SPLITTER.split("foo, ,bar, quux,")} returns an iterable
* containing just {@code ["foo", "bar", "quux"]}. Note that the order in which
* the configuration methods are called is never significant; for instance,
* trimming is always applied first before checking for an empty result,
* regardless of the order in which the {@link #trimResults()} and
* {@link #omitEmptyStrings()} methods were invoked.
*
* <p><b>Warning: splitter instances are always immutable</b>; a configuration
* method such as {@code omitEmptyStrings} has no effect on the instance it
* is invoked on! You must store and use the new splitter instance returned by
* the method. This makes splitters thread-safe, and safe to store as {@code
* static final} constants (as illustrated above). <pre> {@code
*
* // Bad! Do not do this!
* Splitter splitter = Splitter.on('/');
* splitter.trimResults(); // does nothing!
* return splitter.split("wrong / wrong / wrong");}</pre>
*
* The separator recognized by the splitter does not have to be a single
* literal character as in the examples above. See the methods {@link
* #on(String)}, {@link #on(Pattern)} and {@link #on(CharMatcher)} for examples
* of other ways to specify separators.
*
* <p><b>Note:</b> this class does not mimic any of the quirky behaviors of
* similar JDK methods; for instance, it does not silently discard trailing
* separators, as does {@link String#split(String)}, nor does it have a default
* behavior of using five particular whitespace characters as separators, like
* {@link java.util.StringTokenizer}.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/StringsExplained#Splitter">
* {@code Splitter}</a>.
*
* @author Julien Silland
* @author Jesse Wilson
* @author Kevin Bourrillion
* @author Louis Wasserman
* @since 1.0
*/
@GwtCompatible(emulated = true)
public final class Splitter {
private final CharMatcher trimmer;
private final boolean omitEmptyStrings;
private final Strategy strategy;
private final int limit;
private Splitter(Strategy strategy) {
this(strategy, false, CharMatcher.NONE, Integer.MAX_VALUE);
}
private Splitter(Strategy strategy, boolean omitEmptyStrings,
CharMatcher trimmer, int limit) {
this.strategy = strategy;
this.omitEmptyStrings = omitEmptyStrings;
this.trimmer = trimmer;
this.limit = limit;
}
/**
* Returns a splitter that uses the given single-character separator. For
* example, {@code Splitter.on(',').split("foo,,bar")} returns an iterable
* containing {@code ["foo", "", "bar"]}.
*
* @param separator the character to recognize as a separator
* @return a splitter, with default settings, that recognizes that separator
*/
public static Splitter on(char separator) {
return on(CharMatcher.is(separator));
}
/**
* Returns a splitter that considers any single character matched by the
* given {@code CharMatcher} to be a separator. For example, {@code
* Splitter.on(CharMatcher.anyOf(";,")).split("foo,;bar,quux")} returns an
* iterable containing {@code ["foo", "", "bar", "quux"]}.
*
* @param separatorMatcher a {@link CharMatcher} that determines whether a
* character is a separator
* @return a splitter, with default settings, that uses this matcher
*/
public static Splitter on(final CharMatcher separatorMatcher) {
checkNotNull(separatorMatcher);
return new Splitter(new Strategy() {
@Override public SplittingIterator iterator(
Splitter splitter, final CharSequence toSplit) {
return new SplittingIterator(splitter, toSplit) {
@Override int separatorStart(int start) {
return separatorMatcher.indexIn(toSplit, start);
}
@Override int separatorEnd(int separatorPosition) {
return separatorPosition + 1;
}
};
}
});
}
/**
* Returns a splitter that uses the given fixed string as a separator. For
* example, {@code Splitter.on(", ").split("foo, bar, baz,qux")} returns an
* iterable containing {@code ["foo", "bar", "baz,qux"]}.
*
* @param separator the literal, nonempty string to recognize as a separator
* @return a splitter, with default settings, that recognizes that separator
*/
public static Splitter on(final String separator) {
checkArgument(separator.length() != 0,
"The separator may not be the empty string.");
return new Splitter(new Strategy() {
@Override public SplittingIterator iterator(
Splitter splitter, CharSequence toSplit) {
return new SplittingIterator(splitter, toSplit) {
@Override public int separatorStart(int start) {
int delimeterLength = separator.length();
positions:
for (int p = start, last = toSplit.length() - delimeterLength;
p <= last; p++) {
for (int i = 0; i < delimeterLength; i++) {
if (toSplit.charAt(i + p) != separator.charAt(i)) {
continue positions;
}
}
return p;
}
return -1;
}
@Override public int separatorEnd(int separatorPosition) {
return separatorPosition + separator.length();
}
};
}
});
}
/**
* Returns a splitter that considers any subsequence matching {@code
* pattern} to be a separator. For example, {@code
* Splitter.on(Pattern.compile("\r?\n")).split(entireFile)} splits a string
* into lines whether it uses DOS-style or UNIX-style line terminators.
*
* @param separatorPattern the pattern that determines whether a subsequence
* is a separator. This pattern may not match the empty string.
* @return a splitter, with default settings, that uses this pattern
* @throws IllegalArgumentException if {@code separatorPattern} matches the
* empty string
*/
@GwtIncompatible("java.util.regex")
public static Splitter on(final Pattern separatorPattern) {
checkNotNull(separatorPattern);
checkArgument(!separatorPattern.matcher("").matches(),
"The pattern may not match the empty string: %s", separatorPattern);
return new Splitter(new Strategy() {
@Override public SplittingIterator iterator(
final Splitter splitter, CharSequence toSplit) {
final Matcher matcher = separatorPattern.matcher(toSplit);
return new SplittingIterator(splitter, toSplit) {
@Override public int separatorStart(int start) {
return matcher.find(start) ? matcher.start() : -1;
}
@Override public int separatorEnd(int separatorPosition) {
return matcher.end();
}
};
}
});
}
/**
* Returns a splitter that considers any subsequence matching a given
* pattern (regular expression) to be a separator. For example, {@code
* Splitter.onPattern("\r?\n").split(entireFile)} splits a string into lines
* whether it uses DOS-style or UNIX-style line terminators. This is
* equivalent to {@code Splitter.on(Pattern.compile(pattern))}.
*
* @param separatorPattern the pattern that determines whether a subsequence
* is a separator. This pattern may not match the empty string.
* @return a splitter, with default settings, that uses this pattern
* @throws java.util.regex.PatternSyntaxException if {@code separatorPattern}
* is a malformed expression
* @throws IllegalArgumentException if {@code separatorPattern} matches the
* empty string
*/
@GwtIncompatible("java.util.regex")
public static Splitter onPattern(String separatorPattern) {
return on(Pattern.compile(separatorPattern));
}
/**
* Returns a splitter that divides strings into pieces of the given length.
* For example, {@code Splitter.fixedLength(2).split("abcde")} returns an
* iterable containing {@code ["ab", "cd", "e"]}. The last piece can be
* smaller than {@code length} but will never be empty.
*
* @param length the desired length of pieces after splitting
* @return a splitter, with default settings, that can split into fixed sized
* pieces
*/
public static Splitter fixedLength(final int length) {
checkArgument(length > 0, "The length may not be less than 1");
return new Splitter(new Strategy() {
@Override public SplittingIterator iterator(
final Splitter splitter, CharSequence toSplit) {
return new SplittingIterator(splitter, toSplit) {
@Override public int separatorStart(int start) {
int nextChunkStart = start + length;
return (nextChunkStart < toSplit.length() ? nextChunkStart : -1);
}
@Override public int separatorEnd(int separatorPosition) {
return separatorPosition;
}
};
}
});
}
/**
* Returns a splitter that behaves equivalently to {@code this} splitter, but
* automatically omits empty strings from the results. For example, {@code
* Splitter.on(',').omitEmptyStrings().split(",a,,,b,c,,")} returns an
* iterable containing only {@code ["a", "b", "c"]}.
*
* <p>If either {@code trimResults} option is also specified when creating a
* splitter, that splitter always trims results first before checking for
* emptiness. So, for example, {@code
* Splitter.on(':').omitEmptyStrings().trimResults().split(": : : ")} returns
* an empty iterable.
*
* <p>Note that it is ordinarily not possible for {@link #split(CharSequence)}
* to return an empty iterable, but when using this option, it can (if the
* input sequence consists of nothing but separators).
*
* @return a splitter with the desired configuration
*/
@CheckReturnValue
public Splitter omitEmptyStrings() {
return new Splitter(strategy, true, trimmer, limit);
}
/**
* Returns a splitter that behaves equivalently to {@code this} splitter but
* stops splitting after it reaches the limit.
* The limit defines the maximum number of items returned by the iterator.
*
* <p>For example,
* {@code Splitter.on(',').limit(3).split("a,b,c,d")} returns an iterable
* containing {@code ["a", "b", "c,d"]}. When omitting empty strings, the
* omitted strings do no count. Hence,
* {@code Splitter.on(',').limit(3).omitEmptyStrings().split("a,,,b,,,c,d")}
* returns an iterable containing {@code ["a", "b", "c,d"}.
* When trim is requested, all entries, including the last are trimmed. Hence
* {@code Splitter.on(',').limit(3).trimResults().split(" a , b , c , d ")}
* results in @{code ["a", "b", "c , d"]}.
*
* @param limit the maximum number of items returns
* @return a splitter with the desired configuration
* @since 9.0
*/
@CheckReturnValue
public Splitter limit(int limit) {
checkArgument(limit > 0, "must be greater than zero: %s", limit);
return new Splitter(strategy, omitEmptyStrings, trimmer, limit);
}
/**
* Returns a splitter that behaves equivalently to {@code this} splitter, but
* automatically removes leading and trailing {@linkplain
* CharMatcher#WHITESPACE whitespace} from each returned substring; equivalent
* to {@code trimResults(CharMatcher.WHITESPACE)}. For example, {@code
* Splitter.on(',').trimResults().split(" a, b ,c ")} returns an iterable
* containing {@code ["a", "b", "c"]}.
*
* @return a splitter with the desired configuration
*/
@CheckReturnValue
public Splitter trimResults() {
return trimResults(CharMatcher.WHITESPACE);
}
/**
* Returns a splitter that behaves equivalently to {@code this} splitter, but
* removes all leading or trailing characters matching the given {@code
* CharMatcher} from each returned substring. For example, {@code
* Splitter.on(',').trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__")}
* returns an iterable containing {@code ["a ", "b_ ", "c"]}.
*
* @param trimmer a {@link CharMatcher} that determines whether a character
* should be removed from the beginning/end of a subsequence
* @return a splitter with the desired configuration
*/
// TODO(kevinb): throw if a trimmer was already specified!
@CheckReturnValue
public Splitter trimResults(CharMatcher trimmer) {
checkNotNull(trimmer);
return new Splitter(strategy, omitEmptyStrings, trimmer, limit);
}
/**
* Splits {@code sequence} into string components and makes them available
* through an {@link Iterator}, which may be lazily evaluated.
*
* @param sequence the sequence of characters to split
* @return an iteration over the segments split from the parameter.
*/
public Iterable<String> split(final CharSequence sequence) {
checkNotNull(sequence);
return new Iterable<String>() {
@Override public Iterator<String> iterator() {
return spliterator(sequence);
}
@Override public String toString() {
return Joiner.on(", ")
.appendTo(new StringBuilder().append('['), this)
.append(']')
.toString();
}
};
}
private Iterator<String> spliterator(CharSequence sequence) {
return strategy.iterator(this, sequence);
}
/**
* Returns a {@code MapSplitter} which splits entries based on this splitter,
* and splits entries into keys and values using the specified separator.
*
* @since 10.0
*/
@CheckReturnValue
@Beta
public MapSplitter withKeyValueSeparator(String separator) {
return withKeyValueSeparator(on(separator));
}
/**
* Returns a {@code MapSplitter} which splits entries based on this splitter,
* and splits entries into keys and values using the specified key-value
* splitter.
*
* @since 10.0
*/
@CheckReturnValue
@Beta
public MapSplitter withKeyValueSeparator(Splitter keyValueSplitter) {
return new MapSplitter(this, keyValueSplitter);
}
/**
* An object that splits strings into maps as {@code Splitter} splits
* iterables and lists. Like {@code Splitter}, it is thread-safe and
* immutable.
*
* @since 10.0
*/
@Beta
public static final class MapSplitter {
private static final String INVALID_ENTRY_MESSAGE =
"Chunk [%s] is not a valid entry";
private final Splitter outerSplitter;
private final Splitter entrySplitter;
private MapSplitter(Splitter outerSplitter, Splitter entrySplitter) {
this.outerSplitter = outerSplitter; // only "this" is passed
this.entrySplitter = checkNotNull(entrySplitter);
}
/**
* Splits {@code sequence} into substrings, splits each substring into
* an entry, and returns an unmodifiable map with each of the entries. For
* example, <code>
* Splitter.on(';').trimResults().withKeyValueSeparator("=>")
* .split("a=>b ; c=>b")
* </code> will return a mapping from {@code "a"} to {@code "b"} and
* {@code "c"} to {@code b}.
*
* <p>The returned map preserves the order of the entries from
* {@code sequence}.
*
* @throws IllegalArgumentException if the specified sequence does not split
* into valid map entries, or if there are duplicate keys
*/
public Map<String, String> split(CharSequence sequence) {
Map<String, String> map = new LinkedHashMap<String, String>();
for (String entry : outerSplitter.split(sequence)) {
Iterator<String> entryFields = entrySplitter.spliterator(entry);
checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
String key = entryFields.next();
checkArgument(!map.containsKey(key), "Duplicate key [%s] found.", key);
checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
String value = entryFields.next();
map.put(key, value);
checkArgument(!entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry);
}
return Collections.unmodifiableMap(map);
}
}
private interface Strategy {
Iterator<String> iterator(Splitter splitter, CharSequence toSplit);
}
private abstract static class SplittingIterator extends AbstractIterator<String> {
final CharSequence toSplit;
final CharMatcher trimmer;
final boolean omitEmptyStrings;
/**
* Returns the first index in {@code toSplit} at or after {@code start}
* that contains the separator.
*/
abstract int separatorStart(int start);
/**
* Returns the first index in {@code toSplit} after {@code
* separatorPosition} that does not contain a separator. This method is only
* invoked after a call to {@code separatorStart}.
*/
abstract int separatorEnd(int separatorPosition);
int offset = 0;
int limit;
protected SplittingIterator(Splitter splitter, CharSequence toSplit) {
this.trimmer = splitter.trimmer;
this.omitEmptyStrings = splitter.omitEmptyStrings;
this.limit = splitter.limit;
this.toSplit = toSplit;
}
@Override protected String computeNext() {
/*
* The returned string will be from the end of the last match to the
* beginning of the next one. nextStart is the start position of the
* returned substring, while offset is the place to start looking for a
* separator.
*/
int nextStart = offset;
while (offset != -1) {
int start = nextStart;
int end;
int separatorPosition = separatorStart(offset);
if (separatorPosition == -1) {
end = toSplit.length();
offset = -1;
} else {
end = separatorPosition;
offset = separatorEnd(separatorPosition);
}
if (offset == nextStart) {
/*
* This occurs when some pattern has an empty match, even if it
* doesn't match the empty string -- for example, if it requires
* lookahead or the like. The offset must be increased to look for
* separators beyond this point, without changing the start position
* of the next returned substring -- so nextStart stays the same.
*/
offset++;
if (offset >= toSplit.length()) {
offset = -1;
}
continue;
}
while (start < end && trimmer.matches(toSplit.charAt(start))) {
start++;
}
while (end > start && trimmer.matches(toSplit.charAt(end - 1))) {
end--;
}
if (omitEmptyStrings && start == end) {
// Don't include the (unused) separator in next split string.
nextStart = offset;
continue;
}
if (limit == 1) {
// The limit has been reached, return the rest of the string as the
// final item. This is tested after empty string removal so that
// empty strings do not count towards the limit.
end = toSplit.length();
offset = -1;
// Since we may have changed the end, we need to trim it again.
while (end > start && trimmer.matches(toSplit.charAt(end - 1))) {
end--;
}
} else {
limit--;
}
return toSplit.subSequence(start, end).toString();
}
return endOfData();
}
}
}
| 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.base;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import java.util.Formatter;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@code String} or {@code CharSequence}
* instances.
*
* @author Kevin Bourrillion
* @since 3.0
*/
@GwtCompatible
public final class Strings {
private Strings() {}
/**
* Returns the given string if it is non-null; the empty string otherwise.
*
* @param string the string to test and possibly return
* @return {@code string} itself if it is non-null; {@code ""} if it is null
*/
public static String nullToEmpty(@Nullable String string) {
return (string == null) ? "" : string;
}
/**
* Returns the given string if it is nonempty; {@code null} otherwise.
*
* @param string the string to test and possibly return
* @return {@code string} itself if it is nonempty; {@code null} if it is
* empty or null
*/
public static @Nullable String emptyToNull(@Nullable String string) {
return isNullOrEmpty(string) ? null : string;
}
/**
* Returns {@code true} if the given string is null or is the empty string.
*
* <p>Consider normalizing your string references with {@link #nullToEmpty}.
* If you do, you can use {@link String#isEmpty()} instead of this
* method, and you won't need special null-safe forms of methods like {@link
* String#toUpperCase} either. Or, if you'd like to normalize "in the other
* direction," converting empty strings to {@code null}, you can use {@link
* #emptyToNull}.
*
* @param string a string reference to check
* @return {@code true} if the string is null or is the empty string
*/
public static boolean isNullOrEmpty(@Nullable String string) {
return string == null || string.length() == 0; // string.isEmpty() in Java 6
}
/**
* Returns a string, of length at least {@code minLength}, consisting of
* {@code string} prepended with as many copies of {@code padChar} as are
* necessary to reach that length. For example,
*
* <ul>
* <li>{@code padStart("7", 3, '0')} returns {@code "007"}
* <li>{@code padStart("2010", 3, '0')} returns {@code "2010"}
* </ul>
*
* <p>See {@link Formatter} for a richer set of formatting capabilities.
*
* @param string the string which should appear at the end of the result
* @param minLength the minimum length the resulting string must have. Can be
* zero or negative, in which case the input string is always returned.
* @param padChar the character to insert at the beginning of the result until
* the minimum length is reached
* @return the padded string
*/
public static String padStart(String string, int minLength, char padChar) {
checkNotNull(string); // eager for GWT.
if (string.length() >= minLength) {
return string;
}
StringBuilder sb = new StringBuilder(minLength);
for (int i = string.length(); i < minLength; i++) {
sb.append(padChar);
}
sb.append(string);
return sb.toString();
}
/**
* Returns a string, of length at least {@code minLength}, consisting of
* {@code string} appended with as many copies of {@code padChar} as are
* necessary to reach that length. For example,
*
* <ul>
* <li>{@code padEnd("4.", 5, '0')} returns {@code "4.000"}
* <li>{@code padEnd("2010", 3, '!')} returns {@code "2010"}
* </ul>
*
* <p>See {@link Formatter} for a richer set of formatting capabilities.
*
* @param string the string which should appear at the beginning of the result
* @param minLength the minimum length the resulting string must have. Can be
* zero or negative, in which case the input string is always returned.
* @param padChar the character to append to the end of the result until the
* minimum length is reached
* @return the padded string
*/
public static String padEnd(String string, int minLength, char padChar) {
checkNotNull(string); // eager for GWT.
if (string.length() >= minLength) {
return string;
}
StringBuilder sb = new StringBuilder(minLength);
sb.append(string);
for (int i = string.length(); i < minLength; i++) {
sb.append(padChar);
}
return sb.toString();
}
/**
* Returns a string consisting of a specific number of concatenated copies of
* an input string. For example, {@code repeat("hey", 3)} returns the string
* {@code "heyheyhey"}.
*
* @param string any non-null string
* @param count the number of times to repeat it; a nonnegative integer
* @return a string containing {@code string} repeated {@code count} times
* (the empty string if {@code count} is zero)
* @throws IllegalArgumentException if {@code count} is negative
*/
public static String repeat(String string, int count) {
checkNotNull(string); // eager for GWT.
if (count <= 1) {
checkArgument(count >= 0, "invalid count: %s", count);
return (count == 0) ? "" : string;
}
// IF YOU MODIFY THE CODE HERE, you must update StringsRepeatBenchmark
final int len = string.length();
final long longSize = (long) len * (long) count;
final int size = (int) longSize;
if (size != longSize) {
throw new ArrayIndexOutOfBoundsException("Required array size too large: "
+ String.valueOf(longSize));
}
final char[] array = new char[size];
string.getChars(0, len, array, 0);
int n;
for (n = len; n < size - n; n <<= 1) {
System.arraycopy(array, 0, array, n, n);
}
System.arraycopy(array, 0, array, n, size - n);
return new String(array);
}
/**
* Returns the longest string {@code prefix} such that
* {@code a.toString().startsWith(prefix) && b.toString().startsWith(prefix)},
* taking care not to split surrogate pairs. If {@code a} and {@code b} have
* no common prefix, returns the empty string.
*
* @since 11.0
*/
public static String commonPrefix(CharSequence a, CharSequence b) {
checkNotNull(a);
checkNotNull(b);
int maxPrefixLength = Math.min(a.length(), b.length());
int p = 0;
while (p < maxPrefixLength && a.charAt(p) == b.charAt(p)) {
p++;
}
if (validSurrogatePairAt(a, p - 1) || validSurrogatePairAt(b, p - 1)) {
p--;
}
return a.subSequence(0, p).toString();
}
/**
* Returns the longest string {@code suffix} such that
* {@code a.toString().endsWith(suffix) && b.toString().endsWith(suffix)},
* taking care not to split surrogate pairs. If {@code a} and {@code b} have
* no common suffix, returns the empty string.
*
* @since 11.0
*/
public static String commonSuffix(CharSequence a, CharSequence b) {
checkNotNull(a);
checkNotNull(b);
int maxSuffixLength = Math.min(a.length(), b.length());
int s = 0;
while (s < maxSuffixLength
&& a.charAt(a.length() - s - 1) == b.charAt(b.length() - s - 1)) {
s++;
}
if (validSurrogatePairAt(a, a.length() - s - 1)
|| validSurrogatePairAt(b, b.length() - s - 1)) {
s--;
}
return a.subSequence(a.length() - s, a.length()).toString();
}
/**
* True when a valid surrogate pair starts at the given {@code index} in the
* given {@code string}. Out-of-range indexes return false.
*/
@VisibleForTesting
static boolean validSurrogatePairAt(CharSequence string, int index) {
return index >= 0 && index <= (string.length() - 2)
&& Character.isHighSurrogate(string.charAt(index))
&& Character.isLowSurrogate(string.charAt(index + 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.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
/**
* Utility class for converting between various ASCII case formats.
*
* @author Mike Bostock
* @since 1.0
*/
@GwtCompatible
public enum CaseFormat {
/**
* Hyphenated variable naming convention, e.g., "lower-hyphen".
*/
LOWER_HYPHEN(CharMatcher.is('-'), "-") {
@Override String normalizeWord(String word) {
return Ascii.toLowerCase(word);
}
@Override String convert(CaseFormat format, String s) {
if (format == LOWER_UNDERSCORE) {
return s.replace('-', '_');
}
if (format == UPPER_UNDERSCORE) {
return Ascii.toUpperCase(s.replace('-', '_'));
}
return super.convert(format, s);
}
},
/**
* C++ variable naming convention, e.g., "lower_underscore".
*/
LOWER_UNDERSCORE(CharMatcher.is('_'), "_") {
@Override String normalizeWord(String word) {
return Ascii.toLowerCase(word);
}
@Override String convert(CaseFormat format, String s) {
if (format == LOWER_HYPHEN) {
return s.replace('_', '-');
}
if (format == UPPER_UNDERSCORE) {
return Ascii.toUpperCase(s);
}
return super.convert(format, s);
}
},
/**
* Java variable naming convention, e.g., "lowerCamel".
*/
LOWER_CAMEL(CharMatcher.inRange('A', 'Z'), "") {
@Override String normalizeWord(String word) {
return firstCharOnlyToUpper(word);
}
},
/**
* Java and C++ class naming convention, e.g., "UpperCamel".
*/
UPPER_CAMEL(CharMatcher.inRange('A', 'Z'), "") {
@Override String normalizeWord(String word) {
return firstCharOnlyToUpper(word);
}
},
/**
* Java and C++ constant naming convention, e.g., "UPPER_UNDERSCORE".
*/
UPPER_UNDERSCORE(CharMatcher.is('_'), "_") {
@Override String normalizeWord(String word) {
return Ascii.toUpperCase(word);
}
@Override String convert(CaseFormat format, String s) {
if (format == LOWER_HYPHEN) {
return Ascii.toLowerCase(s.replace('_', '-'));
}
if (format == LOWER_UNDERSCORE) {
return Ascii.toLowerCase(s);
}
return super.convert(format, s);
}
};
private final CharMatcher wordBoundary;
private final String wordSeparator;
CaseFormat(CharMatcher wordBoundary, String wordSeparator) {
this.wordBoundary = wordBoundary;
this.wordSeparator = wordSeparator;
}
/**
* Converts the specified {@code String str} from this format to the specified {@code format}. A
* "best effort" approach is taken; if {@code str} does not conform to the assumed format, then
* the behavior of this method is undefined but we make a reasonable effort at converting anyway.
*/
public final String to(CaseFormat format, String str) {
checkNotNull(format);
checkNotNull(str);
return (format == this) ? str : convert(format, str);
}
/**
* Enum values can override for performance reasons.
*/
String convert(CaseFormat format, String s) {
// deal with camel conversion
StringBuilder out = null;
int i = 0;
int j = -1;
while ((j = wordBoundary.indexIn(s, ++j)) != -1) {
if (i == 0) {
// include some extra space for separators
out = new StringBuilder(s.length() + 4 * wordSeparator.length());
out.append(format.normalizeFirstWord(s.substring(i, j)));
} else {
out.append(format.normalizeWord(s.substring(i, j)));
}
out.append(format.wordSeparator);
i = j + wordSeparator.length();
}
return (i == 0)
? format.normalizeFirstWord(s)
: out.append(format.normalizeWord(s.substring(i))).toString();
}
abstract String normalizeWord(String word);
private String normalizeFirstWord(String word) {
return (this == LOWER_CAMEL) ? Ascii.toLowerCase(word) : normalizeWord(word);
}
private static String firstCharOnlyToUpper(String word) {
return (word.isEmpty())
? word
: new StringBuilder(word.length())
.append(Ascii.toUpperCase(word.charAt(0)))
.append(Ascii.toLowerCase(word.substring(1)))
.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.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to instances of {@link Throwable}.
*
* <p>See the Guava User Guide entry on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ThrowablesExplained">
* Throwables</a>.
*
* @author Kevin Bourrillion
* @author Ben Yu
* @since 1.0
*/
public final class Throwables {
private Throwables() {}
/**
* Propagates {@code throwable} exactly as-is, if and only if it is an
* instance of {@code declaredType}. Example usage:
* <pre>
* try {
* someMethodThatCouldThrowAnything();
* } catch (IKnowWhatToDoWithThisException e) {
* handle(e);
* } catch (Throwable t) {
* Throwables.propagateIfInstanceOf(t, IOException.class);
* Throwables.propagateIfInstanceOf(t, SQLException.class);
* throw Throwables.propagate(t);
* }
* </pre>
*/
public static <X extends Throwable> void propagateIfInstanceOf(
@Nullable Throwable throwable, Class<X> declaredType) throws X {
// Check for null is needed to avoid frequent JNI calls to isInstance().
if (throwable != null && declaredType.isInstance(throwable)) {
throw declaredType.cast(throwable);
}
}
/**
* Propagates {@code throwable} exactly as-is, if and only if it is an
* instance of {@link RuntimeException} or {@link Error}. Example usage:
* <pre>
* try {
* someMethodThatCouldThrowAnything();
* } catch (IKnowWhatToDoWithThisException e) {
* handle(e);
* } catch (Throwable t) {
* Throwables.propagateIfPossible(t);
* throw new RuntimeException("unexpected", t);
* }
* </pre>
*/
public static void propagateIfPossible(@Nullable Throwable throwable) {
propagateIfInstanceOf(throwable, Error.class);
propagateIfInstanceOf(throwable, RuntimeException.class);
}
/**
* Propagates {@code throwable} exactly as-is, if and only if it is an
* instance of {@link RuntimeException}, {@link Error}, or
* {@code declaredType}. Example usage:
* <pre>
* try {
* someMethodThatCouldThrowAnything();
* } catch (IKnowWhatToDoWithThisException e) {
* handle(e);
* } catch (Throwable t) {
* Throwables.propagateIfPossible(t, OtherException.class);
* throw new RuntimeException("unexpected", t);
* }
* </pre>
*
* @param throwable the Throwable to possibly propagate
* @param declaredType the single checked exception type declared by the
* calling method
*/
public static <X extends Throwable> void propagateIfPossible(
@Nullable Throwable throwable, Class<X> declaredType) throws X {
propagateIfInstanceOf(throwable, declaredType);
propagateIfPossible(throwable);
}
/**
* Propagates {@code throwable} exactly as-is, if and only if it is an
* instance of {@link RuntimeException}, {@link Error}, {@code declaredType1},
* or {@code declaredType2}. In the unlikely case that you have three or more
* declared checked exception types, you can handle them all by invoking these
* methods repeatedly. See usage example in {@link
* #propagateIfPossible(Throwable, Class)}.
*
* @param throwable the Throwable to possibly propagate
* @param declaredType1 any checked exception type declared by the calling
* method
* @param declaredType2 any other checked exception type declared by the
* calling method
*/
public static <X1 extends Throwable, X2 extends Throwable>
void propagateIfPossible(@Nullable Throwable throwable,
Class<X1> declaredType1, Class<X2> declaredType2) throws X1, X2 {
checkNotNull(declaredType2);
propagateIfInstanceOf(throwable, declaredType1);
propagateIfPossible(throwable, declaredType2);
}
/**
* Propagates {@code throwable} as-is if it is an instance of
* {@link RuntimeException} or {@link Error}, or else as a last resort, wraps
* it in a {@code RuntimeException} then propagates.
* <p>
* This method always throws an exception. The {@code RuntimeException} return
* type is only for client code to make Java type system happy in case a
* return value is required by the enclosing method. Example usage:
* <pre>
* T doSomething() {
* try {
* return someMethodThatCouldThrowAnything();
* } catch (IKnowWhatToDoWithThisException e) {
* return handle(e);
* } catch (Throwable t) {
* throw Throwables.propagate(t);
* }
* }
* </pre>
*
* @param throwable the Throwable to propagate
* @return nothing will ever be returned; this return type is only for your
* convenience, as illustrated in the example above
*/
public static RuntimeException propagate(Throwable throwable) {
propagateIfPossible(checkNotNull(throwable));
throw new RuntimeException(throwable);
}
/**
* Returns the innermost cause of {@code throwable}. The first throwable in a
* chain provides context from when the error or exception was initially
* detected. Example usage:
* <pre>
* assertEquals("Unable to assign a customer id",
* Throwables.getRootCause(e).getMessage());
* </pre>
*/
public static Throwable getRootCause(Throwable throwable) {
Throwable cause;
while ((cause = throwable.getCause()) != null) {
throwable = cause;
}
return throwable;
}
/**
* Gets a {@code Throwable} cause chain as a list. The first entry in the
* list will be {@code throwable} followed by its cause hierarchy. Note
* that this is a snapshot of the cause chain and will not reflect
* any subsequent changes to the cause chain.
*
* <p>Here's an example of how it can be used to find specific types
* of exceptions in the cause chain:
*
* <pre>
* Iterables.filter(Throwables.getCausalChain(e), IOException.class));
* </pre>
*
* @param throwable the non-null {@code Throwable} to extract causes from
* @return an unmodifiable list containing the cause chain starting with
* {@code throwable}
*/
@Beta // TODO(kevinb): decide best return type
public static List<Throwable> getCausalChain(Throwable throwable) {
checkNotNull(throwable);
List<Throwable> causes = new ArrayList<Throwable>(4);
while (throwable != null) {
causes.add(throwable);
throwable = throwable.getCause();
}
return Collections.unmodifiableList(causes);
}
/**
* Returns a string containing the result of
* {@link Throwable#toString() toString()}, followed by the full, recursive
* stack trace of {@code throwable}. Note that you probably should not be
* parsing the resulting string; if you need programmatic access to the stack
* frames, you can call {@link Throwable#getStackTrace()}.
*/
public static String getStackTraceAsString(Throwable throwable) {
StringWriter stringWriter = new StringWriter();
throwable.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.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.base;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
/**
* Soft reference with a {@code finalizeReferent()} method which a background thread invokes after
* the garbage collector reclaims the referent. This is a simpler alternative to using a {@link
* ReferenceQueue}.
*
* @author Bob Lee
* @since 2.0 (imported from Google Collections Library)
*/
public abstract class FinalizableSoftReference<T> extends SoftReference<T>
implements FinalizableReference {
/**
* Constructs a new finalizable soft reference.
*
* @param referent to softly reference
* @param queue that should finalize the referent
*/
protected FinalizableSoftReference(T referent, FinalizableReferenceQueue queue) {
super(referent, queue.queue);
queue.cleanUp();
}
}
| 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.base;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
* A time source; returns a time value representing the number of nanoseconds elapsed since some
* fixed but arbitrary point in time. Note that most users should use {@link Stopwatch} instead of
* interacting with this class directly.
*
* <p><b>Warning:</b> this interface can only be used to measure elapsed time, not wall time.
*
* @author Kevin Bourrillion
* @since 10.0
* (<a href="http://code.google.com/p/guava-libraries/wiki/Compatibility"
* >mostly source-compatible</a> since 9.0)
*/
@Beta
@GwtCompatible
public abstract class Ticker {
/**
* Constructor for use by subclasses.
*/
protected Ticker() {}
/**
* Returns the number of nanoseconds elapsed since this ticker's fixed
* point of reference.
*/
public abstract long read();
/**
* A ticker that reads the current time using {@link System#nanoTime}.
*
* @since 10.0
*/
public static Ticker systemTicker() {
return SYSTEM_TICKER;
}
private static final Ticker SYSTEM_TICKER = new Ticker() {
@Override
public long read() {
return Platform.systemNanoTime();
}
};
}
| 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.base;
/**
* Implemented by references that have code to run after garbage collection of their referents.
*
* @see FinalizableReferenceQueue
* @author Bob Lee
* @since 2.0 (imported from Google Collections Library)
*/
public interface FinalizableReference {
/**
* Invoked on a background thread after the referent has been garbage collected unless security
* restrictions prevented starting a background thread, in which case this method is invoked when
* new references are created.
*/
void finalizeReferent();
}
| 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.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.GwtCompatible;
import java.util.Collections;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Implementation of an {@link Optional} not containing a reference.
*/
@GwtCompatible
final class Absent extends Optional<Object> {
static final Absent INSTANCE = new Absent();
@Override public boolean isPresent() {
return false;
}
@Override public Object get() {
throw new IllegalStateException("Optional.get() cannot be called on an absent value");
}
@Override public Object or(Object defaultValue) {
return checkNotNull(defaultValue, "use Optional.orNull() instead of Optional.or(null)");
}
@SuppressWarnings("unchecked") // safe covariant cast
@Override public Optional<Object> or(Optional<?> secondChoice) {
return (Optional) checkNotNull(secondChoice);
}
@Override public Object or(Supplier<?> supplier) {
return checkNotNull(supplier.get(),
"use Optional.orNull() instead of a Supplier that returns null");
}
@Override @Nullable public Object orNull() {
return null;
}
@Override public Set<Object> asSet() {
return Collections.emptySet();
}
@Override public <V> Optional<V> transform(Function<Object, V> function) {
checkNotNull(function);
return Optional.absent();
}
@Override public boolean equals(@Nullable Object object) {
return object == this;
}
@Override public int hashCode() {
return 0x598df91c;
}
@Override public String toString() {
return "Optional.absent()";
}
private Object readResolve() {
return INSTANCE;
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* Copyright (C) 2012 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.base;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher.FastMatcher;
import java.util.BitSet;
/**
* An immutable small version of CharMatcher that uses an efficient hash table implementation, with
* non-power-of-2 sizing to try to use no reprobing, if possible.
*
* @author Christopher Swenson
*/
@GwtCompatible(emulated = true)
final class SmallCharMatcher extends FastMatcher {
static final int MAX_SIZE = 63;
static final int MAX_TABLE_SIZE = 128;
private final boolean reprobe;
private final char[] table;
private final boolean containsZero;
final long filter;
private SmallCharMatcher(char[] table, long filter, boolean containsZero,
boolean reprobe, String description) {
super(description);
this.table = table;
this.filter = filter;
this.containsZero = containsZero;
this.reprobe = reprobe;
}
private boolean checkFilter(int c) {
return 1 == (1 & (filter >> c));
}
@VisibleForTesting
static char[] buildTable(int modulus, char[] charArray, boolean reprobe) {
char[] table = new char[modulus];
for (char c : charArray) {
int index = c % modulus;
if (index < 0) {
index += modulus;
}
if ((table[index] != 0) && !reprobe) {
return null;
} else if (reprobe) {
while (table[index] != 0) {
index = (index + 1) % modulus;
}
}
table[index] = c;
}
return table;
}
@GwtIncompatible("java.util.BitSet")
static CharMatcher from(BitSet chars, String description) {
char[] charArray = new char[chars.cardinality()];
for (int i = 0, c = chars.nextSetBit(0); c != -1; c = chars.nextSetBit(c + 1)) {
charArray[i++] = (char) c;
}
return from(charArray, description);
}
static CharMatcher from(char[] chars, String description) {
int size = chars.length;
boolean containsZero = chars[0] == 0;
boolean reprobe = false;
// Compute the filter.
long filter = 0;
for (char c : chars) {
filter |= 1L << c;
}
char[] table = null;
for (int i = size; table == null && i < MAX_TABLE_SIZE; i++) {
table = buildTable(i, chars, false);
}
// Compute the hash table.
if (table == null) {
table = buildTable(MAX_TABLE_SIZE, chars, true);
reprobe = true;
}
return new SmallCharMatcher(table, filter, containsZero, reprobe, description);
}
@Override
public boolean matches(char c) {
if (c == 0) {
return containsZero;
}
if (!checkFilter(c)) {
return false;
}
int index = c % table.length;
if (index < 0) {
index += table.length;
}
while (true) {
// Check for empty.
if (table[index] == 0) {
return false;
} else if (table[index] == c) {
return true;
} else if (reprobe) {
// Linear probing will terminate eventually.
index = (index + 1) % table.length;
} else {
return false;
}
}
}
@GwtIncompatible("java.util.BitSet")
@Override
void setBits(BitSet bitSet) {
if (containsZero) {
bitSet.set(0);
}
for (char c : this.table) {
if (c != 0) {
bitSet.set(c);
}
}
}
}
| 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.base;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import java.util.concurrent.TimeUnit;
/**
* An object that measures elapsed time in nanoseconds. It is useful to measure
* elapsed time using this class instead of direct calls to {@link
* System#nanoTime} for a few reasons:
*
* <ul>
* <li>An alternate time source can be substituted, for testing or performance
* reasons.
* <li>As documented by {@code nanoTime}, the value returned has no absolute
* meaning, and can only be interpreted as relative to another timestamp
* returned by {@code nanoTime} at a different time. {@code Stopwatch} is a
* more effective abstraction because it exposes only these relative values,
* not the absolute ones.
* </ul>
*
* <p>Basic usage:
* <pre>
* Stopwatch stopwatch = new Stopwatch().{@link #start start}();
* doSomething();
* stopwatch.{@link #stop stop}(); // optional
*
* long millis = stopwatch.{@link #elapsedMillis elapsedMillis}();
*
* log.info("that took: " + stopwatch); // formatted string like "12.3 ms"
* </pre>
*
* <p>Stopwatch methods are not idempotent; it is an error to start or stop a
* stopwatch that is already in the desired state.
*
* <p>When testing code that uses this class, use the {@linkplain
* #Stopwatch(Ticker) alternate constructor} to supply a fake or mock ticker.
* <!-- TODO(kevinb): restore the "such as" --> This allows you to
* simulate any valid behavior of the stopwatch.
*
* <p><b>Note:</b> This class is not thread-safe.
*
* @author Kevin Bourrillion
* @since 10.0
*/
@Beta
@GwtCompatible(emulated=true)
public final class Stopwatch {
private final Ticker ticker;
private boolean isRunning;
private long elapsedNanos;
private long startTick;
/**
* Creates (but does not start) a new stopwatch using {@link System#nanoTime}
* as its time source.
*/
public Stopwatch() {
this(Ticker.systemTicker());
}
/**
* Creates (but does not start) a new stopwatch, using the specified time
* source.
*/
public Stopwatch(Ticker ticker) {
this.ticker = checkNotNull(ticker);
}
/**
* Returns {@code true} if {@link #start()} has been called on this stopwatch,
* and {@link #stop()} has not been called since the last call to {@code
* start()}.
*/
public boolean isRunning() {
return isRunning;
}
/**
* Starts the stopwatch.
*
* @return this {@code Stopwatch} instance
* @throws IllegalStateException if the stopwatch is already running.
*/
public Stopwatch start() {
checkState(!isRunning);
isRunning = true;
startTick = ticker.read();
return this;
}
/**
* Stops the stopwatch. Future reads will return the fixed duration that had
* elapsed up to this point.
*
* @return this {@code Stopwatch} instance
* @throws IllegalStateException if the stopwatch is already stopped.
*/
public Stopwatch stop() {
long tick = ticker.read();
checkState(isRunning);
isRunning = false;
elapsedNanos += tick - startTick;
return this;
}
/**
* Sets the elapsed time for this stopwatch to zero,
* and places it in a stopped state.
*
* @return this {@code Stopwatch} instance
*/
public Stopwatch reset() {
elapsedNanos = 0;
isRunning = false;
return this;
}
private long elapsedNanos() {
return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos;
}
/**
* Returns the current elapsed time shown on this stopwatch, expressed
* in the desired time unit, with any fraction rounded down.
*
* <p>Note that the overhead of measurement can be more than a microsecond, so
* it is generally not useful to specify {@link TimeUnit#NANOSECONDS}
* precision here.
*/
public long elapsedTime(TimeUnit desiredUnit) {
return desiredUnit.convert(elapsedNanos(), NANOSECONDS);
}
/**
* Returns the current elapsed time shown on this stopwatch, expressed
* in milliseconds, with any fraction rounded down. This is identical to
* {@code elapsedTime(TimeUnit.MILLISECONDS)}.
*/
public long elapsedMillis() {
return elapsedTime(MILLISECONDS);
}
/**
* Returns a string representation of the current elapsed time.
*/
@GwtIncompatible("String.format()")
@Override public String toString() {
return toString(4);
}
/**
* Returns a string representation of the current elapsed time, choosing an
* appropriate unit and using the specified number of significant figures.
* For example, at the instant when {@code elapsedTime(NANOSECONDS)} would
* return {1234567}, {@code toString(4)} returns {@code "1.235 ms"}.
*
* @deprecated Use {@link #toString()} instead. This method is scheduled
* to be removed in Guava release 15.0.
*/
@Deprecated
@GwtIncompatible("String.format()")
public String toString(int significantDigits) {
long nanos = elapsedNanos();
TimeUnit unit = chooseUnit(nanos);
double value = (double) nanos / NANOSECONDS.convert(1, unit);
// Too bad this functionality is not exposed as a regular method call
return String.format("%." + significantDigits + "g %s",
value, abbreviate(unit));
}
private static TimeUnit chooseUnit(long nanos) {
if (SECONDS.convert(nanos, NANOSECONDS) > 0) {
return SECONDS;
}
if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) {
return MILLISECONDS;
}
if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) {
return MICROSECONDS;
}
return NANOSECONDS;
}
private static String abbreviate(TimeUnit unit) {
switch (unit) {
case NANOSECONDS:
return "ns";
case MICROSECONDS:
return "\u03bcs"; // μs
case MILLISECONDS:
return "ms";
case SECONDS:
return "s";
default:
throw new AssertionError();
}
}
}
| 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.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import javax.annotation.Nullable;
/**
* Equivalence applied on functional result.
*
* @author Bob Lee
* @since 10.0
*/
@Beta
@GwtCompatible
final class FunctionalEquivalence<F, T> extends Equivalence<F>
implements Serializable {
private static final long serialVersionUID = 0;
private final Function<F, ? extends T> function;
private final Equivalence<T> resultEquivalence;
FunctionalEquivalence(
Function<F, ? extends T> function, Equivalence<T> resultEquivalence) {
this.function = checkNotNull(function);
this.resultEquivalence = checkNotNull(resultEquivalence);
}
@Override protected boolean doEquivalent(F a, F b) {
return resultEquivalence.equivalent(function.apply(a), function.apply(b));
}
@Override protected int doHash(F a) {
return resultEquivalence.hash(function.apply(a));
}
@Override public boolean equals(@Nullable Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof FunctionalEquivalence) {
FunctionalEquivalence<?, ?> that = (FunctionalEquivalence<?, ?>) obj;
return function.equals(that.function)
&& resultEquivalence.equals(that.resultEquivalence);
}
return false;
}
@Override public int hashCode() {
return Objects.hashCode(function, resultEquivalence);
}
@Override public String toString() {
return resultEquivalence + ".onResultOf(" + function + ")";
}
}
| 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.base.internal;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Thread that finalizes referents. All references should implement
* {@code com.google.common.base.FinalizableReference}.
*
* <p>While this class is public, we consider it to be *internal* and not part
* of our published API. It is public so we can access it reflectively across
* class loaders in secure environments.
*
* <p>This class can't depend on other Google Collections code. If we were
* to load this class in the same class loader as the rest of
* Google Collections, this thread would keep an indirect strong reference
* to the class loader and prevent it from being garbage collected. This
* poses a problem for environments where you want to throw away the class
* loader. For example, dynamically reloading a web application or unloading
* an OSGi bundle.
*
* <p>{@code com.google.common.base.FinalizableReferenceQueue} loads this class
* in its own class loader. That way, this class doesn't prevent the main
* class loader from getting garbage collected, and this class can detect when
* the main class loader has been garbage collected and stop itself.
*/
public class Finalizer implements Runnable {
private static final Logger logger
= Logger.getLogger(Finalizer.class.getName());
/** Name of FinalizableReference.class. */
private static final String FINALIZABLE_REFERENCE
= "com.google.common.base.FinalizableReference";
/**
* Starts the Finalizer thread. FinalizableReferenceQueue calls this method
* reflectively.
*
* @param finalizableReferenceClass FinalizableReference.class.
* @param queue a reference queue that the thread will poll.
* @param frqReference a phantom reference to the FinalizableReferenceQueue, which will be
* queued either when the FinalizableReferenceQueue is no longer referenced anywhere, or when
* its close() method is called.
*/
public static void startFinalizer(
Class<?> finalizableReferenceClass,
ReferenceQueue<Object> queue,
PhantomReference<Object> frqReference) {
/*
* We use FinalizableReference.class for two things:
*
* 1) To invoke FinalizableReference.finalizeReferent()
*
* 2) To detect when FinalizableReference's class loader has to be garbage
* collected, at which point, Finalizer can stop running
*/
if (!finalizableReferenceClass.getName().equals(FINALIZABLE_REFERENCE)) {
throw new IllegalArgumentException(
"Expected " + FINALIZABLE_REFERENCE + ".");
}
Finalizer finalizer = new Finalizer(finalizableReferenceClass, queue, frqReference);
Thread thread = new Thread(finalizer);
thread.setName(Finalizer.class.getName());
thread.setDaemon(true);
try {
if (inheritableThreadLocals != null) {
inheritableThreadLocals.set(thread, null);
}
} catch (Throwable t) {
logger.log(Level.INFO, "Failed to clear thread local values inherited"
+ " by reference finalizer thread.", t);
}
thread.start();
}
private final WeakReference<Class<?>> finalizableReferenceClassReference;
private final PhantomReference<Object> frqReference;
private final ReferenceQueue<Object> queue;
private static final Field inheritableThreadLocals
= getInheritableThreadLocalsField();
/** Constructs a new finalizer thread. */
private Finalizer(
Class<?> finalizableReferenceClass,
ReferenceQueue<Object> queue,
PhantomReference<Object> frqReference) {
this.queue = queue;
this.finalizableReferenceClassReference
= new WeakReference<Class<?>>(finalizableReferenceClass);
// Keep track of the FRQ that started us so we know when to stop.
this.frqReference = frqReference;
}
/**
* Loops continuously, pulling references off the queue and cleaning them up.
*/
@SuppressWarnings("InfiniteLoopStatement")
@Override
public void run() {
try {
while (true) {
try {
cleanUp(queue.remove());
} catch (InterruptedException e) { /* ignore */ }
}
} catch (ShutDown shutDown) { /* ignore */ }
}
/**
* Cleans up a single reference. Catches and logs all throwables.
*/
private void cleanUp(Reference<?> reference) throws ShutDown {
Method finalizeReferentMethod = getFinalizeReferentMethod();
do {
/*
* This is for the benefit of phantom references. Weak and soft
* references will have already been cleared by this point.
*/
reference.clear();
if (reference == frqReference) {
/*
* The client no longer has a reference to the
* FinalizableReferenceQueue. We can stop.
*/
throw new ShutDown();
}
try {
finalizeReferentMethod.invoke(reference);
} catch (Throwable t) {
logger.log(Level.SEVERE, "Error cleaning up after reference.", t);
}
/*
* Loop as long as we have references available so as not to waste
* CPU looking up the Method over and over again.
*/
} while ((reference = queue.poll()) != null);
}
/**
* Looks up FinalizableReference.finalizeReferent() method.
*/
private Method getFinalizeReferentMethod() throws ShutDown {
Class<?> finalizableReferenceClass
= finalizableReferenceClassReference.get();
if (finalizableReferenceClass == null) {
/*
* FinalizableReference's class loader was reclaimed. While there's a
* chance that other finalizable references could be enqueued
* subsequently (at which point the class loader would be resurrected
* by virtue of us having a strong reference to it), we should pretty
* much just shut down and make sure we don't keep it alive any longer
* than necessary.
*/
throw new ShutDown();
}
try {
return finalizableReferenceClass.getMethod("finalizeReferent");
} catch (NoSuchMethodException e) {
throw new AssertionError(e);
}
}
public static Field getInheritableThreadLocalsField() {
try {
Field inheritableThreadLocals
= Thread.class.getDeclaredField("inheritableThreadLocals");
inheritableThreadLocals.setAccessible(true);
return inheritableThreadLocals;
} catch (Throwable t) {
logger.log(Level.INFO, "Couldn't access Thread.inheritableThreadLocals."
+ " Reference finalizer threads will inherit thread local"
+ " values.");
return null;
}
}
/** Indicates that it's time to shut down the Finalizer. */
@SuppressWarnings("serial") // Never serialized or thrown out of this class.
private static class ShutDown extends 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.base;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
/**
* Useful suppliers.
*
* <p>All methods return serializable suppliers as long as they're given
* serializable parameters.
*
* @author Laurence Gonsalves
* @author Harry Heymann
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public final class Suppliers {
private Suppliers() {}
/**
* Returns a new supplier which is the composition of the provided function
* and supplier. In other words, the new supplier's value will be computed by
* retrieving the value from {@code supplier}, and then applying
* {@code function} to that value. Note that the resulting supplier will not
* call {@code supplier} or invoke {@code function} until it is called.
*/
public static <F, T> Supplier<T> compose(
Function<? super F, T> function, Supplier<F> supplier) {
Preconditions.checkNotNull(function);
Preconditions.checkNotNull(supplier);
return new SupplierComposition<F, T>(function, supplier);
}
private static class SupplierComposition<F, T>
implements Supplier<T>, Serializable {
final Function<? super F, T> function;
final Supplier<F> supplier;
SupplierComposition(Function<? super F, T> function, Supplier<F> supplier) {
this.function = function;
this.supplier = supplier;
}
@Override
public T get() {
return function.apply(supplier.get());
}
@Override
public String toString() {
return "Suppliers.compose(" + function + ", " + supplier + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns a supplier which caches the instance retrieved during the first
* call to {@code get()} and returns that value on subsequent calls to
* {@code get()}. See:
* <a href="http://en.wikipedia.org/wiki/Memoization">memoization</a>
*
* <p>The returned supplier is thread-safe. The supplier's serialized form
* does not contain the cached value, which will be recalculated when {@code
* get()} is called on the reserialized instance.
*
* <p>If {@code delegate} is an instance created by an earlier call to {@code
* memoize}, it is returned directly.
*/
public static <T> Supplier<T> memoize(Supplier<T> delegate) {
return (delegate instanceof MemoizingSupplier)
? delegate
: new MemoizingSupplier<T>(Preconditions.checkNotNull(delegate));
}
@VisibleForTesting
static class MemoizingSupplier<T> implements Supplier<T>, Serializable {
final Supplier<T> delegate;
transient volatile boolean initialized;
// "value" does not need to be volatile; visibility piggy-backs
// on volatile read of "initialized".
transient T value;
MemoizingSupplier(Supplier<T> delegate) {
this.delegate = delegate;
}
@Override
public T get() {
// A 2-field variant of Double Checked Locking.
if (!initialized) {
synchronized (this) {
if (!initialized) {
T t = delegate.get();
value = t;
initialized = true;
return t;
}
}
}
return value;
}
@Override
public String toString() {
return "Suppliers.memoize(" + delegate + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns a supplier that caches the instance supplied by the delegate and
* removes the cached value after the specified time has passed. Subsequent
* calls to {@code get()} return the cached value if the expiration time has
* not passed. After the expiration time, a new value is retrieved, cached,
* and returned. See:
* <a href="http://en.wikipedia.org/wiki/Memoization">memoization</a>
*
* <p>The returned supplier is thread-safe. The supplier's serialized form
* does not contain the cached value, which will be recalculated when {@code
* get()} is called on the reserialized instance.
*
* @param duration the length of time after a value is created that it
* should stop being returned by subsequent {@code get()} calls
* @param unit the unit that {@code duration} is expressed in
* @throws IllegalArgumentException if {@code duration} is not positive
* @since 2.0
*/
public static <T> Supplier<T> memoizeWithExpiration(
Supplier<T> delegate, long duration, TimeUnit unit) {
return new ExpiringMemoizingSupplier<T>(delegate, duration, unit);
}
@VisibleForTesting static class ExpiringMemoizingSupplier<T>
implements Supplier<T>, Serializable {
final Supplier<T> delegate;
final long durationNanos;
transient volatile T value;
// The special value 0 means "not yet initialized".
transient volatile long expirationNanos;
ExpiringMemoizingSupplier(
Supplier<T> delegate, long duration, TimeUnit unit) {
this.delegate = Preconditions.checkNotNull(delegate);
this.durationNanos = unit.toNanos(duration);
Preconditions.checkArgument(duration > 0);
}
@Override
public T get() {
// Another variant of Double Checked Locking.
//
// We use two volatile reads. We could reduce this to one by
// putting our fields into a holder class, but (at least on x86)
// the extra memory consumption and indirection are more
// expensive than the extra volatile reads.
long nanos = expirationNanos;
long now = Platform.systemNanoTime();
if (nanos == 0 || now - nanos >= 0) {
synchronized (this) {
if (nanos == expirationNanos) { // recheck for lost race
T t = delegate.get();
value = t;
nanos = now + durationNanos;
// In the very unlikely event that nanos is 0, set it to 1;
// no one will notice 1 ns of tardiness.
expirationNanos = (nanos == 0) ? 1 : nanos;
return t;
}
}
}
return value;
}
@Override
public String toString() {
// This is a little strange if the unit the user provided was not NANOS,
// but we don't want to store the unit just for toString
return "Suppliers.memoizeWithExpiration(" + delegate + ", " +
durationNanos + ", NANOS)";
}
private static final long serialVersionUID = 0;
}
/**
* Returns a supplier that always supplies {@code instance}.
*/
public static <T> Supplier<T> ofInstance(@Nullable T instance) {
return new SupplierOfInstance<T>(instance);
}
private static class SupplierOfInstance<T>
implements Supplier<T>, Serializable {
final T instance;
SupplierOfInstance(@Nullable T instance) {
this.instance = instance;
}
@Override
public T get() {
return instance;
}
@Override
public String toString() {
return "Suppliers.ofInstance(" + instance + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns a supplier whose {@code get()} method synchronizes on
* {@code delegate} before calling it, making it thread-safe.
*/
public static <T> Supplier<T> synchronizedSupplier(Supplier<T> delegate) {
return new ThreadSafeSupplier<T>(Preconditions.checkNotNull(delegate));
}
private static class ThreadSafeSupplier<T>
implements Supplier<T>, Serializable {
final Supplier<T> delegate;
ThreadSafeSupplier(Supplier<T> delegate) {
this.delegate = delegate;
}
@Override
public T get() {
synchronized (delegate) {
return delegate.get();
}
}
@Override
public String toString() {
return "Suppliers.synchronizedSupplier(" + delegate + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns a function that accepts a supplier and returns the result of
* invoking {@link Supplier#get} on that supplier.
*
* @since 8.0
*/
@Beta
@SuppressWarnings("unchecked") // SupplierFunction works for any T.
public static <T> Function<Supplier<T>, T> supplierFunction() {
return (Function) SupplierFunction.INSTANCE;
}
private enum SupplierFunction implements Function<Supplier<?>, Object> {
INSTANCE;
@Override
public Object apply(Supplier<?> input) {
return input.get();
}
@Override
public String toString() {
return "Suppliers.supplierFunction()";
}
}
}
| 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.base;
import com.google.common.annotations.GwtCompatible;
import javax.annotation.Nullable;
/**
* Determines a true or false value for a given input.
*
* <p>The {@link Predicates} class provides common predicates and related utilities.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the use of {@code
* Predicate}</a>.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public interface Predicate<T> {
/**
* Returns the result of applying this predicate to {@code input}. This method is <i>generally
* expected</i>, but not absolutely required, to have the following properties:
*
* <ul>
* <li>Its execution does not cause any observable side effects.
* <li>The computation is <i>consistent with equals</i>; that is, {@link Objects#equal
* Objects.equal}{@code (a, b)} implies that {@code predicate.apply(a) ==
* predicate.apply(b))}.
* </ul>
*
* @throws NullPointerException if {@code input} is null and this predicate does not accept null
* arguments
*/
boolean apply(@Nullable T input);
/**
* Indicates whether another object is equal to this predicate.
*
* <p>Most implementations will have no reason to override the behavior of {@link Object#equals}.
* However, an implementation may also choose to return {@code true} whenever {@code object} is a
* {@link Predicate} that it considers <i>interchangeable</i> with this one. "Interchangeable"
* <i>typically</i> means that {@code this.apply(t) == that.apply(t)} for all {@code t} of type
* {@code T}). Note that a {@code false} result from this method does not imply that the
* predicates are known <i>not</i> to be interchangeable.
*/
@Override
boolean equals(@Nullable Object object);
}
| 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.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.io.IOException;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
/**
* An object which joins pieces of text (specified as an array, {@link Iterable}, varargs or even a
* {@link Map}) with a separator. It either appends the results to an {@link Appendable} or returns
* them as a {@link String}. Example: <pre> {@code
*
* Joiner joiner = Joiner.on("; ").skipNulls();
* . . .
* return joiner.join("Harry", null, "Ron", "Hermione");}</pre>
*
* This returns the string {@code "Harry; Ron; Hermione"}. Note that all input elements are
* converted to strings using {@link Object#toString()} before being appended.
*
* <p>If neither {@link #skipNulls()} nor {@link #useForNull(String)} is specified, the joining
* methods will throw {@link NullPointerException} if any given element is null.
*
* <p><b>Warning: joiner instances are always immutable</b>; a configuration method such as {@code
* useForNull} has no effect on the instance it is invoked on! You must store and use the new joiner
* instance returned by the method. This makes joiners thread-safe, and safe to store as {@code
* static final} constants. <pre> {@code
*
* // Bad! Do not do this!
* Joiner joiner = Joiner.on(',');
* joiner.skipNulls(); // does nothing!
* return joiner.join("wrong", null, "wrong");}</pre>
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/StringsExplained#Joiner">{@code Joiner}</a>.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible
public class Joiner {
/**
* Returns a joiner which automatically places {@code separator} between consecutive elements.
*/
public static Joiner on(String separator) {
return new Joiner(separator);
}
/**
* Returns a joiner which automatically places {@code separator} between consecutive elements.
*/
public static Joiner on(char separator) {
return new Joiner(String.valueOf(separator));
}
private final String separator;
private Joiner(String separator) {
this.separator = checkNotNull(separator);
}
private Joiner(Joiner prototype) {
this.separator = prototype.separator;
}
/**
* <b>Deprecated.</b>
*
* @since 11.0
* @deprecated use {@link #appendTo(Appendable, Iterator)} by casting {@code parts} to
* {@code Iterator<?>}, or better yet, by implementing only {@code Iterator} and not
* {@code Iterable}. <b>This method is scheduled for deletion in June 2013.</b>
*/
@Beta
@Deprecated
public
final <A extends Appendable, I extends Object & Iterable<?> & Iterator<?>> A
appendTo(A appendable, I parts) throws IOException {
return appendTo(appendable, (Iterator<?>) parts);
}
/**
* Appends the string representation of each of {@code parts}, using the previously configured
* separator between each, to {@code appendable}.
*/
public <A extends Appendable> A appendTo(A appendable, Iterable<?> parts) throws IOException {
return appendTo(appendable, parts.iterator());
}
/**
* Appends the string representation of each of {@code parts}, using the previously configured
* separator between each, to {@code appendable}.
*
* @since 11.0
*/
public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException {
checkNotNull(appendable);
if (parts.hasNext()) {
appendable.append(toString(parts.next()));
while (parts.hasNext()) {
appendable.append(separator);
appendable.append(toString(parts.next()));
}
}
return appendable;
}
/**
* Appends the string representation of each of {@code parts}, using the previously configured
* separator between each, to {@code appendable}.
*/
public final <A extends Appendable> A appendTo(A appendable, Object[] parts) throws IOException {
return appendTo(appendable, Arrays.asList(parts));
}
/**
* Appends to {@code appendable} the string representation of each of the remaining arguments.
*/
public final <A extends Appendable> A appendTo(
A appendable, @Nullable Object first, @Nullable Object second, Object... rest)
throws IOException {
return appendTo(appendable, iterable(first, second, rest));
}
/**
* <b>Deprecated.</b>
*
* @since 11.0
* @deprecated use {@link #appendTo(StringBuilder, Iterator)} by casting {@code parts} to
* {@code Iterator<?>}, or better yet, by implementing only {@code Iterator} and not
* {@code Iterable}. <b>This method is scheduled for deletion in June 2013.</b>
*/
@Beta
@Deprecated
public
final <I extends Object & Iterable<?> & Iterator<?>> StringBuilder
appendTo(StringBuilder builder, I parts) {
return appendTo(builder, (Iterator<?>) parts);
}
/**
* Appends the string representation of each of {@code parts}, using the previously configured
* separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable,
* Iterable)}, except that it does not throw {@link IOException}.
*/
public final StringBuilder appendTo(StringBuilder builder, Iterable<?> parts) {
return appendTo(builder, parts.iterator());
}
/**
* Appends the string representation of each of {@code parts}, using the previously configured
* separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable,
* Iterable)}, except that it does not throw {@link IOException}.
*
* @since 11.0
*/
public final StringBuilder appendTo(StringBuilder builder, Iterator<?> parts) {
try {
appendTo((Appendable) builder, parts);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
return builder;
}
/**
* Appends the string representation of each of {@code parts}, using the previously configured
* separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable,
* Iterable)}, except that it does not throw {@link IOException}.
*/
public final StringBuilder appendTo(StringBuilder builder, Object[] parts) {
return appendTo(builder, Arrays.asList(parts));
}
/**
* Appends to {@code builder} the string representation of each of the remaining arguments.
* Identical to {@link #appendTo(Appendable, Object, Object, Object...)}, except that it does not
* throw {@link IOException}.
*/
public final StringBuilder appendTo(
StringBuilder builder, @Nullable Object first, @Nullable Object second, Object... rest) {
return appendTo(builder, iterable(first, second, rest));
}
/**
* <b>Deprecated.</b>
*
* @since 11.0
* @deprecated use {@link #join(Iterator)} by casting {@code parts} to
* {@code Iterator<?>}, or better yet, by implementing only {@code Iterator} and not
* {@code Iterable}. <b>This method is scheduled for deletion in June 2013.</b>
*/
@Beta
@Deprecated
public
final <I extends Object & Iterable<?> & Iterator<?>> String join(I parts) {
return join((Iterator<?>) parts);
}
/**
* Returns a string containing the string representation of each of {@code parts}, using the
* previously configured separator between each.
*/
public final String join(Iterable<?> parts) {
return join(parts.iterator());
}
/**
* Returns a string containing the string representation of each of {@code parts}, using the
* previously configured separator between each.
*
* @since 11.0
*/
public final String join(Iterator<?> parts) {
return appendTo(new StringBuilder(), parts).toString();
}
/**
* Returns a string containing the string representation of each of {@code parts}, using the
* previously configured separator between each.
*/
public final String join(Object[] parts) {
return join(Arrays.asList(parts));
}
/**
* Returns a string containing the string representation of each argument, using the previously
* configured separator between each.
*/
public final String join(@Nullable Object first, @Nullable Object second, Object... rest) {
return join(iterable(first, second, rest));
}
/**
* Returns a joiner with the same behavior as this one, except automatically substituting {@code
* nullText} for any provided null elements.
*/
@CheckReturnValue
public Joiner useForNull(final String nullText) {
checkNotNull(nullText);
return new Joiner(this) {
@Override CharSequence toString(@Nullable Object part) {
return (part == null) ? nullText : Joiner.this.toString(part);
}
@Override public Joiner useForNull(String nullText) {
checkNotNull(nullText); // weird: just to satisfy NullPointerTester.
throw new UnsupportedOperationException("already specified useForNull");
}
@Override public Joiner skipNulls() {
throw new UnsupportedOperationException("already specified useForNull");
}
};
}
/**
* Returns a joiner with the same behavior as this joiner, except automatically skipping over any
* provided null elements.
*/
@CheckReturnValue
public Joiner skipNulls() {
return new Joiner(this) {
@Override public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts)
throws IOException {
checkNotNull(appendable, "appendable");
checkNotNull(parts, "parts");
while (parts.hasNext()) {
Object part = parts.next();
if (part != null) {
appendable.append(Joiner.this.toString(part));
break;
}
}
while (parts.hasNext()) {
Object part = parts.next();
if (part != null) {
appendable.append(separator);
appendable.append(Joiner.this.toString(part));
}
}
return appendable;
}
@Override public Joiner useForNull(String nullText) {
checkNotNull(nullText); // weird: just to satisfy NullPointerTester.
throw new UnsupportedOperationException("already specified skipNulls");
}
@Override public MapJoiner withKeyValueSeparator(String kvs) {
checkNotNull(kvs); // weird: just to satisfy NullPointerTester.
throw new UnsupportedOperationException("can't use .skipNulls() with maps");
}
};
}
/**
* Returns a {@code MapJoiner} using the given key-value separator, and the same configuration as
* this {@code Joiner} otherwise.
*/
@CheckReturnValue
public MapJoiner withKeyValueSeparator(String keyValueSeparator) {
return new MapJoiner(this, keyValueSeparator);
}
/**
* An object that joins map entries in the same manner as {@code Joiner} joins iterables and
* arrays. Like {@code Joiner}, it is thread-safe and immutable.
*
* <p>In addition to operating on {@code Map} instances, {@code MapJoiner} can operate on {@code
* Multimap} entries in two distinct modes:
*
* <ul>
* <li>To output a separate entry for each key-value pair, pass {@code multimap.entries()} to a
* {@code MapJoiner} method that accepts entries as input, and receive output of the form
* {@code key1=A&key1=B&key2=C}.
* <li>To output a single entry for each key, pass {@code multimap.asMap()} to a {@code MapJoiner}
* method that accepts a map as input, and receive output of the form {@code
* key1=[A, B]&key2=C}.
* </ul>
*
* @since 2.0 (imported from Google Collections Library)
*/
public final static class MapJoiner {
private final Joiner joiner;
private final String keyValueSeparator;
private MapJoiner(Joiner joiner, String keyValueSeparator) {
this.joiner = joiner; // only "this" is ever passed, so don't checkNotNull
this.keyValueSeparator = checkNotNull(keyValueSeparator);
}
/**
* Appends the string representation of each entry of {@code map}, using the previously
* configured separator and key-value separator, to {@code appendable}.
*/
public <A extends Appendable> A appendTo(A appendable, Map<?, ?> map) throws IOException {
return appendTo(appendable, map.entrySet());
}
/**
* Appends the string representation of each entry of {@code map}, using the previously
* configured separator and key-value separator, to {@code builder}. Identical to {@link
* #appendTo(Appendable, Map)}, except that it does not throw {@link IOException}.
*/
public StringBuilder appendTo(StringBuilder builder, Map<?, ?> map) {
return appendTo(builder, map.entrySet());
}
/**
* Returns a string containing the string representation of each entry of {@code map}, using the
* previously configured separator and key-value separator.
*/
public String join(Map<?, ?> map) {
return join(map.entrySet());
}
/**
* <b>Deprecated.</b>
*
* @since 11.0
* @deprecated use {@link #appendTo(Appendable, Iterator)} by casting {@code entries} to
* {@code Iterator<? extends Entry<?, ?>>}, or better yet, by implementing only
* {@code Iterator} and not {@code Iterable}. <b>This method is scheduled for deletion
* in June 2013.</b>
*/
@Beta
@Deprecated
public
<A extends Appendable,
I extends Object & Iterable<? extends Entry<?, ?>> & Iterator<? extends Entry<?, ?>>>
A appendTo(A appendable, I entries) throws IOException {
Iterator<? extends Entry<?, ?>> iterator = entries;
return appendTo(appendable, iterator);
}
/**
* Appends the string representation of each entry in {@code entries}, using the previously
* configured separator and key-value separator, to {@code appendable}.
*
* @since 10.0
*/
@Beta
public <A extends Appendable> A appendTo(A appendable, Iterable<? extends Entry<?, ?>> entries)
throws IOException {
return appendTo(appendable, entries.iterator());
}
/**
* Appends the string representation of each entry in {@code entries}, using the previously
* configured separator and key-value separator, to {@code appendable}.
*
* @since 11.0
*/
@Beta
public <A extends Appendable> A appendTo(A appendable, Iterator<? extends Entry<?, ?>> parts)
throws IOException {
checkNotNull(appendable);
if (parts.hasNext()) {
Entry<?, ?> entry = parts.next();
appendable.append(joiner.toString(entry.getKey()));
appendable.append(keyValueSeparator);
appendable.append(joiner.toString(entry.getValue()));
while (parts.hasNext()) {
appendable.append(joiner.separator);
Entry<?, ?> e = parts.next();
appendable.append(joiner.toString(e.getKey()));
appendable.append(keyValueSeparator);
appendable.append(joiner.toString(e.getValue()));
}
}
return appendable;
}
/**
* <b>Deprecated.</b>
*
* @since 11.0
* @deprecated use {@link #appendTo(StringBuilder, Iterator)} by casting {@code entries} to
* {@code Iterator<? extends Entry<?, ?>>}, or better yet, by implementing only
* {@code Iterator} and not {@code Iterable}. <b>This method is scheduled for deletion
* in June 2013.</b>
*/
@Beta
@Deprecated
public
<I extends Object & Iterable<? extends Entry<?, ?>> & Iterator<? extends Entry<?, ?>>>
StringBuilder appendTo(StringBuilder builder, I entries) throws IOException {
Iterator<? extends Entry<?, ?>> iterator = entries;
return appendTo(builder, iterator);
}
/**
* Appends the string representation of each entry in {@code entries}, using the previously
* configured separator and key-value separator, to {@code builder}. Identical to {@link
* #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}.
*
* @since 10.0
*/
@Beta
public StringBuilder appendTo(StringBuilder builder, Iterable<? extends Entry<?, ?>> entries) {
return appendTo(builder, entries.iterator());
}
/**
* Appends the string representation of each entry in {@code entries}, using the previously
* configured separator and key-value separator, to {@code builder}. Identical to {@link
* #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}.
*
* @since 11.0
*/
@Beta
public StringBuilder appendTo(StringBuilder builder, Iterator<? extends Entry<?, ?>> entries) {
try {
appendTo((Appendable) builder, entries);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
return builder;
}
/**
* <b>Deprecated.</b>
*
* @since 11.0
* @deprecated use {@link #join(Iterator)} by casting {@code entries} to
* {@code Iterator<? extends Entry<?, ?>>}, or better yet, by implementing only
* {@code Iterator} and not {@code Iterable}. <b>This method is scheduled for deletion
* in June 2013.</b>
*/
@Beta
@Deprecated
public
<I extends Object & Iterable<? extends Entry<?, ?>> & Iterator<? extends Entry<?, ?>>>
String join(I entries) throws IOException {
Iterator<? extends Entry<?, ?>> iterator = entries;
return join(iterator);
}
/**
* Returns a string containing the string representation of each entry in {@code entries}, using
* the previously configured separator and key-value separator.
*
* @since 10.0
*/
@Beta
public String join(Iterable<? extends Entry<?, ?>> entries) {
return join(entries.iterator());
}
/**
* Returns a string containing the string representation of each entry in {@code entries}, using
* the previously configured separator and key-value separator.
*
* @since 11.0
*/
@Beta
public String join(Iterator<? extends Entry<?, ?>> entries) {
return appendTo(new StringBuilder(), entries).toString();
}
/**
* Returns a map joiner with the same behavior as this one, except automatically substituting
* {@code nullText} for any provided null keys or values.
*/
@CheckReturnValue
public MapJoiner useForNull(String nullText) {
return new MapJoiner(joiner.useForNull(nullText), keyValueSeparator);
}
}
CharSequence toString(Object part) {
checkNotNull(part); // checkNotNull for GWT (do not optimize).
return (part instanceof CharSequence) ? (CharSequence) part : part.toString();
}
private static Iterable<Object> iterable(
final Object first, final Object second, final Object[] rest) {
checkNotNull(rest);
return new AbstractList<Object>() {
@Override public int size() {
return rest.length + 2;
}
@Override public Object get(int index) {
switch (index) {
case 0:
return first;
case 1:
return second;
default:
return rest[index - 2];
}
}
};
}
}
| 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.base;
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.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@code Predicate} instances.
*
* <p>All methods returns serializable predicates as long as they're given
* serializable parameters.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the
* use of {@code Predicate}</a>.
*
* @author Kevin Bourrillion
* @since 2.0 (imported from Google Collections Library)
*/
@GwtCompatible(emulated = true)
public final class Predicates {
private Predicates() {}
// TODO(kevinb): considering having these implement a VisitablePredicate
// interface which specifies an accept(PredicateVisitor) method.
/**
* Returns a predicate that always evaluates to {@code true}.
*/
@GwtCompatible(serializable = true)
public static <T> Predicate<T> alwaysTrue() {
return ObjectPredicate.ALWAYS_TRUE.withNarrowedType();
}
/**
* Returns a predicate that always evaluates to {@code false}.
*/
@GwtCompatible(serializable = true)
public static <T> Predicate<T> alwaysFalse() {
return ObjectPredicate.ALWAYS_FALSE.withNarrowedType();
}
/**
* Returns a predicate that evaluates to {@code true} if the object reference
* being tested is null.
*/
@GwtCompatible(serializable = true)
public static <T> Predicate<T> isNull() {
return ObjectPredicate.IS_NULL.withNarrowedType();
}
/**
* Returns a predicate that evaluates to {@code true} if the object reference
* being tested is not null.
*/
@GwtCompatible(serializable = true)
public static <T> Predicate<T> notNull() {
return ObjectPredicate.NOT_NULL.withNarrowedType();
}
/**
* Returns a predicate that evaluates to {@code true} if the given predicate
* evaluates to {@code false}.
*/
public static <T> Predicate<T> not(Predicate<T> predicate) {
return new NotPredicate<T>(predicate);
}
/**
* Returns a predicate that evaluates to {@code true} if each of its
* components evaluates to {@code true}. The components are evaluated in
* order, and evaluation will be "short-circuited" as soon as a false
* predicate is found. It defensively copies the iterable passed in, so future
* changes to it won't alter the behavior of this predicate. If {@code
* components} is empty, the returned predicate will always evaluate to {@code
* true}.
*/
public static <T> Predicate<T> and(
Iterable<? extends Predicate<? super T>> components) {
return new AndPredicate<T>(defensiveCopy(components));
}
/**
* Returns a predicate that evaluates to {@code true} if each of its
* components evaluates to {@code true}. The components are evaluated in
* order, and evaluation will be "short-circuited" as soon as a false
* predicate is found. It defensively copies the array passed in, so future
* changes to it won't alter the behavior of this predicate. If {@code
* components} is empty, the returned predicate will always evaluate to {@code
* true}.
*/
public static <T> Predicate<T> and(Predicate<? super T>... components) {
return new AndPredicate<T>(defensiveCopy(components));
}
/**
* Returns a predicate that evaluates to {@code true} if both of its
* components evaluate to {@code true}. The components are evaluated in
* order, and evaluation will be "short-circuited" as soon as a false
* predicate is found.
*/
public static <T> Predicate<T> and(Predicate<? super T> first,
Predicate<? super T> second) {
return new AndPredicate<T>(Predicates.<T>asList(
checkNotNull(first), checkNotNull(second)));
}
/**
* Returns a predicate that evaluates to {@code true} if any one of its
* components evaluates to {@code true}. The components are evaluated in
* order, and evaluation will be "short-circuited" as soon as a
* true predicate is found. It defensively copies the iterable passed in, so
* future changes to it won't alter the behavior of this predicate. If {@code
* components} is empty, the returned predicate will always evaluate to {@code
* false}.
*/
public static <T> Predicate<T> or(
Iterable<? extends Predicate<? super T>> components) {
return new OrPredicate<T>(defensiveCopy(components));
}
/**
* Returns a predicate that evaluates to {@code true} if any one of its
* components evaluates to {@code true}. The components are evaluated in
* order, and evaluation will be "short-circuited" as soon as a
* true predicate is found. It defensively copies the array passed in, so
* future changes to it won't alter the behavior of this predicate. If {@code
* components} is empty, the returned predicate will always evaluate to {@code
* false}.
*/
public static <T> Predicate<T> or(Predicate<? super T>... components) {
return new OrPredicate<T>(defensiveCopy(components));
}
/**
* Returns a predicate that evaluates to {@code true} if either of its
* components evaluates to {@code true}. The components are evaluated in
* order, and evaluation will be "short-circuited" as soon as a
* true predicate is found.
*/
public static <T> Predicate<T> or(
Predicate<? super T> first, Predicate<? super T> second) {
return new OrPredicate<T>(Predicates.<T>asList(
checkNotNull(first), checkNotNull(second)));
}
/**
* Returns a predicate that evaluates to {@code true} if the object being
* tested {@code equals()} the given target or both are null.
*/
public static <T> Predicate<T> equalTo(@Nullable T target) {
return (target == null)
? Predicates.<T>isNull()
: new IsEqualToPredicate<T>(target);
}
/**
* Returns a predicate that evaluates to {@code true} if the object being
* tested is an instance of the given class. If the object being tested
* is {@code null} this predicate evaluates to {@code false}.
*
* <p>If you want to filter an {@code Iterable} to narrow its type, consider
* using {@link com.google.common.collect.Iterables#filter(Iterable, Class)}
* in preference.
*
* <p><b>Warning:</b> contrary to the typical assumptions about predicates (as
* documented at {@link Predicate#apply}), the returned predicate may not be
* <i>consistent with equals</i>. For example, {@code
* instanceOf(ArrayList.class)} will yield different results for the two equal
* instances {@code Lists.newArrayList(1)} and {@code Arrays.asList(1)}.
*/
@GwtIncompatible("Class.isInstance")
public static Predicate<Object> instanceOf(Class<?> clazz) {
return new InstanceOfPredicate(clazz);
}
/**
* Returns a predicate that evaluates to {@code true} if the class being
* tested is assignable from the given class. The returned predicate
* does not allow null inputs.
*
* @since 10.0
*/
@GwtIncompatible("Class.isAssignableFrom")
@Beta
public static Predicate<Class<?>> assignableFrom(Class<?> clazz) {
return new AssignableFromPredicate(clazz);
}
/**
* Returns a predicate that evaluates to {@code true} if the object reference
* being tested is a member of the given collection. It does not defensively
* copy the collection passed in, so future changes to it will alter the
* behavior of the predicate.
*
* <p>This method can technically accept any {@code Collection<?>}, but using
* a typed collection helps prevent bugs. This approach doesn't block any
* potential users since it is always possible to use {@code
* Predicates.<Object>in()}.
*
* @param target the collection that may contain the function input
*/
public static <T> Predicate<T> in(Collection<? extends T> target) {
return new InPredicate<T>(target);
}
/**
* Returns the composition of a function and a predicate. For every {@code x},
* the generated predicate returns {@code predicate(function(x))}.
*
* @return the composition of the provided function and predicate
*/
public static <A, B> Predicate<A> compose(
Predicate<B> predicate, Function<A, ? extends B> function) {
return new CompositionPredicate<A, B>(predicate, function);
}
/**
* Returns a predicate that evaluates to {@code true} if the
* {@code CharSequence} being tested contains any match for the given
* regular expression pattern. The test used is equivalent to
* {@code Pattern.compile(pattern).matcher(arg).find()}
*
* @throws java.util.regex.PatternSyntaxException if the pattern is invalid
* @since 3.0
*/
@GwtIncompatible(value = "java.util.regex.Pattern")
public static Predicate<CharSequence> containsPattern(String pattern) {
return new ContainsPatternPredicate(pattern);
}
/**
* Returns a predicate that evaluates to {@code true} if the
* {@code CharSequence} being tested contains any match for the given
* regular expression pattern. The test used is equivalent to
* {@code pattern.matcher(arg).find()}
*
* @since 3.0
*/
@GwtIncompatible(value = "java.util.regex.Pattern")
public static Predicate<CharSequence> contains(Pattern pattern) {
return new ContainsPatternPredicate(pattern);
}
// End public API, begin private implementation classes.
// Package private for GWT serialization.
enum ObjectPredicate implements Predicate<Object> {
ALWAYS_TRUE {
@Override public boolean apply(@Nullable Object o) {
return true;
}
},
ALWAYS_FALSE {
@Override public boolean apply(@Nullable Object o) {
return false;
}
},
IS_NULL {
@Override public boolean apply(@Nullable Object o) {
return o == null;
}
},
NOT_NULL {
@Override public boolean apply(@Nullable Object o) {
return o != null;
}
};
@SuppressWarnings("unchecked") // these Object predicates work for any T
<T> Predicate<T> withNarrowedType() {
return (Predicate<T>) this;
}
}
/** @see Predicates#not(Predicate) */
private static class NotPredicate<T> implements Predicate<T>, Serializable {
final Predicate<T> predicate;
NotPredicate(Predicate<T> predicate) {
this.predicate = checkNotNull(predicate);
}
@Override
public boolean apply(T t) {
return !predicate.apply(t);
}
@Override public int hashCode() {
return ~predicate.hashCode();
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof NotPredicate) {
NotPredicate<?> that = (NotPredicate<?>) obj;
return predicate.equals(that.predicate);
}
return false;
}
@Override public String toString() {
return "Not(" + predicate.toString() + ")";
}
private static final long serialVersionUID = 0;
}
private static final Joiner COMMA_JOINER = Joiner.on(",");
/** @see Predicates#and(Iterable) */
private static class AndPredicate<T> implements Predicate<T>, Serializable {
private final List<? extends Predicate<? super T>> components;
private AndPredicate(List<? extends Predicate<? super T>> components) {
this.components = components;
}
@Override
public boolean apply(T t) {
// Avoid using the Iterator to avoid generating garbage (issue 820).
for (int i = 0; i < components.size(); i++) {
if (!components.get(i).apply(t)) {
return false;
}
}
return true;
}
@Override public int hashCode() {
// add a random number to avoid collisions with OrPredicate
return components.hashCode() + 0x12472c2c;
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof AndPredicate) {
AndPredicate<?> that = (AndPredicate<?>) obj;
return components.equals(that.components);
}
return false;
}
@Override public String toString() {
return "And(" + COMMA_JOINER.join(components) + ")";
}
private static final long serialVersionUID = 0;
}
/** @see Predicates#or(Iterable) */
private static class OrPredicate<T> implements Predicate<T>, Serializable {
private final List<? extends Predicate<? super T>> components;
private OrPredicate(List<? extends Predicate<? super T>> components) {
this.components = components;
}
@Override
public boolean apply(T t) {
// Avoid using the Iterator to avoid generating garbage (issue 820).
for (int i = 0; i < components.size(); i++) {
if (components.get(i).apply(t)) {
return true;
}
}
return false;
}
@Override public int hashCode() {
// add a random number to avoid collisions with AndPredicate
return components.hashCode() + 0x053c91cf;
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof OrPredicate) {
OrPredicate<?> that = (OrPredicate<?>) obj;
return components.equals(that.components);
}
return false;
}
@Override public String toString() {
return "Or(" + COMMA_JOINER.join(components) + ")";
}
private static final long serialVersionUID = 0;
}
/** @see Predicates#equalTo(Object) */
private static class IsEqualToPredicate<T>
implements Predicate<T>, Serializable {
private final T target;
private IsEqualToPredicate(T target) {
this.target = target;
}
@Override
public boolean apply(T t) {
return target.equals(t);
}
@Override public int hashCode() {
return target.hashCode();
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof IsEqualToPredicate) {
IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj;
return target.equals(that.target);
}
return false;
}
@Override public String toString() {
return "IsEqualTo(" + target + ")";
}
private static final long serialVersionUID = 0;
}
/** @see Predicates#instanceOf(Class) */
@GwtIncompatible("Class.isInstance")
private static class InstanceOfPredicate
implements Predicate<Object>, Serializable {
private final Class<?> clazz;
private InstanceOfPredicate(Class<?> clazz) {
this.clazz = checkNotNull(clazz);
}
@Override
public boolean apply(@Nullable Object o) {
return clazz.isInstance(o);
}
@Override public int hashCode() {
return clazz.hashCode();
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof InstanceOfPredicate) {
InstanceOfPredicate that = (InstanceOfPredicate) obj;
return clazz == that.clazz;
}
return false;
}
@Override public String toString() {
return "IsInstanceOf(" + clazz.getName() + ")";
}
private static final long serialVersionUID = 0;
}
/** @see Predicates#assignableFrom(Class) */
@GwtIncompatible("Class.isAssignableFrom")
private static class AssignableFromPredicate
implements Predicate<Class<?>>, Serializable {
private final Class<?> clazz;
private AssignableFromPredicate(Class<?> clazz) {
this.clazz = checkNotNull(clazz);
}
@Override
public boolean apply(Class<?> input) {
return clazz.isAssignableFrom(input);
}
@Override public int hashCode() {
return clazz.hashCode();
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof AssignableFromPredicate) {
AssignableFromPredicate that = (AssignableFromPredicate) obj;
return clazz == that.clazz;
}
return false;
}
@Override public String toString() {
return "IsAssignableFrom(" + clazz.getName() + ")";
}
private static final long serialVersionUID = 0;
}
/** @see Predicates#in(Collection) */
private static class InPredicate<T> implements Predicate<T>, Serializable {
private final Collection<?> target;
private InPredicate(Collection<?> target) {
this.target = checkNotNull(target);
}
@Override
public boolean apply(T t) {
try {
return target.contains(t);
} catch (NullPointerException e) {
return false;
} catch (ClassCastException e) {
return false;
}
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof InPredicate) {
InPredicate<?> that = (InPredicate<?>) obj;
return target.equals(that.target);
}
return false;
}
@Override public int hashCode() {
return target.hashCode();
}
@Override public String toString() {
return "In(" + target + ")";
}
private static final long serialVersionUID = 0;
}
/** @see Predicates#compose(Predicate, Function) */
private static class CompositionPredicate<A, B>
implements Predicate<A>, Serializable {
final Predicate<B> p;
final Function<A, ? extends B> f;
private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) {
this.p = checkNotNull(p);
this.f = checkNotNull(f);
}
@Override
public boolean apply(A a) {
return p.apply(f.apply(a));
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof CompositionPredicate) {
CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj;
return f.equals(that.f) && p.equals(that.p);
}
return false;
}
@Override public int hashCode() {
return f.hashCode() ^ p.hashCode();
}
@Override public String toString() {
return p.toString() + "(" + f.toString() + ")";
}
private static final long serialVersionUID = 0;
}
/**
* @see Predicates#contains(Pattern)
* @see Predicates#containsPattern(String)
*/
@GwtIncompatible("Only used by other GWT-incompatible code.")
private static class ContainsPatternPredicate
implements Predicate<CharSequence>, Serializable {
final Pattern pattern;
ContainsPatternPredicate(Pattern pattern) {
this.pattern = checkNotNull(pattern);
}
ContainsPatternPredicate(String patternStr) {
this(Pattern.compile(patternStr));
}
@Override
public boolean apply(CharSequence t) {
return pattern.matcher(t).find();
}
@Override public int hashCode() {
// Pattern uses Object.hashCode, so we have to reach
// inside to build a hashCode consistent with equals.
return Objects.hashCode(pattern.pattern(), pattern.flags());
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof ContainsPatternPredicate) {
ContainsPatternPredicate that = (ContainsPatternPredicate) obj;
// Pattern uses Object (identity) equality, so we have to reach
// inside to compare individual fields.
return Objects.equal(pattern.pattern(), that.pattern.pattern())
&& Objects.equal(pattern.flags(), that.pattern.flags());
}
return false;
}
@Override public String toString() {
return Objects.toStringHelper(this)
.add("pattern", pattern)
.add("pattern.flags", Integer.toHexString(pattern.flags()))
.toString();
}
private static final long serialVersionUID = 0;
}
@SuppressWarnings("unchecked")
private static <T> List<Predicate<? super T>> asList(
Predicate<? super T> first, Predicate<? super T> second) {
return Arrays.<Predicate<? super T>>asList(first, second);
}
private static <T> List<T> defensiveCopy(T... array) {
return defensiveCopy(Arrays.asList(array));
}
static <T> List<T> defensiveCopy(Iterable<T> iterable) {
ArrayList<T> list = new ArrayList<T>();
for (T element : iterable) {
list.add(checkNotNull(element));
}
return list;
}
}
| 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.base;
import com.google.common.annotations.VisibleForTesting;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A reference queue with an associated background thread that dequeues references and invokes
* {@link FinalizableReference#finalizeReferent()} on them.
*
* <p>Keep a strong reference to this object until all of the associated referents have been
* finalized. If this object is garbage collected earlier, the backing thread will not invoke {@code
* finalizeReferent()} on the remaining references.
*
* @author Bob Lee
* @since 2.0 (imported from Google Collections Library)
*/
public class FinalizableReferenceQueue implements Closeable {
/*
* The Finalizer thread keeps a phantom reference to this object. When the client (for example, a
* map built by MapMaker) no longer has a strong reference to this object, the garbage collector
* will reclaim it and enqueue the phantom reference. The enqueued reference will trigger the
* Finalizer to stop.
*
* If this library is loaded in the system class loader, FinalizableReferenceQueue can load
* Finalizer directly with no problems.
*
* If this library is loaded in an application class loader, it's important that Finalizer not
* have a strong reference back to the class loader. Otherwise, you could have a graph like this:
*
* Finalizer Thread runs instance of -> Finalizer.class loaded by -> Application class loader
* which loaded -> ReferenceMap.class which has a static -> FinalizableReferenceQueue instance
*
* Even if no other references to classes from the application class loader remain, the Finalizer
* thread keeps an indirect strong reference to the queue in ReferenceMap, which keeps the
* Finalizer running, and as a result, the application class loader can never be reclaimed.
*
* This means that dynamically loaded web applications and OSGi bundles can't be unloaded.
*
* If the library is loaded in an application class loader, we try to break the cycle by loading
* Finalizer in its own independent class loader:
*
* System class loader -> Application class loader -> ReferenceMap -> FinalizableReferenceQueue
* -> etc. -> Decoupled class loader -> Finalizer
*
* Now, Finalizer no longer keeps an indirect strong reference to the static
* FinalizableReferenceQueue field in ReferenceMap. The application class loader can be reclaimed
* at which point the Finalizer thread will stop and its decoupled class loader can also be
* reclaimed.
*
* If any of this fails along the way, we fall back to loading Finalizer directly in the
* application class loader.
*/
private static final Logger logger = Logger.getLogger(FinalizableReferenceQueue.class.getName());
private static final String FINALIZER_CLASS_NAME = "com.google.common.base.internal.Finalizer";
/** Reference to Finalizer.startFinalizer(). */
private static final Method startFinalizer;
static {
Class<?> finalizer = loadFinalizer(
new SystemLoader(), new DecoupledLoader(), new DirectLoader());
startFinalizer = getStartFinalizer(finalizer);
}
/**
* The actual reference queue that our background thread will poll.
*/
final ReferenceQueue<Object> queue;
final PhantomReference<Object> frqRef;
/**
* Whether or not the background thread started successfully.
*/
final boolean threadStarted;
/**
* Constructs a new queue.
*/
@SuppressWarnings("unchecked")
public FinalizableReferenceQueue() {
// We could start the finalizer lazily, but I'd rather it blow up early.
queue = new ReferenceQueue<Object>();
frqRef = new PhantomReference<Object>(this, queue);
boolean threadStarted = false;
try {
startFinalizer.invoke(null, FinalizableReference.class, queue, frqRef);
threadStarted = true;
} catch (IllegalAccessException impossible) {
throw new AssertionError(impossible); // startFinalizer() is public
} catch (Throwable t) {
logger.log(Level.INFO, "Failed to start reference finalizer thread."
+ " Reference cleanup will only occur when new references are created.", t);
}
this.threadStarted = threadStarted;
}
@Override
public void close() {
frqRef.enqueue();
cleanUp();
}
/**
* Repeatedly dequeues references from the queue and invokes {@link
* FinalizableReference#finalizeReferent()} on them until the queue is empty. This method is a
* no-op if the background thread was created successfully.
*/
void cleanUp() {
if (threadStarted) {
return;
}
Reference<?> reference;
while ((reference = queue.poll()) != null) {
/*
* This is for the benefit of phantom references. Weak and soft references will have already
* been cleared by this point.
*/
reference.clear();
try {
((FinalizableReference) reference).finalizeReferent();
} catch (Throwable t) {
logger.log(Level.SEVERE, "Error cleaning up after reference.", t);
}
}
}
/**
* Iterates through the given loaders until it finds one that can load Finalizer.
*
* @return Finalizer.class
*/
private static Class<?> loadFinalizer(FinalizerLoader... loaders) {
for (FinalizerLoader loader : loaders) {
Class<?> finalizer = loader.loadFinalizer();
if (finalizer != null) {
return finalizer;
}
}
throw new AssertionError();
}
/**
* Loads Finalizer.class.
*/
interface FinalizerLoader {
/**
* Returns Finalizer.class or null if this loader shouldn't or can't load it.
*
* @throws SecurityException if we don't have the appropriate privileges
*/
Class<?> loadFinalizer();
}
/**
* Tries to load Finalizer from the system class loader. If Finalizer is in the system class path,
* we needn't create a separate loader.
*/
static class SystemLoader implements FinalizerLoader {
// This is used by the ClassLoader-leak test in FinalizableReferenceQueueTest to disable
// finding Finalizer on the system class path even if it is there.
@VisibleForTesting
static boolean disabled;
@Override
public Class<?> loadFinalizer() {
if (disabled) {
return null;
}
ClassLoader systemLoader;
try {
systemLoader = ClassLoader.getSystemClassLoader();
} catch (SecurityException e) {
logger.info("Not allowed to access system class loader.");
return null;
}
if (systemLoader != null) {
try {
return systemLoader.loadClass(FINALIZER_CLASS_NAME);
} catch (ClassNotFoundException e) {
// Ignore. Finalizer is simply in a child class loader.
return null;
}
} else {
return null;
}
}
}
/**
* Try to load Finalizer in its own class loader. If Finalizer's thread had a direct reference to
* our class loader (which could be that of a dynamically loaded web application or OSGi bundle),
* it would prevent our class loader from getting garbage collected.
*/
static class DecoupledLoader implements FinalizerLoader {
private static final String LOADING_ERROR = "Could not load Finalizer in its own class loader."
+ "Loading Finalizer in the current class loader instead. As a result, you will not be able"
+ "to garbage collect this class loader. To support reclaiming this class loader, either"
+ "resolve the underlying issue, or move Google Collections to your system class path.";
@Override
public Class<?> loadFinalizer() {
try {
/*
* We use URLClassLoader because it's the only concrete class loader implementation in the
* JDK. If we used our own ClassLoader subclass, Finalizer would indirectly reference this
* class loader:
*
* Finalizer.class -> CustomClassLoader -> CustomClassLoader.class -> This class loader
*
* System class loader will (and must) be the parent.
*/
ClassLoader finalizerLoader = newLoader(getBaseUrl());
return finalizerLoader.loadClass(FINALIZER_CLASS_NAME);
} catch (Exception e) {
logger.log(Level.WARNING, LOADING_ERROR, e);
return null;
}
}
/**
* Gets URL for base of path containing Finalizer.class.
*/
URL getBaseUrl() throws IOException {
// Find URL pointing to Finalizer.class file.
String finalizerPath = FINALIZER_CLASS_NAME.replace('.', '/') + ".class";
URL finalizerUrl = getClass().getClassLoader().getResource(finalizerPath);
if (finalizerUrl == null) {
throw new FileNotFoundException(finalizerPath);
}
// Find URL pointing to base of class path.
String urlString = finalizerUrl.toString();
if (!urlString.endsWith(finalizerPath)) {
throw new IOException("Unsupported path style: " + urlString);
}
urlString = urlString.substring(0, urlString.length() - finalizerPath.length());
return new URL(finalizerUrl, urlString);
}
/** Creates a class loader with the given base URL as its classpath. */
URLClassLoader newLoader(URL base) {
// We use the bootstrap class loader as the parent because Finalizer by design uses
// only standard Java classes. That also means that FinalizableReferenceQueueTest
// doesn't pick up the wrong version of the Finalizer class.
return new URLClassLoader(new URL[] {base}, null);
}
}
/**
* Loads Finalizer directly using the current class loader. We won't be able to garbage collect
* this class loader, but at least the world doesn't end.
*/
static class DirectLoader implements FinalizerLoader {
@Override
public Class<?> loadFinalizer() {
try {
return Class.forName(FINALIZER_CLASS_NAME);
} catch (ClassNotFoundException e) {
throw new AssertionError(e);
}
}
}
/**
* Looks up Finalizer.startFinalizer().
*/
static Method getStartFinalizer(Class<?> finalizer) {
try {
return finalizer.getMethod(
"startFinalizer",
Class.class,
ReferenceQueue.class,
PhantomReference.class);
} catch (NoSuchMethodException e) {
throw new AssertionError(e);
}
}
}
| 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.base;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.Iterator;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An immutable object that may contain a non-null reference to another object. Each
* instance of this type either contains a non-null reference, or contains nothing (in
* which case we say that the reference is "absent"); it is never said to "contain {@code
* null}".
*
* <p>A non-null {@code Optional<T>} reference can be used as a replacement for a nullable
* {@code T} reference. It allows you to represent "a {@code T} that must be present" and
* a "a {@code T} that might be absent" as two distinct types in your program, which can
* aid clarity.
*
* <p>Some uses of this class include
*
* <ul>
* <li>As a method return type, as an alternative to returning {@code null} to indicate
* that no value was available
* <li>To distinguish between "unknown" (for example, not present in a map) and "known to
* have no value" (present in the map, with value {@code Optional.absent()})
* <li>To wrap nullable references for storage in a collection that does not support
* {@code null} (though there are
* <a href="http://code.google.com/p/guava-libraries/wiki/LivingWithNullHostileCollections">
* several other approaches to this</a> that should be considered first)
* </ul>
*
* <p>A common alternative to using this class is to find or create a suitable
* <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">null object</a> for the
* type in question.
*
* <p>This class is not intended as a direct analogue of any existing "option" or "maybe"
* construct from other programming environments, though it may bear some similarities.
*
* <p>See the Guava User Guide article on <a
* href="http://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained#Optional">
* using {@code Optional}</a>.
*
* @param <T> the type of instance that can be contained. {@code Optional} is naturally
* covariant on this type, so it is safe to cast an {@code Optional<T>} to {@code
* Optional<S>} for any supertype {@code S} of {@code T}.
* @author Kurt Alfred Kluever
* @author Kevin Bourrillion
* @since 10.0
*/
@GwtCompatible(serializable = true)
public abstract class Optional<T> implements Serializable {
/**
* Returns an {@code Optional} instance with no contained reference.
*/
@SuppressWarnings("unchecked")
public static <T> Optional<T> absent() {
return (Optional<T>) Absent.INSTANCE;
}
/**
* Returns an {@code Optional} instance containing the given non-null reference.
*/
public static <T> Optional<T> of(T reference) {
return new Present<T>(checkNotNull(reference));
}
/**
* If {@code nullableReference} is non-null, returns an {@code Optional} instance containing that
* reference; otherwise returns {@link Optional#absent}.
*/
public static <T> Optional<T> fromNullable(@Nullable T nullableReference) {
return (nullableReference == null)
? Optional.<T>absent()
: new Present<T>(nullableReference);
}
Optional() {}
/**
* Returns {@code true} if this holder contains a (non-null) instance.
*/
public abstract boolean isPresent();
/**
* Returns the contained instance, which must be present. If the instance might be
* absent, use {@link #or(Object)} or {@link #orNull} instead.
*
* @throws IllegalStateException if the instance is absent ({@link #isPresent} returns
* {@code false})
*/
public abstract T get();
/**
* Returns the contained instance if it is present; {@code defaultValue} otherwise. If
* no default value should be required because the instance is known to be present, use
* {@link #get()} instead. For a default value of {@code null}, use {@link #orNull}.
*
* <p>Note about generics: The signature {@code public T or(T defaultValue)} is overly
* restrictive. However, the ideal signature, {@code public <S super T> S or(S)}, is not legal
* Java. As a result, some sensible operations involving subtypes are compile errors:
* <pre> {@code
*
* Optional<Integer> optionalInt = getSomeOptionalInt();
* Number value = optionalInt.or(0.5); // error
*
* FluentIterable<? extends Number> numbers = getSomeNumbers();
* Optional<? extends Number> first = numbers.first();
* Number value = first.or(0.5); // error}</pre>
*
* As a workaround, it is always safe to cast an {@code Optional<? extends T>} to {@code
* Optional<T>}. Casting either of the above example {@code Optional} instances to {@code
* Optional<Number>} (where {@code Number} is the desired output type) solves the problem:
* <pre> {@code
*
* Optional<Number> optionalInt = (Optional) getSomeOptionalInt();
* Number value = optionalInt.or(0.5); // fine
*
* FluentIterable<? extends Number> numbers = getSomeNumbers();
* Optional<Number> first = (Optional) numbers.first();
* Number value = first.or(0.5); // fine}</pre>
*/
public abstract T or(T defaultValue);
/**
* Returns this {@code Optional} if it has a value present; {@code secondChoice}
* otherwise.
*/
@Beta
public abstract Optional<T> or(Optional<? extends T> secondChoice);
/**
* Returns the contained instance if it is present; {@code supplier.get()} otherwise. If the
* supplier returns {@code null}, a {@link NullPointerException} is thrown.
*
* @throws NullPointerException if the supplier returns {@code null}
*/
@Beta
public abstract T or(Supplier<? extends T> supplier);
/**
* Returns the contained instance if it is present; {@code null} otherwise. If the
* instance is known to be present, use {@link #get()} instead.
*/
@Nullable
public abstract T orNull();
/**
* Returns an immutable singleton {@link Set} whose only element is the contained instance
* if it is present; an empty immutable {@link Set} otherwise.
*
* @since 11.0
*/
public abstract Set<T> asSet();
/**
* If the instance is present, it is transformed with the given {@link Function}; otherwise,
* {@link Optional#absent} is returned. If the function returns {@code null}, a
* {@link NullPointerException} is thrown.
*
* @throws NullPointerException if the function returns {@code null}
*
* @since 12.0
*/
@Beta
public abstract <V> Optional<V> transform(Function<? super T, V> function);
/**
* Returns {@code true} if {@code object} is an {@code Optional} instance, and either
* the contained references are {@linkplain Object#equals equal} to each other or both
* are absent. Note that {@code Optional} instances of differing parameterized types can
* be equal.
*/
@Override
public abstract boolean equals(@Nullable Object object);
/**
* Returns a hash code for this instance.
*/
@Override
public abstract int hashCode();
/**
* Returns a string representation for this instance. The form of this string
* representation is unspecified.
*/
@Override
public abstract String toString();
/**
* Returns the value of each present instance from the supplied {@code optionals}, in order,
* skipping over occurrences of {@link Optional#absent}. Iterators are unmodifiable and are
* evaluated lazily.
*
* @since 11.0 (generics widened in 13.0)
*/
@Beta
public static <T> Iterable<T> presentInstances(
final Iterable<? extends Optional<? extends T>> optionals) {
checkNotNull(optionals);
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new AbstractIterator<T>() {
private final Iterator<? extends Optional<? extends T>> iterator =
checkNotNull(optionals.iterator());
@Override
protected T computeNext() {
while (iterator.hasNext()) {
Optional<? extends T> optional = iterator.next();
if (optional.isPresent()) {
return optional.get();
}
}
return endOfData();
}
};
};
};
}
private static final long serialVersionUID = 0;
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.