code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * 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.util.concurrent; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Predicates.instanceOf; import static com.google.common.base.Predicates.not; import static java.util.concurrent.TimeUnit.MILLISECONDS; import com.google.common.annotations.Beta; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Stopwatch; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Ordering; import com.google.common.util.concurrent.Service.State; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.Immutable; import javax.inject.Inject; import javax.inject.Singleton; /** * A manager for monitoring and controlling a set of {@link Service services}. This class provides * methods for {@linkplain #startAsync() starting}, {@linkplain #stopAsync() stopping} and * {@linkplain #servicesByState inspecting} a collection of {@linkplain Service services}. * Additionally, users can monitor state transitions with the {@link Listener listener} mechanism. * * <p>While it is recommended that service lifecycles be managed via this class, state transitions * initiated via other mechanisms do not impact the correctness of its methods. For example, if the * services are started by some mechanism besides {@link #startAsync}, the listeners will be invoked * when appropriate and {@link #awaitHealthy} will still work as expected. * * <p>Here is a simple example of how to use a {@link ServiceManager} to start a server. * <pre> {@code * class Server { * public static void main(String[] args) { * Set<Service> services = ...; * ServiceManager manager = new ServiceManager(services); * manager.addListener(new Listener() { * public void stopped() {} * public void healthy() { * // Services have been initialized and are healthy, start accepting requests... * } * public void failure(Service service) { * // Something failed, at this point we could log it, notify a load balancer, or take * // some other action. For now we will just exit. * System.exit(1); * } * }, * MoreExecutors.sameThreadExecutor()); * * Runtime.getRuntime().addShutdownHook(new Thread() { * public void run() { * // Give the services 5 seconds to stop to ensure that we are responsive to shutdown * // requests. * try { * manager.stopAsync().awaitStopped(5, TimeUnit.SECONDS); * } catch (TimeoutException timeout) { * // stopping timed out * } * } * }); * manager.startAsync(); // start all the services asynchronously * } * }}</pre> * * <p>This class uses the ServiceManager's methods to start all of its services, to respond to * service failure and to ensure that when the JVM is shutting down all the services are stopped. * * @author Luke Sandberg * @since 14.0 */ @Beta @Singleton public final class ServiceManager { private static final Logger logger = Logger.getLogger(ServiceManager.class.getName()); /** * A listener for the aggregate state changes of the services that are under management. Users * that need to listen to more fine-grained events (such as when each particular * {@link Service service} starts, or terminates), should attach {@link Service.Listener service * listeners} to each individual service. * * @author Luke Sandberg * @since 15.0 (present as an interface in 14.0) */ @Beta // Should come out of Beta when ServiceManager does public abstract static class Listener { /** * Called when the service initially becomes healthy. * * <p>This will be called at most once after all the services have entered the * {@linkplain State#RUNNING running} state. If any services fail during start up or * {@linkplain State#FAILED fail}/{@linkplain State#TERMINATED terminate} before all other * services have started {@linkplain State#RUNNING running} then this method will not be called. */ public void healthy() {} /** * Called when the all of the component services have reached a terminal state, either * {@linkplain State#TERMINATED terminated} or {@linkplain State#FAILED failed}. */ public void stopped() {} /** * Called when a component service has {@linkplain State#FAILED failed}. * * @param service The service that failed. */ public void failure(Service service) {} } /** * An encapsulation of all of the state that is accessed by the {@linkplain ServiceListener * service listeners}. This is extracted into its own object so that {@link ServiceListener} * could be made {@code static} and its instances can be safely constructed and added in the * {@link ServiceManager} constructor without having to close over the partially constructed * {@link ServiceManager} instance (i.e. avoid leaking a pointer to {@code this}). */ private final ServiceManagerState state; private final ImmutableMap<Service, ServiceListener> services; /** * Constructs a new instance for managing the given services. * * @param services The services to manage * * @throws IllegalArgumentException if not all services are {@link State#NEW new} or if there are * any duplicate services. */ public ServiceManager(Iterable<? extends Service> services) { ImmutableList<Service> copy = ImmutableList.copyOf(services); if (copy.isEmpty()) { // Having no services causes the manager to behave strangely. Notably, listeners are never // fired. To avoid this we substitute a placeholder service. logger.log(Level.WARNING, "ServiceManager configured with no services. Is your application configured properly?", new EmptyServiceManagerWarning()); copy = ImmutableList.<Service>of(new NoOpService()); } this.state = new ServiceManagerState(copy.size()); ImmutableMap.Builder<Service, ServiceListener> builder = ImmutableMap.builder(); Executor executor = MoreExecutors.sameThreadExecutor(); for (Service service : copy) { ServiceListener listener = new ServiceListener(service, state); service.addListener(listener, executor); // We check the state after adding the listener as a way to ensure that our listener was added // to a NEW service. checkArgument(service.state() == State.NEW, "Can only manage NEW services, %s", service); builder.put(service, listener); } this.services = builder.build(); } /** * Constructs a new instance for managing the given services. This constructor is provided so that * dependency injection frameworks can inject instances of {@link ServiceManager}. * * @param services The services to manage * * @throws IllegalStateException if not all services are {@link State#NEW new}. */ @Inject ServiceManager(Set<Service> services) { this((Iterable<Service>) services); } /** * Registers a {@link Listener} to be {@linkplain Executor#execute executed} on the given * executor. The listener will not have previous state changes replayed, so it is * suggested that listeners are added before any of the managed services are * {@linkplain Service#start started}. * * <p>There is no guaranteed ordering of execution of listeners, but any listener added through * this method is guaranteed to be called whenever there is a state change. * * <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> For fast, lightweight listeners that would be safe to execute in any thread, consider * calling {@link #addListener(Listener)}. * * @param listener the listener to run when the manager changes state * @param executor the executor in which the listeners callback methods will be run. */ public void addListener(Listener listener, Executor executor) { state.addListener(listener, executor); } /** * Registers a {@link Listener} to be run when this {@link ServiceManager} changes state. The * listener will not have previous state changes replayed, so it is suggested that listeners are * added before any of the managed services are {@linkplain Service#start started}. * * <p>There is no guaranteed ordering of execution of listeners, but any listener added through * this method is guaranteed to be called whenever there is a state change. * * <p>Exceptions thrown by a listener will be will be caught and logged. * * @param listener the listener to run when the manager changes state */ public void addListener(Listener listener) { state.addListener(listener, MoreExecutors.sameThreadExecutor()); } /** * Initiates service {@linkplain Service#start startup} on all the services being managed. It is * only valid to call this method if all of the services are {@linkplain State#NEW new}. * * @return this * @throws IllegalStateException if any of the Services are not {@link State#NEW new} when the * method is called. */ public ServiceManager startAsync() { for (Map.Entry<Service, ServiceListener> entry : services.entrySet()) { Service service = entry.getKey(); State state = service.state(); checkState(state == State.NEW, "Service %s is %s, cannot start it.", service, state); } for (ServiceListener service : services.values()) { service.start(); } return this; } /** * Waits for the {@link ServiceManager} to become {@linkplain #isHealthy() healthy}. The manager * will become healthy after all the component services have reached the {@linkplain State#RUNNING * running} state. * * @throws IllegalStateException if the service manager reaches a state from which it cannot * become {@linkplain #isHealthy() healthy}. */ public void awaitHealthy() { state.awaitHealthy(); checkState(isHealthy(), "Expected to be healthy after starting"); } /** * Waits for the {@link ServiceManager} to become {@linkplain #isHealthy() healthy} for no more * than the given time. The manager will become healthy after all the component services have * reached the {@linkplain State#RUNNING running} state. * * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @throws TimeoutException if not all of the services have finished starting within the deadline * @throws IllegalStateException if the service manager reaches a state from which it cannot * become {@linkplain #isHealthy() healthy}. */ public void awaitHealthy(long timeout, TimeUnit unit) throws TimeoutException { if (!state.awaitHealthy(timeout, unit)) { // It would be nice to tell the caller who we are still waiting on, and this information is // likely to be in servicesByState(), however due to race conditions we can't actually tell // which services are holding up healthiness. The current set of NEW or STARTING services is // likely to point out the culprit, but may not. If we really wanted to solve this we could // change state to track exactly which services have started and then we could accurately // report on this. But it is only for logging so we likely don't care. throw new TimeoutException("Timeout waiting for the services to become healthy."); } checkState(isHealthy(), "Expected to be healthy after starting"); } /** * Initiates service {@linkplain Service#stop shutdown} if necessary on all the services being * managed. * * @return this */ public ServiceManager stopAsync() { for (Service service : services.keySet()) { service.stop(); } return this; } /** * Waits for the all the services to reach a terminal state. After this method returns all * services will either be {@link Service.State#TERMINATED terminated} or * {@link Service.State#FAILED failed} */ public void awaitStopped() { state.awaitStopped(); } /** * Waits for the all the services to reach a terminal state for no more than the given time. After * this method returns all services will either be {@link Service.State#TERMINATED terminated} or * {@link Service.State#FAILED failed} * * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @throws TimeoutException if not all of the services have stopped within the deadline */ public void awaitStopped(long timeout, TimeUnit unit) throws TimeoutException { if (!state.awaitStopped(timeout, unit)) { throw new TimeoutException("Timeout waiting for the services to stop."); } } /** * Returns true if all services are currently in the {@linkplain State#RUNNING running} state. * * <p>Users who want more detailed information should use the {@link #servicesByState} method to * get detailed information about which services are not running. */ public boolean isHealthy() { for (Service service : services.keySet()) { if (!service.isRunning()) { return false; } } return true; } /** * Provides a snapshot of the current state of all the services under management. * * <p>N.B. This snapshot it not guaranteed to be consistent, i.e. the set of states returned may * not correspond to any particular point in time view of the services. */ public ImmutableMultimap<State, Service> servicesByState() { ImmutableMultimap.Builder<State, Service> builder = ImmutableMultimap.builder(); for (Service service : services.keySet()) { if (!(service instanceof NoOpService)) { builder.put(service.state(), service); } } return builder.build(); } /** * Returns the service load times. This value will only return startup times for services that * have finished starting. * * @return Map of services and their corresponding startup time in millis, the map entries will be * ordered by startup time. */ public ImmutableMap<Service, Long> startupTimes() { List<Entry<Service, Long>> loadTimes = Lists.newArrayListWithCapacity(services.size()); for (Map.Entry<Service, ServiceListener> entry : services.entrySet()) { Service service = entry.getKey(); State state = service.state(); if (state != State.NEW & state != State.STARTING & !(service instanceof NoOpService)) { loadTimes.add(Maps.immutableEntry(service, entry.getValue().startupTimeMillis())); } } Collections.sort(loadTimes, Ordering.<Long>natural() .onResultOf(new Function<Entry<Service, Long>, Long>() { @Override public Long apply(Map.Entry<Service, Long> input) { return input.getValue(); } })); ImmutableMap.Builder<Service, Long> builder = ImmutableMap.builder(); for (Entry<Service, Long> entry : loadTimes) { builder.put(entry); } return builder.build(); } @Override public String toString() { return Objects.toStringHelper(ServiceManager.class) .add("services", Collections2.filter(services.keySet(), not(instanceOf(NoOpService.class)))) .toString(); } /** * An encapsulation of all the mutable state of the {@link ServiceManager} that needs to be * accessed by instances of {@link ServiceListener}. */ private static final class ServiceManagerState { final Monitor monitor = new Monitor(); final int numberOfServices; /** The number of services that have not finished starting up. */ @GuardedBy("monitor") int unstartedServices; /** The number of services that have not reached a terminal state. */ @GuardedBy("monitor") int unstoppedServices; /** * Controls how long to wait for all the service manager to either become healthy or reach a * state where it is guaranteed that it can never become healthy. */ final Monitor.Guard awaitHealthGuard = new Monitor.Guard(monitor) { @Override public boolean isSatisfied() { // All services have started or some service has terminated/failed. return unstartedServices == 0 | unstoppedServices != numberOfServices; } }; /** * Controls how long to wait for all services to reach a terminal state. */ final Monitor.Guard stoppedGuard = new Monitor.Guard(monitor) { @Override public boolean isSatisfied() { return unstoppedServices == 0; } }; /** The listeners to notify during a state transition. */ @GuardedBy("monitor") final List<ListenerExecutorPair> listeners = Lists.newArrayList(); /** * The queue of listeners that are waiting to be executed. * * <p>Enqueue operations should be protected by {@link #monitor} while dequeue operations are * not protected. Holding {@link #monitor} while enqueuing ensures that listeners in the queue * are in the correct order and {@link ExecutionQueue} ensures that they are executed in the * correct order. */ @GuardedBy("monitor") final ExecutionQueue queuedListeners = new ExecutionQueue(); ServiceManagerState(int numberOfServices) { this.numberOfServices = numberOfServices; this.unstoppedServices = numberOfServices; this.unstartedServices = numberOfServices; } void addListener(Listener listener, Executor executor) { checkNotNull(listener, "listener"); checkNotNull(executor, "executor"); monitor.enter(); try { // no point in adding a listener that will never be called if (unstartedServices > 0 || unstoppedServices > 0) { listeners.add(new ListenerExecutorPair(listener, executor)); } } finally { monitor.leave(); } } void awaitHealthy() { monitor.enterWhenUninterruptibly(awaitHealthGuard); monitor.leave(); } boolean awaitHealthy(long timeout, TimeUnit unit) { if (monitor.enterWhenUninterruptibly(awaitHealthGuard, timeout, unit)) { monitor.leave(); return true; } return false; } void awaitStopped() { monitor.enterWhenUninterruptibly(stoppedGuard); monitor.leave(); } boolean awaitStopped(long timeout, TimeUnit unit) { if (monitor.enterWhenUninterruptibly(stoppedGuard, timeout, unit)) { monitor.leave(); return true; } return false; } /** * This should be called when a service finishes starting up. * * @param currentlyHealthy whether or not the service that finished starting was healthy at the * time that it finished starting. */ @GuardedBy("monitor") private void serviceFinishedStarting(Service service, boolean currentlyHealthy) { checkState(unstartedServices > 0, "All services should have already finished starting but %s just finished.", service); unstartedServices--; if (currentlyHealthy && unstartedServices == 0 && unstoppedServices == numberOfServices) { // This means that the manager is currently healthy, or at least it should have been // healthy at some point from some perspective. Calling isHealthy is not currently // guaranteed to return true because any service could fail right now. However, the // happens-before relationship enforced by the monitor ensures that this method was called // before either serviceTerminated or serviceFailed, so we know that the manager was at // least healthy for some period of time. Furthermore we are guaranteed that this call to // healthy() will be before any call to terminated() or failure(Service) on the listener. // So it is correct to execute the listener's health() callback. for (final ListenerExecutorPair pair : listeners) { queuedListeners.add(new Runnable() { @Override public void run() { pair.listener.healthy(); } }, pair.executor); } } } /** * This should be called when a service is {@linkplain State#TERMINATED terminated}. */ @GuardedBy("monitor") private void serviceTerminated(Service service) { serviceStopped(service); } /** * This should be called when a service is {@linkplain State#FAILED failed}. */ @GuardedBy("monitor") private void serviceFailed(final Service service) { for (final ListenerExecutorPair pair : listeners) { queuedListeners.add(new Runnable() { @Override public void run() { pair.listener.failure(service); } }, pair.executor); } serviceStopped(service); } /** * Should be called whenever a service reaches a terminal state ( * {@linkplain State#TERMINATED terminated} or * {@linkplain State#FAILED failed}). */ @GuardedBy("monitor") private void serviceStopped(Service service) { checkState(unstoppedServices > 0, "All services should have already stopped but %s just stopped.", service); unstoppedServices--; if (unstoppedServices == 0) { checkState(unstartedServices == 0, "All services are stopped but %d services haven't finished starting", unstartedServices); for (final ListenerExecutorPair pair : listeners) { queuedListeners.add(new Runnable() { @Override public void run() { pair.listener.stopped(); } }, pair.executor); } // no more listeners could possibly be called, so clear them out listeners.clear(); } } /** Attempts to execute all the listeners in {@link #queuedListeners}. */ private void executeListeners() { checkState(!monitor.isOccupiedByCurrentThread(), "It is incorrect to execute listeners with the monitor held."); queuedListeners.execute(); } } /** * A {@link Service} that wraps another service and times how long it takes for it to start and * also calls the {@link ServiceManagerState#serviceFinishedStarting}, * {@link ServiceManagerState#serviceTerminated} and {@link ServiceManagerState#serviceFailed} * according to its current state. */ private static final class ServiceListener extends Service.Listener { @GuardedBy("watch") // AFAICT Stopwatch is not thread safe so we need to protect accesses final Stopwatch watch = Stopwatch.createUnstarted(); final Service service; final ServiceManagerState state; /** * @param service the service that */ ServiceListener(Service service, ServiceManagerState state) { this.service = service; this.state = state; } @Override public void starting() { // This can happen if someone besides the ServiceManager starts the service, in this case // our timings may be inaccurate. startTimer(); } @Override public void running() { state.monitor.enter(); try { finishedStarting(true); } finally { state.monitor.leave(); state.executeListeners(); } } @Override public void stopping(State from) { if (from == State.STARTING) { state.monitor.enter(); try { finishedStarting(false); } finally { state.monitor.leave(); state.executeListeners(); } } } @Override public void terminated(State from) { if (!(service instanceof NoOpService)) { logger.log(Level.FINE, "Service {0} has terminated. Previous state was: {1}", new Object[] {service, from}); } state.monitor.enter(); try { if (from == State.NEW) { // startTimer is idempotent, so this is safe to call and it may be necessary if no one has // started the timer yet. startTimer(); finishedStarting(false); } state.serviceTerminated(service); } finally { state.monitor.leave(); state.executeListeners(); } } @Override public void failed(State from, Throwable failure) { logger.log(Level.SEVERE, "Service " + service + " has failed in the " + from + " state.", failure); state.monitor.enter(); try { if (from == State.STARTING) { finishedStarting(false); } state.serviceFailed(service); } finally { state.monitor.leave(); state.executeListeners(); } } /** * Stop the stopwatch, log the startup time and decrement the startup latch * * @param currentlyHealthy whether or not the service that finished starting is currently * healthy */ @GuardedBy("monitor") void finishedStarting(boolean currentlyHealthy) { synchronized (watch) { watch.stop(); if (!(service instanceof NoOpService)) { logger.log(Level.FINE, "Started {0} in {1} ms.", new Object[] {service, startupTimeMillis()}); } } state.serviceFinishedStarting(service, currentlyHealthy); } void start() { startTimer(); service.start(); } /** Start the timer if it hasn't been started. */ void startTimer() { synchronized (watch) { if (!watch.isRunning()) { // only start the watch once. watch.start(); if (!(service instanceof NoOpService)) { logger.log(Level.FINE, "Starting {0}.", service); } } } } /** Returns the amount of time it took for the service to finish starting in milliseconds. */ long startupTimeMillis() { synchronized (watch) { return watch.elapsed(MILLISECONDS); } } } /** Simple value object binding a listener to its executor. */ @Immutable private static final class ListenerExecutorPair { final Listener listener; final Executor executor; ListenerExecutorPair(Listener listener, Executor executor) { this.listener = listener; this.executor = executor; } } /** * A {@link Service} instance that does nothing. This is only useful as a placeholder to * ensure that the {@link ServiceManager} functions properly even when it is managing no services. * * <p>The use of this class is considered an implementation detail of the class and as such it is * excluded from {@link #servicesByState}, {@link #startupTimes}, {@link #toString} and all * logging statements. */ private static final class NoOpService extends AbstractService { @Override protected void doStart() { notifyStarted(); } @Override protected void doStop() { notifyStopped(); } } /** This is never thrown but only used for logging. */ private static final class EmptyServiceManagerWarning extends Throwable {} }
Java
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor; import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly; import static java.lang.Thread.currentThread; import static java.util.Arrays.asList; import com.google.common.annotations.Beta; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.UndeclaredThrowableException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; /** * Static utility methods pertaining to the {@link Future} interface. * * <p>Many of these methods use the {@link ListenableFuture} API; consult the * Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained"> * {@code ListenableFuture}</a>. * * @author Kevin Bourrillion * @author Nishant Thakkar * @author Sven Mawson * @since 1.0 */ @Beta public final class Futures { private Futures() {} /** * Creates a {@link CheckedFuture} out of a normal {@link ListenableFuture} * and a {@link Function} that maps from {@link Exception} instances into the * appropriate checked type. * * <p>The given mapping function will be applied to an * {@link InterruptedException}, a {@link CancellationException}, or an * {@link ExecutionException}. * See {@link Future#get()} for details on the exceptions thrown. * * @since 9.0 (source-compatible since 1.0) */ public static <V, X extends Exception> CheckedFuture<V, X> makeChecked( ListenableFuture<V> future, Function<Exception, X> mapper) { return new MappingCheckedFuture<V, X>(checkNotNull(future), mapper); } private abstract static class ImmediateFuture<V> implements ListenableFuture<V> { private static final Logger log = Logger.getLogger(ImmediateFuture.class.getName()); @Override public void addListener(Runnable listener, Executor executor) { checkNotNull(listener, "Runnable was null."); checkNotNull(executor, "Executor was null."); try { executor.execute(listener); } catch (RuntimeException e) { // ListenableFuture's contract is that it will not throw unchecked // exceptions, so log the bad runnable and/or executor and swallow it. log.log(Level.SEVERE, "RuntimeException while executing runnable " + listener + " with executor " + executor, e); } } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public abstract V get() throws ExecutionException; @Override public V get(long timeout, TimeUnit unit) throws ExecutionException { checkNotNull(unit); return get(); } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } } private static class ImmediateSuccessfulFuture<V> extends ImmediateFuture<V> { @Nullable private final V value; ImmediateSuccessfulFuture(@Nullable V value) { this.value = value; } @Override public V get() { return value; } } private static class ImmediateSuccessfulCheckedFuture<V, X extends Exception> extends ImmediateFuture<V> implements CheckedFuture<V, X> { @Nullable private final V value; ImmediateSuccessfulCheckedFuture(@Nullable V value) { this.value = value; } @Override public V get() { return value; } @Override public V checkedGet() { return value; } @Override public V checkedGet(long timeout, TimeUnit unit) { checkNotNull(unit); return value; } } private static class ImmediateFailedFuture<V> extends ImmediateFuture<V> { private final Throwable thrown; ImmediateFailedFuture(Throwable thrown) { this.thrown = thrown; } @Override public V get() throws ExecutionException { throw new ExecutionException(thrown); } } private static class ImmediateCancelledFuture<V> extends ImmediateFuture<V> { private final CancellationException thrown; ImmediateCancelledFuture() { this.thrown = new CancellationException("Immediate cancelled future."); } @Override public boolean isCancelled() { return true; } @Override public V get() { throw AbstractFuture.cancellationExceptionWithCause( "Task was cancelled.", thrown); } } private static class ImmediateFailedCheckedFuture<V, X extends Exception> extends ImmediateFuture<V> implements CheckedFuture<V, X> { private final X thrown; ImmediateFailedCheckedFuture(X thrown) { this.thrown = thrown; } @Override public V get() throws ExecutionException { throw new ExecutionException(thrown); } @Override public V checkedGet() throws X { throw thrown; } @Override public V checkedGet(long timeout, TimeUnit unit) throws X { checkNotNull(unit); throw thrown; } } /** * Creates a {@code ListenableFuture} which has its value set immediately upon * construction. The getters just return the value. This {@code Future} can't * be canceled or timed out and its {@code isDone()} method always returns * {@code true}. */ public static <V> ListenableFuture<V> immediateFuture(@Nullable V value) { return new ImmediateSuccessfulFuture<V>(value); } /** * Returns a {@code CheckedFuture} which has its value set immediately upon * construction. * * <p>The returned {@code Future} can't be cancelled, and its {@code isDone()} * method always returns {@code true}. Calling {@code get()} or {@code * checkedGet()} will immediately return the provided value. */ public static <V, X extends Exception> CheckedFuture<V, X> immediateCheckedFuture(@Nullable V value) { return new ImmediateSuccessfulCheckedFuture<V, X>(value); } /** * Returns a {@code ListenableFuture} which has an exception set immediately * upon construction. * * <p>The returned {@code Future} can't be cancelled, and its {@code isDone()} * method always returns {@code true}. Calling {@code get()} will immediately * throw the provided {@code Throwable} wrapped in an {@code * ExecutionException}. */ public static <V> ListenableFuture<V> immediateFailedFuture( Throwable throwable) { checkNotNull(throwable); return new ImmediateFailedFuture<V>(throwable); } /** * Creates a {@code ListenableFuture} which is cancelled immediately upon * construction, so that {@code isCancelled()} always returns {@code true}. * * @since 14.0 */ public static <V> ListenableFuture<V> immediateCancelledFuture() { return new ImmediateCancelledFuture<V>(); } /** * Returns a {@code CheckedFuture} which has an exception set immediately upon * construction. * * <p>The returned {@code Future} can't be cancelled, and its {@code isDone()} * method always returns {@code true}. Calling {@code get()} will immediately * throw the provided {@code Exception} wrapped in an {@code * ExecutionException}, and calling {@code checkedGet()} will throw the * provided exception itself. */ public static <V, X extends Exception> CheckedFuture<V, X> immediateFailedCheckedFuture(X exception) { checkNotNull(exception); return new ImmediateFailedCheckedFuture<V, X>(exception); } /** * Returns a {@code Future} whose result is taken from the given primary * {@code input} or, if the primary input fails, from the {@code Future} * provided by the {@code fallback}. {@link FutureFallback#create} is not * invoked until the primary input has failed, so if the primary input * succeeds, it is never invoked. If, during the invocation of {@code * fallback}, an exception is thrown, this exception is used as the result of * the output {@code Future}. * * <p>Below is an example of a fallback that returns a default value if an * exception occurs: * * <pre> {@code * ListenableFuture<Integer> fetchCounterFuture = ...; * * // Falling back to a zero counter in case an exception happens when * // processing the RPC to fetch counters. * ListenableFuture<Integer> faultTolerantFuture = Futures.withFallback( * fetchCounterFuture, new FutureFallback<Integer>() { * public ListenableFuture<Integer> create(Throwable t) { * // Returning "0" as the default for the counter when the * // exception happens. * return immediateFuture(0); * } * });}</pre> * * <p>The fallback can also choose to propagate the original exception when * desired: * * <pre> {@code * ListenableFuture<Integer> fetchCounterFuture = ...; * * // Falling back to a zero counter only in case the exception was a * // TimeoutException. * ListenableFuture<Integer> faultTolerantFuture = Futures.withFallback( * fetchCounterFuture, new FutureFallback<Integer>() { * public ListenableFuture<Integer> create(Throwable t) { * if (t instanceof TimeoutException) { * return immediateFuture(0); * } * return immediateFailedFuture(t); * } * });}</pre> * * <p>Note: If the derived {@code Future} is slow or heavyweight to create * (whether the {@code Future} itself is slow or heavyweight to complete is * irrelevant), consider {@linkplain #withFallback(ListenableFuture, * FutureFallback, Executor) supplying an executor}. If you do not supply an * executor, {@code withFallback} will use {@link * MoreExecutors#sameThreadExecutor sameThreadExecutor}, which carries some * caveats for heavier operations. For example, the call to {@code * fallback.create} may run on an unpredictable or undesirable thread: * * <ul> * <li>If the input {@code Future} is done at the time {@code withFallback} * is called, {@code withFallback} will call {@code fallback.create} inline. * <li>If the input {@code Future} is not yet done, {@code withFallback} will * schedule {@code fallback.create} 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> * * <p>Also note that, regardless of which thread executes the {@code * sameThreadExecutor} {@code fallback.create}, all other registered but * unexecuted listeners are prevented from running during its execution, even * if those listeners are to run in other executors. * * @param input the primary input {@code Future} * @param fallback the {@link FutureFallback} implementation to be called if * {@code input} fails * @since 14.0 */ public static <V> ListenableFuture<V> withFallback( ListenableFuture<? extends V> input, FutureFallback<? extends V> fallback) { return withFallback(input, fallback, sameThreadExecutor()); } /** * Returns a {@code Future} whose result is taken from the given primary * {@code input} or, if the primary input fails, from the {@code Future} * provided by the {@code fallback}. {@link FutureFallback#create} is not * invoked until the primary input has failed, so if the primary input * succeeds, it is never invoked. If, during the invocation of {@code * fallback}, an exception is thrown, this exception is used as the result of * the output {@code Future}. * * <p>Below is an example of a fallback that returns a default value if an * exception occurs: * * <pre> {@code * ListenableFuture<Integer> fetchCounterFuture = ...; * * // Falling back to a zero counter in case an exception happens when * // processing the RPC to fetch counters. * ListenableFuture<Integer> faultTolerantFuture = Futures.withFallback( * fetchCounterFuture, new FutureFallback<Integer>() { * public ListenableFuture<Integer> create(Throwable t) { * // Returning "0" as the default for the counter when the * // exception happens. * return immediateFuture(0); * } * }, sameThreadExecutor());}</pre> * * <p>The fallback can also choose to propagate the original exception when * desired: * * <pre> {@code * ListenableFuture<Integer> fetchCounterFuture = ...; * * // Falling back to a zero counter only in case the exception was a * // TimeoutException. * ListenableFuture<Integer> faultTolerantFuture = Futures.withFallback( * fetchCounterFuture, new FutureFallback<Integer>() { * public ListenableFuture<Integer> create(Throwable t) { * if (t instanceof TimeoutException) { * return immediateFuture(0); * } * return immediateFailedFuture(t); * } * }, sameThreadExecutor());}</pre> * * <p>When the execution of {@code fallback.create} is fast and lightweight * (though the {@code Future} it returns need not meet these criteria), * consider {@linkplain #withFallback(ListenableFuture, FutureFallback) * omitting the executor} or explicitly specifying {@code * sameThreadExecutor}. However, be aware of the caveats documented in the * link above. * * @param input the primary input {@code Future} * @param fallback the {@link FutureFallback} implementation to be called if * {@code input} fails * @param executor the executor that runs {@code fallback} if {@code input} * fails * @since 14.0 */ public static <V> ListenableFuture<V> withFallback( ListenableFuture<? extends V> input, FutureFallback<? extends V> fallback, Executor executor) { checkNotNull(fallback); return new FallbackFuture<V>(input, fallback, executor); } /** * A future that falls back on a second, generated future, in case its * original future fails. */ private static class FallbackFuture<V> extends AbstractFuture<V> { private volatile ListenableFuture<? extends V> running; FallbackFuture(ListenableFuture<? extends V> input, final FutureFallback<? extends V> fallback, final Executor executor) { running = input; addCallback(running, new FutureCallback<V>() { @Override public void onSuccess(V value) { set(value); } @Override public void onFailure(Throwable t) { if (isCancelled()) { return; } try { running = fallback.create(t); if (isCancelled()) { // in case cancel called in the meantime running.cancel(wasInterrupted()); return; } addCallback(running, new FutureCallback<V>() { @Override public void onSuccess(V value) { set(value); } @Override public void onFailure(Throwable t) { if (running.isCancelled()) { cancel(false); } else { setException(t); } } }, sameThreadExecutor()); } catch (Throwable e) { setException(e); } } }, executor); } @Override public boolean cancel(boolean mayInterruptIfRunning) { if (super.cancel(mayInterruptIfRunning)) { running.cancel(mayInterruptIfRunning); return true; } return false; } } /** * Returns a new {@code ListenableFuture} whose result is asynchronously * derived from the result of the given {@code Future}. More precisely, the * returned {@code Future} takes its result from a {@code Future} produced by * applying the given {@code AsyncFunction} to the result of the original * {@code Future}. Example: * * <pre> {@code * ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query); * AsyncFunction<RowKey, QueryResult> queryFunction = * new AsyncFunction<RowKey, QueryResult>() { * public ListenableFuture<QueryResult> apply(RowKey rowKey) { * return dataService.read(rowKey); * } * }; * ListenableFuture<QueryResult> queryFuture = * transform(rowKeyFuture, queryFunction);}</pre> * * <p>Note: If the derived {@code Future} is slow or heavyweight to create * (whether the {@code Future} itself is slow or heavyweight to complete is * irrelevant), consider {@linkplain #transform(ListenableFuture, * AsyncFunction, Executor) supplying an executor}. If you do not supply an * executor, {@code transform} will use {@link * MoreExecutors#sameThreadExecutor sameThreadExecutor}, which carries some * caveats for heavier operations. For example, the call to {@code * function.apply} may run on an unpredictable or undesirable thread: * * <ul> * <li>If the input {@code Future} is done at the time {@code transform} is * called, {@code transform} will call {@code function.apply} inline. * <li>If the input {@code Future} is not yet done, {@code transform} will * schedule {@code function.apply} 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> * * <p>Also note that, regardless of which thread executes the {@code * sameThreadExecutor} {@code function.apply}, all other registered but * unexecuted listeners are prevented from running during its execution, even * if those listeners are to run in other executors. * * <p>The returned {@code Future} attempts to keep its cancellation state in * sync with that of the input future and that of the future returned by the * function. That is, if the returned {@code Future} is cancelled, it will * attempt to cancel the other two, and if either of the other two is * cancelled, the returned {@code Future} will receive a callback in which it * will attempt to cancel itself. * * @param input The future to transform * @param function A function to transform the result of the input future * to the result of the output future * @return A future that holds result of the function (if the input succeeded) * or the original input's failure (if not) * @since 11.0 */ public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input, AsyncFunction<? super I, ? extends O> function) { return transform(input, function, MoreExecutors.sameThreadExecutor()); } /** * Returns a new {@code ListenableFuture} whose result is asynchronously * derived from the result of the given {@code Future}. More precisely, the * returned {@code Future} takes its result from a {@code Future} produced by * applying the given {@code AsyncFunction} to the result of the original * {@code Future}. Example: * * <pre> {@code * ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query); * AsyncFunction<RowKey, QueryResult> queryFunction = * new AsyncFunction<RowKey, QueryResult>() { * public ListenableFuture<QueryResult> apply(RowKey rowKey) { * return dataService.read(rowKey); * } * }; * ListenableFuture<QueryResult> queryFuture = * transform(rowKeyFuture, queryFunction, executor);}</pre> * * <p>The returned {@code Future} attempts to keep its cancellation state in * sync with that of the input future and that of the future returned by the * chain function. That is, if the returned {@code Future} is cancelled, it * will attempt to cancel the other two, and if either of the other two is * cancelled, the returned {@code Future} will receive a callback in which it * will attempt to cancel itself. * * <p>When the execution of {@code function.apply} is fast and lightweight * (though the {@code Future} it returns need not meet these criteria), * consider {@linkplain #transform(ListenableFuture, AsyncFunction) omitting * the executor} or explicitly specifying {@code sameThreadExecutor}. * However, be aware of the caveats documented in the link above. * * @param input The future to transform * @param function A function to transform the result of the input future * to the result of the output future * @param executor Executor to run the function in. * @return A future that holds result of the function (if the input succeeded) * or the original input's failure (if not) * @since 11.0 */ public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input, AsyncFunction<? super I, ? extends O> function, Executor executor) { ChainingListenableFuture<I, O> output = new ChainingListenableFuture<I, O>(function, input); input.addListener(output, executor); return output; } /** * Returns a new {@code ListenableFuture} whose result is the product of * applying the given {@code Function} to the result of the given {@code * Future}. Example: * * <pre> {@code * ListenableFuture<QueryResult> queryFuture = ...; * Function<QueryResult, List<Row>> rowsFunction = * new Function<QueryResult, List<Row>>() { * public List<Row> apply(QueryResult queryResult) { * return queryResult.getRows(); * } * }; * ListenableFuture<List<Row>> rowsFuture = * transform(queryFuture, rowsFunction);}</pre> * * <p>Note: If the transformation is slow or heavyweight, consider {@linkplain * #transform(ListenableFuture, Function, Executor) supplying an executor}. * If you do not supply an executor, {@code transform} will use {@link * MoreExecutors#sameThreadExecutor sameThreadExecutor}, which carries some * caveats for heavier operations. For example, the call to {@code * function.apply} may run on an unpredictable or undesirable thread: * * <ul> * <li>If the input {@code Future} is done at the time {@code transform} is * called, {@code transform} will call {@code function.apply} inline. * <li>If the input {@code Future} is not yet done, {@code transform} will * schedule {@code function.apply} 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> * * <p>Also note that, regardless of which thread executes the {@code * sameThreadExecutor} {@code function.apply}, all other registered but * unexecuted listeners are prevented from running during its execution, even * if those listeners are to run in other executors. * * <p>The returned {@code Future} attempts to keep its cancellation state in * sync with that of the input future. That is, if the returned {@code Future} * is cancelled, it will attempt to cancel the input, and if the input is * cancelled, the returned {@code Future} will receive a callback in which it * will attempt to cancel itself. * * <p>An example use of this method is to convert a serializable object * returned from an RPC into a POJO. * * @param input The future to transform * @param function A Function to transform the results of the provided future * to the results of the returned future. This will be run in the thread * that notifies input it is complete. * @return A future that holds result of the transformation. * @since 9.0 (in 1.0 as {@code compose}) */ public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input, final Function<? super I, ? extends O> function) { return transform(input, function, MoreExecutors.sameThreadExecutor()); } /** * Returns a new {@code ListenableFuture} whose result is the product of * applying the given {@code Function} to the result of the given {@code * Future}. Example: * * <pre> {@code * ListenableFuture<QueryResult> queryFuture = ...; * Function<QueryResult, List<Row>> rowsFunction = * new Function<QueryResult, List<Row>>() { * public List<Row> apply(QueryResult queryResult) { * return queryResult.getRows(); * } * }; * ListenableFuture<List<Row>> rowsFuture = * transform(queryFuture, rowsFunction, executor);}</pre> * * <p>The returned {@code Future} attempts to keep its cancellation state in * sync with that of the input future. That is, if the returned {@code Future} * is cancelled, it will attempt to cancel the input, and if the input is * cancelled, the returned {@code Future} will receive a callback in which it * will attempt to cancel itself. * * <p>An example use of this method is to convert a serializable object * returned from an RPC into a POJO. * * <p>When the transformation is fast and lightweight, consider {@linkplain * #transform(ListenableFuture, Function) omitting the executor} or * explicitly specifying {@code sameThreadExecutor}. However, be aware of the * caveats documented in the link above. * * @param input The future to transform * @param function A Function to transform the results of the provided future * to the results of the returned future. * @param executor Executor to run the function in. * @return A future that holds result of the transformation. * @since 9.0 (in 2.0 as {@code compose}) */ public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input, final Function<? super I, ? extends O> function, Executor executor) { checkNotNull(function); AsyncFunction<I, O> wrapperFunction = new AsyncFunction<I, O>() { @Override public ListenableFuture<O> apply(I input) { O output = function.apply(input); return immediateFuture(output); } }; return transform(input, wrapperFunction, executor); } /** * Like {@link #transform(ListenableFuture, Function)} except that the * transformation {@code function} is invoked on each call to * {@link Future#get() get()} on the returned future. * * <p>The returned {@code Future} reflects the input's cancellation * state directly, and any attempt to cancel the returned Future is likewise * passed through to the input Future. * * <p>Note that calls to {@linkplain Future#get(long, TimeUnit) timed get} * only apply the timeout to the execution of the underlying {@code Future}, * <em>not</em> to the execution of the transformation function. * * <p>The primary audience of this method is callers of {@code transform} * who don't have a {@code ListenableFuture} available and * do not mind repeated, lazy function evaluation. * * @param input The future to transform * @param function A Function to transform the results of the provided future * to the results of the returned future. * @return A future that returns the result of the transformation. * @since 10.0 */ public static <I, O> Future<O> lazyTransform(final Future<I> input, final Function<? super I, ? extends O> function) { checkNotNull(input); checkNotNull(function); return new Future<O>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return input.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return input.isCancelled(); } @Override public boolean isDone() { return input.isDone(); } @Override public O get() throws InterruptedException, ExecutionException { return applyTransformation(input.get()); } @Override public O get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return applyTransformation(input.get(timeout, unit)); } private O applyTransformation(I input) throws ExecutionException { try { return function.apply(input); } catch (Throwable t) { throw new ExecutionException(t); } } }; } /** * An implementation of {@code ListenableFuture} that also implements * {@code Runnable} so that it can be used to nest ListenableFutures. * Once the passed-in {@code ListenableFuture} is complete, it calls the * passed-in {@code Function} to generate the result. * * <p>If the function throws any checked exceptions, they should be wrapped * in a {@code UndeclaredThrowableException} so that this class can get * access to the cause. */ private static class ChainingListenableFuture<I, O> extends AbstractFuture<O> implements Runnable { private AsyncFunction<? super I, ? extends O> function; private ListenableFuture<? extends I> inputFuture; private volatile ListenableFuture<? extends O> outputFuture; private final CountDownLatch outputCreated = new CountDownLatch(1); private ChainingListenableFuture( AsyncFunction<? super I, ? extends O> function, ListenableFuture<? extends I> inputFuture) { this.function = checkNotNull(function); this.inputFuture = checkNotNull(inputFuture); } @Override public boolean cancel(boolean mayInterruptIfRunning) { /* * Our additional cancellation work needs to occur even if * !mayInterruptIfRunning, so we can't move it into interruptTask(). */ if (super.cancel(mayInterruptIfRunning)) { // This should never block since only one thread is allowed to cancel // this Future. cancel(inputFuture, mayInterruptIfRunning); cancel(outputFuture, mayInterruptIfRunning); return true; } return false; } private void cancel(@Nullable Future<?> future, boolean mayInterruptIfRunning) { if (future != null) { future.cancel(mayInterruptIfRunning); } } @Override public void run() { try { I sourceResult; try { sourceResult = getUninterruptibly(inputFuture); } catch (CancellationException e) { // Cancel this future and return. // At this point, inputFuture is cancelled and outputFuture doesn't // exist, so the value of mayInterruptIfRunning is irrelevant. cancel(false); return; } catch (ExecutionException e) { // Set the cause of the exception as this future's exception setException(e.getCause()); return; } final ListenableFuture<? extends O> outputFuture = this.outputFuture = function.apply(sourceResult); if (isCancelled()) { outputFuture.cancel(wasInterrupted()); this.outputFuture = null; return; } outputFuture.addListener(new Runnable() { @Override public void run() { try { set(getUninterruptibly(outputFuture)); } catch (CancellationException e) { // Cancel this future and return. // At this point, inputFuture and outputFuture are done, so the // value of mayInterruptIfRunning is irrelevant. cancel(false); return; } catch (ExecutionException e) { // Set the cause of the exception as this future's exception setException(e.getCause()); } finally { // Don't pin inputs beyond completion ChainingListenableFuture.this.outputFuture = null; } } }, MoreExecutors.sameThreadExecutor()); } catch (UndeclaredThrowableException e) { // Set the cause of the exception as this future's exception setException(e.getCause()); } catch (Throwable t) { // This exception is irrelevant in this thread, but useful for the // client setException(t); } finally { // Don't pin inputs beyond completion function = null; inputFuture = null; // Allow our get routines to examine outputFuture now. outputCreated.countDown(); } } } /** * Returns a new {@code ListenableFuture} whose result is the product of * calling {@code get()} on the {@code Future} nested within the given {@code * Future}, effectively chaining the futures one after the other. Example: * * <pre> {@code * SettableFuture<ListenableFuture<String>> nested = SettableFuture.create(); * ListenableFuture<String> dereferenced = dereference(nested);}</pre> * * <p>This call has the same cancellation and execution semantics as {@link * #transform(ListenableFuture, AsyncFunction)}, in that the returned {@code * Future} attempts to keep its cancellation state in sync with both the * input {@code Future} and the nested {@code Future}. The transformation * is very lightweight and therefore takes place in the thread that called * {@code dereference}. * * @param nested The nested future to transform. * @return A future that holds result of the inner future. * @since 13.0 */ @SuppressWarnings({"rawtypes", "unchecked"}) public static <V> ListenableFuture<V> dereference( ListenableFuture<? extends ListenableFuture<? extends V>> nested) { return Futures.transform((ListenableFuture) nested, (AsyncFunction) DEREFERENCER); } /** * Helper {@code Function} for {@link #dereference}. */ private static final AsyncFunction<ListenableFuture<Object>, Object> DEREFERENCER = new AsyncFunction<ListenableFuture<Object>, Object>() { @Override public ListenableFuture<Object> apply(ListenableFuture<Object> input) { return input; } }; /** * Creates a new {@code ListenableFuture} whose value is a list containing the * values of all its input futures, if all succeed. If any input fails, the * returned future fails. * * <p>The list of results is in the same order as the input list. * * <p>Canceling this future will attempt to cancel all the component futures, * and if any of the provided futures fails or is canceled, this one is, * too. * * @param futures futures to combine * @return a future that provides a list of the results of the component * futures * @since 10.0 */ public static <V> ListenableFuture<List<V>> allAsList( ListenableFuture<? extends V>... futures) { return listFuture(ImmutableList.copyOf(futures), true, MoreExecutors.sameThreadExecutor()); } /** * Creates a new {@code ListenableFuture} whose value is a list containing the * values of all its input futures, if all succeed. If any input fails, the * returned future fails. * * <p>The list of results is in the same order as the input list. * * <p>Canceling this future will attempt to cancel all the component futures, * and if any of the provided futures fails or is canceled, this one is, * too. * * @param futures futures to combine * @return a future that provides a list of the results of the component * futures * @since 10.0 */ public static <V> ListenableFuture<List<V>> allAsList( Iterable<? extends ListenableFuture<? extends V>> futures) { return listFuture(ImmutableList.copyOf(futures), true, MoreExecutors.sameThreadExecutor()); } /** * Creates a new {@code ListenableFuture} whose result is set from the * supplied future when it completes. Cancelling the supplied future * will also cancel the returned future, but cancelling the returned * future will have no effect on the supplied future. * * @since 15.0 */ public static <V> ListenableFuture<V> nonCancellationPropagating( ListenableFuture<V> future) { return new NonCancellationPropagatingFuture<V>(future); } /** * A wrapped future that does not propagate cancellation to its delegate. */ private static class NonCancellationPropagatingFuture<V> extends AbstractFuture<V> { NonCancellationPropagatingFuture(final ListenableFuture<V> delegate) { checkNotNull(delegate); addCallback(delegate, new FutureCallback<V>() { @Override public void onSuccess(V result) { set(result); } @Override public void onFailure(Throwable t) { if (delegate.isCancelled()) { cancel(false); } else { setException(t); } } }, sameThreadExecutor()); } } /** * Creates a new {@code ListenableFuture} whose value is a list containing the * values of all its successful input futures. The list of results is in the * same order as the input list, and if any of the provided futures fails or * is canceled, its corresponding position will contain {@code null} (which is * indistinguishable from the future having a successful value of * {@code null}). * * <p>Canceling this future will attempt to cancel all the component futures. * * @param futures futures to combine * @return a future that provides a list of the results of the component * futures * @since 10.0 */ public static <V> ListenableFuture<List<V>> successfulAsList( ListenableFuture<? extends V>... futures) { return listFuture(ImmutableList.copyOf(futures), false, MoreExecutors.sameThreadExecutor()); } /** * Creates a new {@code ListenableFuture} whose value is a list containing the * values of all its successful input futures. The list of results is in the * same order as the input list, and if any of the provided futures fails or * is canceled, its corresponding position will contain {@code null} (which is * indistinguishable from the future having a successful value of * {@code null}). * * <p>Canceling this future will attempt to cancel all the component futures. * * @param futures futures to combine * @return a future that provides a list of the results of the component * futures * @since 10.0 */ public static <V> ListenableFuture<List<V>> successfulAsList( Iterable<? extends ListenableFuture<? extends V>> futures) { return listFuture(ImmutableList.copyOf(futures), false, MoreExecutors.sameThreadExecutor()); } /** * Registers separate success and failure callbacks to be run when the {@code * Future}'s computation is {@linkplain java.util.concurrent.Future#isDone() * complete} or, if the computation is already complete, immediately. * * <p>There is no guaranteed ordering of execution of callbacks, but any * callback added through this method is guaranteed to be called once the * computation is complete. * * Example: <pre> {@code * ListenableFuture<QueryResult> future = ...; * addCallback(future, * new FutureCallback<QueryResult> { * public void onSuccess(QueryResult result) { * storeInCache(result); * } * public void onFailure(Throwable t) { * reportError(t); * } * });}</pre> * * <p>Note: If the callback is slow or heavyweight, consider {@linkplain * #addCallback(ListenableFuture, FutureCallback, Executor) supplying an * executor}. If you do not supply an executor, {@code addCallback} will use * {@link MoreExecutors#sameThreadExecutor sameThreadExecutor}, which carries * some caveats for heavier operations. For example, the callback may run on * an unpredictable or undesirable thread: * * <ul> * <li>If the input {@code Future} is done at the time {@code addCallback} is * called, {@code addCallback} will execute the callback inline. * <li>If the input {@code Future} is not yet done, {@code addCallback} will * schedule the callback 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> * * <p>Also note that, regardless of which thread executes the {@code * sameThreadExecutor} callback, all other registered but unexecuted listeners * are prevented from running during its execution, even if those listeners * are to run in other executors. * * <p>For a more general interface to attach a completion listener to a * {@code Future}, see {@link ListenableFuture#addListener addListener}. * * @param future The future attach the callback to. * @param callback The callback to invoke when {@code future} is completed. * @since 10.0 */ public static <V> void addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback) { addCallback(future, callback, MoreExecutors.sameThreadExecutor()); } /** * Registers separate success and failure callbacks to be run when the {@code * Future}'s computation is {@linkplain java.util.concurrent.Future#isDone() * complete} or, if the computation is already complete, immediately. * * <p>The callback is run in {@code executor}. * There is no guaranteed ordering of execution of callbacks, but any * callback added through this method is guaranteed to be called once the * computation is complete. * * Example: <pre> {@code * ListenableFuture<QueryResult> future = ...; * Executor e = ... * addCallback(future, e, * new FutureCallback<QueryResult> { * public void onSuccess(QueryResult result) { * storeInCache(result); * } * public void onFailure(Throwable t) { * reportError(t); * } * });}</pre> * * <p>When the callback is fast and lightweight, consider {@linkplain * #addCallback(ListenableFuture, FutureCallback) omitting the executor} or * explicitly specifying {@code sameThreadExecutor}. However, be aware of the * caveats documented in the link above. * * <p>For a more general interface to attach a completion listener to a * {@code Future}, see {@link ListenableFuture#addListener addListener}. * * @param future The future attach the callback to. * @param callback The callback to invoke when {@code future} is completed. * @param executor The executor to run {@code callback} when the future * completes. * @since 10.0 */ public static <V> void addCallback(final ListenableFuture<V> future, final FutureCallback<? super V> callback, Executor executor) { Preconditions.checkNotNull(callback); Runnable callbackListener = new Runnable() { @Override public void run() { final V value; try { // TODO(user): (Before Guava release), validate that this // is the thing for IE. value = getUninterruptibly(future); } catch (ExecutionException e) { callback.onFailure(e.getCause()); return; } catch (RuntimeException e) { callback.onFailure(e); return; } catch (Error e) { callback.onFailure(e); return; } callback.onSuccess(value); } }; future.addListener(callbackListener, executor); } /** * Returns the result of {@link Future#get()}, converting most exceptions to a * new instance of the given checked exception type. This reduces boilerplate * for a common use of {@code Future} in which it is unnecessary to * programmatically distinguish between exception types or to extract other * information from the exception instance. * * <p>Exceptions from {@code Future.get} are treated as follows: * <ul> * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an * {@code X} if the cause is a checked exception, an {@link * UncheckedExecutionException} if the cause is a {@code * RuntimeException}, or an {@link ExecutionError} if the cause is an * {@code Error}. * <li>Any {@link InterruptedException} is wrapped in an {@code X} (after * restoring the interrupt). * <li>Any {@link CancellationException} is propagated untouched, as is any * other {@link RuntimeException} (though {@code get} implementations are * discouraged from throwing such exceptions). * </ul> * * <p>The overall principle is to continue to treat every checked exception as a * checked exception, every unchecked exception as an unchecked exception, and * every error as an error. In addition, the cause of any {@code * ExecutionException} is wrapped in order to ensure that the new stack trace * matches that of the current thread. * * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary * public constructor that accepts zero or more arguments, all of type {@code * String} or {@code Throwable} (preferring constructors with at least one * {@code String}) and calling the constructor via reflection. If the * exception did not already have a cause, one is set by calling {@link * Throwable#initCause(Throwable)} on it. If no such constructor exists, an * {@code IllegalArgumentException} is thrown. * * @throws X if {@code get} throws any checked exception except for an {@code * ExecutionException} whose cause is not itself a checked exception * @throws UncheckedExecutionException if {@code get} throws an {@code * ExecutionException} with a {@code RuntimeException} as its cause * @throws ExecutionError if {@code get} throws an {@code ExecutionException} * with an {@code Error} as its cause * @throws CancellationException if {@code get} throws a {@code * CancellationException} * @throws IllegalArgumentException if {@code exceptionClass} extends {@code * RuntimeException} or does not have a suitable constructor * @since 10.0 */ public static <V, X extends Exception> V get( Future<V> future, Class<X> exceptionClass) throws X { checkNotNull(future); checkArgument(!RuntimeException.class.isAssignableFrom(exceptionClass), "Futures.get exception type (%s) must not be a RuntimeException", exceptionClass); try { return future.get(); } catch (InterruptedException e) { currentThread().interrupt(); throw newWithCause(exceptionClass, e); } catch (ExecutionException e) { wrapAndThrowExceptionOrError(e.getCause(), exceptionClass); throw new AssertionError(); } } /** * Returns the result of {@link Future#get(long, TimeUnit)}, converting most * exceptions to a new instance of the given checked exception type. This * reduces boilerplate for a common use of {@code Future} in which it is * unnecessary to programmatically distinguish between exception types or to * extract other information from the exception instance. * * <p>Exceptions from {@code Future.get} are treated as follows: * <ul> * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an * {@code X} if the cause is a checked exception, an {@link * UncheckedExecutionException} if the cause is a {@code * RuntimeException}, or an {@link ExecutionError} if the cause is an * {@code Error}. * <li>Any {@link InterruptedException} is wrapped in an {@code X} (after * restoring the interrupt). * <li>Any {@link TimeoutException} is wrapped in an {@code X}. * <li>Any {@link CancellationException} is propagated untouched, as is any * other {@link RuntimeException} (though {@code get} implementations are * discouraged from throwing such exceptions). * </ul> * * <p>The overall principle is to continue to treat every checked exception as a * checked exception, every unchecked exception as an unchecked exception, and * every error as an error. In addition, the cause of any {@code * ExecutionException} is wrapped in order to ensure that the new stack trace * matches that of the current thread. * * <p>Instances of {@code exceptionClass} are created by choosing an arbitrary * public constructor that accepts zero or more arguments, all of type {@code * String} or {@code Throwable} (preferring constructors with at least one * {@code String}) and calling the constructor via reflection. If the * exception did not already have a cause, one is set by calling {@link * Throwable#initCause(Throwable)} on it. If no such constructor exists, an * {@code IllegalArgumentException} is thrown. * * @throws X if {@code get} throws any checked exception except for an {@code * ExecutionException} whose cause is not itself a checked exception * @throws UncheckedExecutionException if {@code get} throws an {@code * ExecutionException} with a {@code RuntimeException} as its cause * @throws ExecutionError if {@code get} throws an {@code ExecutionException} * with an {@code Error} as its cause * @throws CancellationException if {@code get} throws a {@code * CancellationException} * @throws IllegalArgumentException if {@code exceptionClass} extends {@code * RuntimeException} or does not have a suitable constructor * @since 10.0 */ public static <V, X extends Exception> V get( Future<V> future, long timeout, TimeUnit unit, Class<X> exceptionClass) throws X { checkNotNull(future); checkNotNull(unit); checkArgument(!RuntimeException.class.isAssignableFrom(exceptionClass), "Futures.get exception type (%s) must not be a RuntimeException", exceptionClass); try { return future.get(timeout, unit); } catch (InterruptedException e) { currentThread().interrupt(); throw newWithCause(exceptionClass, e); } catch (TimeoutException e) { throw newWithCause(exceptionClass, e); } catch (ExecutionException e) { wrapAndThrowExceptionOrError(e.getCause(), exceptionClass); throw new AssertionError(); } } private static <X extends Exception> void wrapAndThrowExceptionOrError( Throwable cause, Class<X> exceptionClass) throws X { if (cause instanceof Error) { throw new ExecutionError((Error) cause); } if (cause instanceof RuntimeException) { throw new UncheckedExecutionException(cause); } throw newWithCause(exceptionClass, cause); } /** * Returns the result of calling {@link Future#get()} uninterruptibly on a * task known not to throw a checked exception. This makes {@code Future} more * suitable for lightweight, fast-running tasks that, barring bugs in the * code, will not fail. This gives it exception-handling behavior similar to * that of {@code ForkJoinTask.join}. * * <p>Exceptions from {@code Future.get} are treated as follows: * <ul> * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an * {@link UncheckedExecutionException} (if the cause is an {@code * Exception}) or {@link ExecutionError} (if the cause is an {@code * Error}). * <li>Any {@link InterruptedException} causes a retry of the {@code get} * call. The interrupt is restored before {@code getUnchecked} returns. * <li>Any {@link CancellationException} is propagated untouched. So is any * other {@link RuntimeException} ({@code get} implementations are * discouraged from throwing such exceptions). * </ul> * * <p>The overall principle is to eliminate all checked exceptions: to loop to * avoid {@code InterruptedException}, to pass through {@code * CancellationException}, and to wrap any exception from the underlying * computation in an {@code UncheckedExecutionException} or {@code * ExecutionError}. * * <p>For an uninterruptible {@code get} that preserves other exceptions, see * {@link Uninterruptibles#getUninterruptibly(Future)}. * * @throws UncheckedExecutionException if {@code get} throws an {@code * ExecutionException} with an {@code Exception} as its cause * @throws ExecutionError if {@code get} throws an {@code ExecutionException} * with an {@code Error} as its cause * @throws CancellationException if {@code get} throws a {@code * CancellationException} * @since 10.0 */ public static <V> V getUnchecked(Future<V> future) { checkNotNull(future); try { return getUninterruptibly(future); } catch (ExecutionException e) { wrapAndThrowUnchecked(e.getCause()); throw new AssertionError(); } } private static void wrapAndThrowUnchecked(Throwable cause) { if (cause instanceof Error) { throw new ExecutionError((Error) cause); } /* * It's a non-Error, non-Exception Throwable. From my survey of such * classes, I believe that most users intended to extend Exception, so we'll * treat it like an Exception. */ throw new UncheckedExecutionException(cause); } /* * TODO(user): FutureChecker interface for these to be static methods on? If * so, refer to it in the (static-method) Futures.get documentation */ /* * Arguably we don't need a timed getUnchecked because any operation slow * enough to require a timeout is heavyweight enough to throw a checked * exception and therefore be inappropriate to use with getUnchecked. Further, * it's not clear that converting the checked TimeoutException to a * RuntimeException -- especially to an UncheckedExecutionException, since it * wasn't thrown by the computation -- makes sense, and if we don't convert * it, the user still has to write a try-catch block. * * If you think you would use this method, let us know. */ private static <X extends Exception> X newWithCause( Class<X> exceptionClass, Throwable cause) { // getConstructors() guarantees this as long as we don't modify the array. @SuppressWarnings("unchecked") List<Constructor<X>> constructors = (List) Arrays.asList(exceptionClass.getConstructors()); for (Constructor<X> constructor : preferringStrings(constructors)) { @Nullable X instance = newFromConstructor(constructor, cause); if (instance != null) { if (instance.getCause() == null) { instance.initCause(cause); } return instance; } } throw new IllegalArgumentException( "No appropriate constructor for exception of type " + exceptionClass + " in response to chained exception", cause); } private static <X extends Exception> List<Constructor<X>> preferringStrings(List<Constructor<X>> constructors) { return WITH_STRING_PARAM_FIRST.sortedCopy(constructors); } private static final Ordering<Constructor<?>> WITH_STRING_PARAM_FIRST = Ordering.natural().onResultOf(new Function<Constructor<?>, Boolean>() { @Override public Boolean apply(Constructor<?> input) { return asList(input.getParameterTypes()).contains(String.class); } }).reverse(); @Nullable private static <X> X newFromConstructor( Constructor<X> constructor, Throwable cause) { Class<?>[] paramTypes = constructor.getParameterTypes(); Object[] params = new Object[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) { Class<?> paramType = paramTypes[i]; if (paramType.equals(String.class)) { params[i] = cause.toString(); } else if (paramType.equals(Throwable.class)) { params[i] = cause; } else { return null; } } try { return constructor.newInstance(params); } catch (IllegalArgumentException e) { return null; } catch (InstantiationException e) { return null; } catch (IllegalAccessException e) { return null; } catch (InvocationTargetException e) { return null; } } private interface FutureCombiner<V, C> { C combine(List<Optional<V>> values); } private static class CombinedFuture<V, C> extends AbstractFuture<C> { private static final Logger logger = Logger.getLogger(CombinedFuture.class.getName()); ImmutableCollection<? extends ListenableFuture<? extends V>> futures; final boolean allMustSucceed; final AtomicInteger remaining; FutureCombiner<V, C> combiner; List<Optional<V>> values; CombinedFuture( ImmutableCollection<? extends ListenableFuture<? extends V>> futures, boolean allMustSucceed, Executor listenerExecutor, FutureCombiner<V, C> combiner) { this.futures = futures; this.allMustSucceed = allMustSucceed; this.remaining = new AtomicInteger(futures.size()); this.combiner = combiner; this.values = Lists.newArrayListWithCapacity(futures.size()); init(listenerExecutor); } /** * Must be called at the end of the constructor. */ protected void init(final Executor listenerExecutor) { // First, schedule cleanup to execute when the Future is done. addListener(new Runnable() { @Override public void run() { // Cancel all the component futures. if (CombinedFuture.this.isCancelled()) { for (ListenableFuture<?> future : CombinedFuture.this.futures) { future.cancel(CombinedFuture.this.wasInterrupted()); } } // Let go of the memory held by other futures CombinedFuture.this.futures = null; // By now the values array has either been set as the Future's value, // or (in case of failure) is no longer useful. CombinedFuture.this.values = null; // The combiner may also hold state, so free that as well CombinedFuture.this.combiner = null; } }, MoreExecutors.sameThreadExecutor()); // Now begin the "real" initialization. // Corner case: List is empty. if (futures.isEmpty()) { set(combiner.combine(ImmutableList.<Optional<V>>of())); return; } // Populate the results list with null initially. for (int i = 0; i < futures.size(); ++i) { values.add(null); } // Register a listener on each Future in the list to update // the state of this future. // Note that if all the futures on the list are done prior to completing // this loop, the last call to addListener() will callback to // setOneValue(), transitively call our cleanup listener, and set // this.futures to null. // This is not actually a problem, since the foreach only needs // this.futures to be non-null at the beginning of the loop. int i = 0; for (final ListenableFuture<? extends V> listenable : futures) { final int index = i++; listenable.addListener(new Runnable() { @Override public void run() { setOneValue(index, listenable); } }, listenerExecutor); } } /** * Fails this future with the given Throwable if {@link #allMustSucceed} is * true. Also, logs the throwable if it is an {@link Error} or if * {@link #allMustSucceed} is {@code true} and the throwable did not cause * this future to fail. */ private void setExceptionAndMaybeLog(Throwable throwable) { boolean result = false; if (allMustSucceed) { // As soon as the first one fails, throw the exception up. // The result of all other inputs is then ignored. result = super.setException(throwable); } if (throwable instanceof Error || (allMustSucceed && !result)) { logger.log(Level.SEVERE, "input future failed.", throwable); } } /** * Sets the value at the given index to that of the given future. */ private void setOneValue(int index, Future<? extends V> future) { List<Optional<V>> localValues = values; // TODO(user): This check appears to be redundant since values is // assigned null only after the future completes. However, values // is not volatile so it may be possible for us to observe the changes // to these two values in a different order... which I think is why // we need to check both. Clear up this craziness either by making // values volatile or proving that it doesn't need to be for some other // reason. if (isDone() || localValues == null) { // Some other future failed or has been cancelled, causing this one to // also be cancelled or have an exception set. This should only happen // if allMustSucceed is true or if the output itself has been // cancelled. checkState(allMustSucceed || isCancelled(), "Future was done before all dependencies completed"); } try { checkState(future.isDone(), "Tried to set value from future which is not done"); V returnValue = getUninterruptibly(future); if (localValues != null) { localValues.set(index, Optional.fromNullable(returnValue)); } } catch (CancellationException e) { if (allMustSucceed) { // Set ourselves as cancelled. Let the input futures keep running // as some of them may be used elsewhere. cancel(false); } } catch (ExecutionException e) { setExceptionAndMaybeLog(e.getCause()); } catch (Throwable t) { setExceptionAndMaybeLog(t); } finally { int newRemaining = remaining.decrementAndGet(); checkState(newRemaining >= 0, "Less than 0 remaining futures"); if (newRemaining == 0) { FutureCombiner<V, C> localCombiner = combiner; if (localCombiner != null && localValues != null) { set(localCombiner.combine(localValues)); } else { checkState(isDone()); } } } } } /** Used for {@link #allAsList} and {@link #successfulAsList}. */ private static <V> ListenableFuture<List<V>> listFuture( ImmutableList<ListenableFuture<? extends V>> futures, boolean allMustSucceed, Executor listenerExecutor) { return new CombinedFuture<V, List<V>>( futures, allMustSucceed, listenerExecutor, new FutureCombiner<V, List<V>>() { @Override public List<V> combine(List<Optional<V>> values) { List<V> result = Lists.newArrayList(); for (Optional<V> element : values) { result.add(element != null ? element.orNull() : null); } return Collections.unmodifiableList(result); } }); } /** * A checked future that uses a function to map from exceptions to the * appropriate checked type. */ private static class MappingCheckedFuture<V, X extends Exception> extends AbstractCheckedFuture<V, X> { final Function<Exception, X> mapper; MappingCheckedFuture(ListenableFuture<V> delegate, Function<Exception, X> mapper) { super(delegate); this.mapper = checkNotNull(mapper); } @Override protected X mapException(Exception e) { return mapper.apply(e); } } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.Beta; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * A {@code CheckedFuture} is a {@link ListenableFuture} that includes versions * of the {@code get} methods that can throw a checked exception. This makes it * easier to create a future that executes logic which can throw an exception. * * <p>A common implementation is {@link Futures#immediateCheckedFuture}. * * <p>Implementations of this interface must adapt the exceptions thrown by * {@code Future#get()}: {@link CancellationException}, * {@link ExecutionException} and {@link InterruptedException} into the type * specified by the {@code X} type parameter. * * <p>This interface also extends the ListenableFuture interface to allow * listeners to be added. This allows the future to be used as a normal * {@link Future} or as an asynchronous callback mechanism as needed. This * allows multiple callbacks to be registered for a particular task, and the * future will guarantee execution of all listeners when the task completes. * * <p>For a simpler alternative to CheckedFuture, consider accessing Future * values with {@link Futures#get(Future, Class) Futures.get()}. * * @author Sven Mawson * @since 1.0 */ @Beta public interface CheckedFuture<V, X extends Exception> extends ListenableFuture<V> { /** * Exception checking version of {@link Future#get()} that will translate * {@link InterruptedException}, {@link CancellationException} and * {@link ExecutionException} into application-specific exceptions. * * @return the result of executing the future. * @throws X on interruption, cancellation or execution exceptions. */ V checkedGet() throws X; /** * Exception checking version of {@link Future#get(long, TimeUnit)} that will * translate {@link InterruptedException}, {@link CancellationException} and * {@link ExecutionException} into application-specific exceptions. On * timeout this method throws a normal {@link TimeoutException}. * * @return the result of executing the future. * @throws TimeoutException if retrieving the result timed out. * @throws X on interruption, cancellation or execution exceptions. */ V checkedGet(long timeout, TimeUnit unit) throws TimeoutException, X; }
Java
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static java.util.logging.Level.SEVERE; import com.google.common.annotations.VisibleForTesting; import java.lang.Thread.UncaughtExceptionHandler; import java.util.logging.Logger; /** * Factories for {@link UncaughtExceptionHandler} instances. * * @author Gregory Kick * @since 8.0 */ public final class UncaughtExceptionHandlers { private UncaughtExceptionHandlers() {} /** * Returns an exception handler that exits the system. This is particularly useful for the main * thread, which may start up other, non-daemon threads, but fail to fully initialize the * application successfully. * * <p>Example usage: * <pre>public static void main(String[] args) { * Thread.currentThread().setUncaughtExceptionHandler(UncaughtExceptionHandlers.systemExit()); * ... * </pre> * * <p>The returned handler logs any exception at severity {@code SEVERE} and then shuts down the * process with an exit status of 1, indicating abnormal termination. */ public static UncaughtExceptionHandler systemExit() { return new Exiter(Runtime.getRuntime()); } @VisibleForTesting static final class Exiter implements UncaughtExceptionHandler { private static final Logger logger = Logger.getLogger(Exiter.class.getName()); private final Runtime runtime; Exiter(Runtime runtime) { this.runtime = runtime; } @Override public void uncaughtException(Thread t, Throwable e) { // cannot use FormattingLogger due to a dependency loop logger.log(SEVERE, String.format("Caught an exception in %s. Shutting down.", t), e); runtime.exit(1); } } }
Java
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import javax.annotation.Nullable; /** * Unchecked version of {@link java.util.concurrent.TimeoutException}. * * @author Kevin Bourrillion * @since 1.0 */ public class UncheckedTimeoutException extends RuntimeException { public UncheckedTimeoutException() {} public UncheckedTimeoutException(@Nullable String message) { super(message); } public UncheckedTimeoutException(@Nullable Throwable cause) { super(cause); } public UncheckedTimeoutException(@Nullable String message, @Nullable Throwable cause) { super(message, cause); } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Supplier; import java.util.concurrent.Callable; import javax.annotation.Nullable; /** * Static utility methods pertaining to the {@link Callable} interface. * * @author Isaac Shum * @since 1.0 */ public final class Callables { private Callables() {} /** * Creates a {@code Callable} which immediately returns a preset value each * time it is called. */ public static <T> Callable<T> returning(final @Nullable T value) { return new Callable<T>() { @Override public T call() { return value; } }; } /** * Wraps the given callable such that for the duration of {@link Callable#call} the thread that is * running will have the given name. * * @param callable The callable to wrap * @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once * for each invocation of the wrapped callable. */ static <T> Callable<T> threadRenaming(final Callable<T> callable, final Supplier<String> nameSupplier) { checkNotNull(nameSupplier); checkNotNull(callable); return new Callable<T>() { @Override public T call() throws Exception { Thread currentThread = Thread.currentThread(); String oldName = currentThread.getName(); boolean restoreName = trySetName(nameSupplier.get(), currentThread); try { return callable.call(); } finally { if (restoreName) { trySetName(oldName, currentThread); } } } }; } /** * Wraps the given runnable such that for the duration of {@link Runnable#run} the thread that is * running with have the given name. * * @param task The Runnable to wrap * @param nameSupplier The supplier of thread names, {@link Supplier#get get} will be called once * for each invocation of the wrapped callable. */ static Runnable threadRenaming(final Runnable task, final Supplier<String> nameSupplier) { checkNotNull(nameSupplier); checkNotNull(task); return new Runnable() { @Override public void run() { Thread currentThread = Thread.currentThread(); String oldName = currentThread.getName(); boolean restoreName = trySetName(nameSupplier.get(), currentThread); try { task.run(); } finally { if (restoreName) { trySetName(oldName, currentThread); } } } }; } /** Tries to set name of the given {@link Thread}, returns true if successful. */ private static boolean trySetName(final String threadName, Thread currentThread) { // In AppEngine this will always fail, should we test for that explicitly using // MoreExecutors.isAppEngine. More generally, is there a way to see if we have the modifyThread // permission without catching an exception? try { currentThread.setName(threadName); return true; } catch (SecurityException e) { 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 static com.google.common.base.Objects.firstNonNull; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.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.ConcurrentMap; 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} instances and * {@link ReentrantReadWriteLock} instances 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> * <p>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> * <p>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> * <p>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> * <p>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 -&gt; LockB -&gt; LockC * LockA -&gt; LockC -&gt; LockB * </pre> * * <strong>ReadWriteLocks</strong> * <p> * While {@code ReadWriteLock} instances have different properties and can form cycles * without potential deadlock, this class treats {@code ReadWriteLock} instances 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> * * <p>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 ConcurrentMap<Class<? extends Enum>, Map<? extends Enum, LockGraphNode>> lockGraphNodesPerType = new MapMaker().weakKeys().makeMap(); /** * Creates a {@code CycleDetectingLockFactory.WithExplicitOrdering<E>}. */ public static <E extends Enum<E>> WithExplicitOrdering<E> newInstanceWithExplicitOrdering(Class<E> enumClass, Policy policy) { // createNodes maps each enumClass to a Map with the corresponding enum key // type. checkNotNull(enumClass); checkNotNull(policy); @SuppressWarnings("unchecked") Map<E, LockGraphNode> lockGraphNodes = (Map<E, LockGraphNode>) getOrCreateNodes(enumClass); return new WithExplicitOrdering<E>(policy, lockGraphNodes); } private static Map<? extends Enum, LockGraphNode> getOrCreateNodes( Class<? extends Enum> clazz) { Map<? extends Enum, LockGraphNode> existing = lockGraphNodesPerType.get(clazz); if (existing != null) { return existing; } Map<? extends Enum, LockGraphNode> created = createNodes(clazz); existing = lockGraphNodesPerType.putIfAbsent(clazz, created); return firstNonNull(existing, created); } /** * 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 <E extends Enum<E>> Map<E, LockGraphNode> createNodes(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 static String getLockName(Enum<?> rank) { return rank.getDeclaringClass().getSimpleName() + "." + rank.name(); } /** * <p>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> * * <p>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> * * <p>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); } } //////// Implementation ///////// private static final Logger logger = Logger.getLogger( CycleDetectingLockFactory.class.getName()); final Policy policy; private CycleDetectingLockFactory(Policy policy) { this.policy = checkNotNull(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 -&gt; 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} instances to illustrate the * cycle, e.g. * * <pre> * com....PotentialDeadlockException: Potential Deadlock from LockC -&gt; ReadWriteA * at ... * at ... * Caused by: com...ExampleStackTrace: LockB -&gt; LockC * at ... * at ... * Caused by: com...ExampleStackTrace: ReadWriteA -&gt; LockB * at ... * at ... * </pre> * * <p>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) 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.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 */ @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) 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 java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; 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> * * <p>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 * @author Martin Buchholz * @since 10.0 */ @Beta public final class Monitor { // TODO(user): Use raw LockSupport or AbstractQueuedSynchronizer instead of ReentrantLock. // TODO(user): "Port" jsr166 tests for ReentrantLock. // TODO(user): Change API to make it impossible to use a Guard with the "wrong" monitor, // by making the monitor implicit, and to eliminate other sources of IMSE. // Imagine: // guard.lock(); // try { /* monitor locked and guard satisfied here */ } // finally { guard.unlock(); } // TODO(user): Implement ReentrantLock features: // - toString() method // - getOwner() method // - getQueuedThreads() method // - getWaitingThreads(Guard) method // - implement Serializable // - redo the API to be as close to identical to ReentrantLock as possible, // since, after all, this class is also a reentrant mutual exclusion lock!? /* * One of the key challenges of this class is to prevent lost signals, while trying hard to * minimize unnecessary signals. One simple and correct algorithm is to signal some other * waiter with a satisfied guard (if one exists) whenever any thread occupying the monitor * exits the monitor, either by unlocking all of its held locks, or by starting to wait for a * guard. This includes exceptional exits, so all control paths involving signalling must be * protected by a finally block. * * Further optimizations of this algorithm become increasingly subtle. A wait that terminates * without the guard being satisfied (due to timeout, but not interrupt) can then immediately * exit the monitor without signalling. If it timed out without being signalled, it does not * need to "pass on" the signal to another thread. If it *was* signalled, then its guard must * have been satisfied at the time of signal, and has since been modified by some other thread * to be non-satisfied before reacquiring the lock, and that other thread takes over the * responsibility of signaling the next waiter. * * Unlike the underlying Condition, if we are not careful, an interrupt *can* cause a signal to * be lost, because the signal may be sent to a condition whose sole waiter has just been * interrupted. * * Imagine a monitor with multiple guards. A thread enters the monitor, satisfies all the * guards, and leaves, calling signalNextWaiter. With traditional locks and conditions, all * the conditions need to be signalled because it is not known which if any of them have * waiters (and hasWaiters can't be used reliably because of a check-then-act race). With our * Monitor guards, we only signal the first active guard that is satisfied. But the * corresponding thread may have already been interrupted and is waiting to reacquire the lock * while still registered in activeGuards, in which case the signal is a no-op, and the * bigger-picture signal is lost unless interrupted threads take special action by * participating in the signal-passing game. */ /** * 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; /** The next active guard */ @GuardedBy("monitor.lock") Guard next; 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(); } /** * 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}). * A linked list threaded through the Guard.next field. */ @GuardedBy("lock") private Guard activeGuards = null; /** * 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) { long timeoutNanos = unit.toNanos(time); final ReentrantLock lock = this.lock; if (!fair && lock.tryLock()) { return true; } long deadline = System.nanoTime() + timeoutNanos; boolean interrupted = Thread.interrupted(); try { while (true) { try { return lock.tryLock(timeoutNanos, TimeUnit.NANOSECONDS); } catch (InterruptedException interrupt) { interrupted = true; timeoutNanos = deadline - System.nanoTime(); } } } finally { if (interrupted) { 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 signalBeforeWaiting = lock.isHeldByCurrentThread(); lock.lockInterruptibly(); boolean satisfied = false; try { if (!guard.isSatisfied()) { await(guard, signalBeforeWaiting); } satisfied = true; } finally { if (!satisfied) { leave(); } } } /** * 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 signalBeforeWaiting = lock.isHeldByCurrentThread(); lock.lock(); boolean satisfied = false; try { if (!guard.isSatisfied()) { awaitUninterruptibly(guard, signalBeforeWaiting); } satisfied = true; } finally { if (!satisfied) { leave(); } } } /** * 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 with the guard satisfied */ public boolean enterWhen(Guard guard, long time, TimeUnit unit) throws InterruptedException { long timeoutNanos = unit.toNanos(time); if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; boolean reentrant = lock.isHeldByCurrentThread(); if (fair || !lock.tryLock()) { long deadline = System.nanoTime() + timeoutNanos; if (!lock.tryLock(time, unit)) { return false; } timeoutNanos = deadline - System.nanoTime(); } boolean satisfied = false; boolean threw = true; try { satisfied = guard.isSatisfied() || awaitNanos(guard, timeoutNanos, reentrant); threw = false; return satisfied; } finally { if (!satisfied) { try { // Don't need to signal if timed out, but do if interrupted if (threw && !reentrant) { signalNextWaiter(); } } finally { 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. * * @return whether the monitor was entered with the guard satisfied */ public boolean enterWhenUninterruptibly(Guard guard, long time, TimeUnit unit) { long timeoutNanos = unit.toNanos(time); if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; long deadline = System.nanoTime() + timeoutNanos; boolean signalBeforeWaiting = lock.isHeldByCurrentThread(); boolean interrupted = Thread.interrupted(); try { if (fair || !lock.tryLock()) { boolean locked = false; do { try { locked = lock.tryLock(timeoutNanos, TimeUnit.NANOSECONDS); if (!locked) { return false; } } catch (InterruptedException interrupt) { interrupted = true; } timeoutNanos = deadline - System.nanoTime(); } while (!locked); } boolean satisfied = false; try { while (true) { try { return satisfied = guard.isSatisfied() || awaitNanos(guard, timeoutNanos, signalBeforeWaiting); } catch (InterruptedException interrupt) { interrupted = true; signalBeforeWaiting = false; timeoutNanos = deadline - System.nanoTime(); } } } finally { if (!satisfied) { lock.unlock(); // No need to signal if timed out } } } finally { if (interrupted) { 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 with the guard satisfied */ public boolean enterIf(Guard guard) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; lock.lock(); boolean satisfied = false; try { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } } /** * 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 with the guard satisfied */ 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 { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } } /** * 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 with the guard satisfied */ public boolean enterIf(Guard guard, long time, TimeUnit unit) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } if (!enter(time, unit)) { return false; } boolean satisfied = false; try { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } } /** * 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 with the guard satisfied */ 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 { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } } /** * 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 with the guard satisfied */ 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 { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } } /** * 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) & lock.isHeldByCurrentThread())) { throw new IllegalMonitorStateException(); } if (!guard.isSatisfied()) { await(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) & lock.isHeldByCurrentThread())) { throw new IllegalMonitorStateException(); } if (!guard.isSatisfied()) { awaitUninterruptibly(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 { long timeoutNanos = unit.toNanos(time); if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { throw new IllegalMonitorStateException(); } return guard.isSatisfied() || awaitNanos(guard, timeoutNanos, 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) { long timeoutNanos = unit.toNanos(time); if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { throw new IllegalMonitorStateException(); } if (guard.isSatisfied()) { return true; } boolean signalBeforeWaiting = true; long deadline = System.nanoTime() + timeoutNanos; boolean interrupted = Thread.interrupted(); try { while (true) { try { return awaitNanos(guard, timeoutNanos, signalBeforeWaiting); } catch (InterruptedException interrupt) { interrupted = true; if (guard.isSatisfied()) { return true; } signalBeforeWaiting = false; timeoutNanos = deadline - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Leaves this monitor. May be called only by a thread currently occupying this monitor. */ public void leave() { final ReentrantLock lock = this.lock; try { // No need to signal if we will still be holding the lock when we return if (lock.getHoldCount() == 1) { signalNextWaiter(); } } finally { lock.unlock(); // Will throw IllegalMonitorStateException if not held } } /** * Returns whether this monitor is using a fair ordering policy. */ public boolean isFair() { return fair; } /** * 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) { return getWaitQueueLength(guard) > 0; } /** * 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(); } } /** * Signals some other thread waiting on a satisfied guard, if one exists. * * We manage calls to this method carefully, to signal only when necessary, but never losing a * signal, which is the classic problem of this kind of concurrency construct. We must signal if * the current thread is about to relinquish the lock and may have changed the state protected by * the monitor, thereby causing some guard to be satisfied. * * In addition, any thread that has been signalled when its guard was satisfied acquires the * responsibility of signalling the next thread when it again relinquishes the lock. Unlike a * normal Condition, there is no guarantee that an interrupted thread has not been signalled, * since the concurrency control must manage multiple Conditions. So this method must generally * be called when waits are interrupted. * * On the other hand, if a signalled thread wakes up to discover that its guard is still not * satisfied, it does *not* need to call this method before returning to wait. This can only * happen due to spurious wakeup (ignorable) or another thread acquiring the lock before the * current thread can and returning the guard to the unsatisfied state. In the latter case the * other thread (last thread modifying the state protected by the monitor) takes over the * responsibility of signalling the next waiter. * * This method must not be called from within a beginWaitingFor/endWaitingFor block, or else the * current thread's guard might be mistakenly signalled, leading to a lost signal. */ @GuardedBy("lock") private void signalNextWaiter() { for (Guard guard = activeGuards; guard != null; guard = guard.next) { if (isSatisfied(guard)) { guard.condition.signal(); break; } } } /** * Exactly like signalNextWaiter, but caller guarantees that guardToSkip need not be considered, * because caller has previously checked that guardToSkip.isSatisfied() returned false. * An optimization for the case that guardToSkip.isSatisfied() may be expensive. * * We decided against using this method, since in practice, isSatisfied() is likely to be very * cheap (typically one field read). Resurrect this method if you find that not to be true. */ // @GuardedBy("lock") // private void signalNextWaiterSkipping(Guard guardToSkip) { // for (Guard guard = activeGuards; guard != null; guard = guard.next) { // if (guard != guardToSkip && isSatisfied(guard)) { // guard.condition.signal(); // break; // } // } // } /** * Exactly like guard.isSatisfied(), but in addition signals all waiting threads in the * (hopefully unlikely) event that isSatisfied() throws. */ @GuardedBy("lock") private boolean isSatisfied(Guard guard) { try { return guard.isSatisfied(); } catch (Throwable throwable) { signalAllWaiters(); throw Throwables.propagate(throwable); } } /** * Signals all threads waiting on guards. */ @GuardedBy("lock") private void signalAllWaiters() { for (Guard guard = activeGuards; guard != null; guard = guard.next) { guard.condition.signalAll(); } } /** * Records that the current thread is about to wait on the specified guard. */ @GuardedBy("lock") private void beginWaitingFor(Guard guard) { int waiters = guard.waiterCount++; if (waiters == 0) { // push guard onto activeGuards guard.next = activeGuards; activeGuards = guard; } } /** * Records that the current thread is no longer waiting on the specified guard. */ @GuardedBy("lock") private void endWaitingFor(Guard guard) { int waiters = --guard.waiterCount; if (waiters == 0) { // unlink guard from activeGuards for (Guard p = activeGuards, pred = null;; pred = p, p = p.next) { if (p == guard) { if (pred == null) { activeGuards = p.next; } else { pred.next = p.next; } p.next = null; // help GC break; } } } } /* * Methods that loop waiting on a guard's condition until the guard is satisfied, while * recording this fact so that other threads know to check our guard and signal us. * It's caller's responsibility to ensure that the guard is *not* currently satisfied. */ @GuardedBy("lock") private void await(Guard guard, boolean signalBeforeWaiting) throws InterruptedException { if (signalBeforeWaiting) { signalNextWaiter(); } beginWaitingFor(guard); try { do { guard.condition.await(); } while (!guard.isSatisfied()); } finally { endWaitingFor(guard); } } @GuardedBy("lock") private void awaitUninterruptibly(Guard guard, boolean signalBeforeWaiting) { if (signalBeforeWaiting) { signalNextWaiter(); } beginWaitingFor(guard); try { do { guard.condition.awaitUninterruptibly(); } while (!guard.isSatisfied()); } finally { endWaitingFor(guard); } } @GuardedBy("lock") private boolean awaitNanos(Guard guard, long nanos, boolean signalBeforeWaiting) throws InterruptedException { if (signalBeforeWaiting) { signalNextWaiter(); } beginWaitingFor(guard); try { do { if (nanos < 0L) { return false; } nanos = guard.condition.awaitNanos(nanos); } while (!guard.isSatisfied()); return true; } finally { endWaitingFor(guard); } } }
Java
/* * Written by Doug Lea and Martin Buchholz with assistance from * members of JCP JSR-166 Expert Group and released to the public * domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ /* * Source: * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/extra/AtomicDouble.java?revision=1.13 * (Modified to adapt to guava coding conventions and * to use AtomicLongFieldUpdater instead of sun.misc.Unsafe) */ package com.google.common.util.concurrent; import static java.lang.Double.doubleToRawLongBits; import static java.lang.Double.longBitsToDouble; import java.util.concurrent.atomic.AtomicLongFieldUpdater; /** * A {@code double} value that may be updated atomically. See the * {@link java.util.concurrent.atomic} package specification for * description of the properties of atomic variables. An {@code * AtomicDouble} is used in applications such as atomic accumulation, * and cannot be used as a replacement for a {@link Double}. However, * this class does extend {@code Number} to allow uniform access by * tools and utilities that deal with numerically-based classes. * * <p><a name="bitEquals">This class compares primitive {@code double} * values in methods such as {@link #compareAndSet} by comparing their * bitwise representation using {@link Double#doubleToRawLongBits}, * which differs from both the primitive double {@code ==} operator * and from {@link Double#equals}, as if implemented by: * <pre> {@code * static boolean bitEquals(double x, double y) { * long xBits = Double.doubleToRawLongBits(x); * long yBits = Double.doubleToRawLongBits(y); * return xBits == yBits; * }}</pre> * * <p>It is possible to write a more scalable updater, at the cost of * giving up strict atomicity. See for example * <a href="http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166edocs/jsr166e/DoubleAdder.html"> * DoubleAdder</a> * and * <a href="http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166edocs/jsr166e/DoubleMaxUpdater.html"> * DoubleMaxUpdater</a>. * * @author Doug Lea * @author Martin Buchholz * @since 11.0 */ public class AtomicDouble extends Number implements java.io.Serializable { private static final long serialVersionUID = 0L; private transient volatile long value; private static final AtomicLongFieldUpdater<AtomicDouble> updater = AtomicLongFieldUpdater.newUpdater(AtomicDouble.class, "value"); /** * Creates a new {@code AtomicDouble} with the given initial value. * * @param initialValue the initial value */ public AtomicDouble(double initialValue) { value = doubleToRawLongBits(initialValue); } /** * Creates a new {@code AtomicDouble} with initial value {@code 0.0}. */ public AtomicDouble() { // assert doubleToRawLongBits(0.0) == 0L; } /** * Gets the current value. * * @return the current value */ public final double get() { return longBitsToDouble(value); } /** * Sets to the given value. * * @param newValue the new value */ public final void set(double newValue) { long next = doubleToRawLongBits(newValue); value = next; } /** * Eventually sets to the given value. * * @param newValue the new value */ public final void lazySet(double newValue) { set(newValue); // TODO(user): replace with code below when jdk5 support is dropped. // long next = doubleToRawLongBits(newValue); // updater.lazySet(this, next); } /** * Atomically sets to the given value and returns the old value. * * @param newValue the new value * @return the previous value */ public final double getAndSet(double newValue) { long next = doubleToRawLongBits(newValue); return longBitsToDouble(updater.getAndSet(this, next)); } /** * Atomically sets the value to the given updated value * if the current value is <a href="#bitEquals">bitwise equal</a> * to the expected value. * * @param expect the expected value * @param update the new value * @return {@code true} if successful. False return indicates that * the actual value was not bitwise equal to the expected value. */ public final boolean compareAndSet(double expect, double update) { return updater.compareAndSet(this, doubleToRawLongBits(expect), doubleToRawLongBits(update)); } /** * Atomically sets the value to the given updated value * if the current value is <a href="#bitEquals">bitwise equal</a> * to the expected value. * * <p>May <a * href="http://download.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html#Spurious"> * fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * * @param expect the expected value * @param update the new value * @return {@code true} if successful */ public final boolean weakCompareAndSet(double expect, double update) { return updater.weakCompareAndSet(this, doubleToRawLongBits(expect), doubleToRawLongBits(update)); } /** * Atomically adds the given value to the current value. * * @param delta the value to add * @return the previous value */ public final double getAndAdd(double delta) { while (true) { long current = value; double currentVal = longBitsToDouble(current); double nextVal = currentVal + delta; long next = doubleToRawLongBits(nextVal); if (updater.compareAndSet(this, current, next)) { return currentVal; } } } /** * Atomically adds the given value to the current value. * * @param delta the value to add * @return the updated value */ public final double addAndGet(double delta) { while (true) { long current = value; double currentVal = longBitsToDouble(current); double nextVal = currentVal + delta; long next = doubleToRawLongBits(nextVal); if (updater.compareAndSet(this, current, next)) { return nextVal; } } } /** * Returns the String representation of the current value. * @return the String representation of the current value */ public String toString() { return Double.toString(get()); } /** * Returns the value of this {@code AtomicDouble} as an {@code int} * after a narrowing primitive conversion. */ public int intValue() { return (int) get(); } /** * Returns the value of this {@code AtomicDouble} as a {@code long} * after a narrowing primitive conversion. */ public long longValue() { return (long) get(); } /** * Returns the value of this {@code AtomicDouble} as a {@code float} * after a narrowing primitive conversion. */ public float floatValue() { return (float) get(); } /** * Returns the value of this {@code AtomicDouble} as a {@code double}. */ public double doubleValue() { return get(); } /** * Saves the state to a stream (that is, serializes it). * * @serialData The current value is emitted (a {@code double}). */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { s.defaultWriteObject(); s.writeDouble(get()); } /** * Reconstitutes the instance from a stream (that is, deserializes it). */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); set(s.readDouble()); } }
Java
/* * Copyright (C) 2013 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.collect.Queues; import java.util.Iterator; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; /** * <p>A thread-safe queue of listeners, each with an associated {@code Executor}, that guarantees * that every {@code Runnable} that is {@linkplain #add added} will be * {@link Executor#execute(Runnable) executed} in the same order that it was added and also that * execution is delayed until the next call to {@link #execute}. This is particularly useful if * you need to ensure that listeners are <em>not</em> executed with a lock held. * * <p>While similar, this is different than {@link ExecutionList} which makes much looser guarantees * around ordering and has a notion of state (the executed bit) that this class does not have. * * <p>Listeners are queued by calling {@link #add} and flushed on calls to {@link #execute()}. * Because calls to {@link #add} may be concurrent with calls to {@link #execute} there is no * guarantee that the queue will be empty after calling {@link #execute}. * * <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 Luke Sandberg */ @ThreadSafe final class ExecutionQueue { private static final Logger logger = Logger.getLogger(ExecutionQueue.class.getName()); /** The listeners to execute in order. */ private final ConcurrentLinkedQueue<RunnableExecutorPair> queuedListeners = Queues.newConcurrentLinkedQueue(); /** * This lock is used with {@link RunnableExecutorPair#submit} to ensure that each listener is * executed at most once. */ private final ReentrantLock lock = new ReentrantLock(); /** * Adds the {@code Runnable} and accompanying {@code Executor} to the queue of listeners to * execute. */ void add(Runnable runnable, Executor executor) { queuedListeners.add(new RunnableExecutorPair(runnable, executor)); } /** * Executes all listeners in the queue. However, note that listeners added concurrently with this * method may be executed as part of this call or not, so there is no guarantee that the queue is * empty after calling this method. */ void execute() { // We need to make sure that listeners are submitted to their executors in the correct order. So // we cannot remove a listener from the queue until we know that it has been submited to its // executor. So we use an iterator and only call remove after submit. This iterator is 'weakly // consistent' which means it observes the list in the correct order but not neccesarily all of // it (i.e. concurrently added or removed items may or may not be observed correctly by this // iterator). This is fine because 1. our contract says we may not execute all concurrently // added items and 2. calling listener.submit is idempotent, so it is safe (and generally cheap) // to call it multiple times. Iterator<RunnableExecutorPair> iterator = queuedListeners.iterator(); while (iterator.hasNext()) { iterator.next().submit(); iterator.remove(); } } /** * The listener object for the queue. * * <p>This ensures that: * <ol> * <li>{@link #executor executor}.{@link Executor#execute execute} is called at most once * <li>{@link #runnable runnable}.{@link Runnable#run run} is called at most once by the * executor * <li>{@link #lock lock} is not held when {@link #runnable runnable}.{@link Runnable#run run} * is called * <li>no thread calling {@link #submit} can return until the task has been accepted by the * executor * </ol> */ private final class RunnableExecutorPair implements Runnable { private final Executor executor; private final Runnable runnable; /** * Should be set to {@code true} after {@link #executor}.{@link Executor#execute execute} has * been called. */ @GuardedBy("lock") private boolean hasBeenExecuted = false; RunnableExecutorPair(Runnable runnable, Executor executor) { this.runnable = checkNotNull(runnable); this.executor = checkNotNull(executor); } /** Submit this listener to its executor */ private void submit() { lock.lock(); try { if (!hasBeenExecuted) { try { executor.execute(this); } catch (Exception e) { logger.log(Level.SEVERE, "Exception while executing listener " + runnable + " with executor " + executor, e); } } } finally { // If the executor was the sameThreadExecutor we may have already released the lock, so // check for that here. if (lock.isHeldByCurrentThread()) { hasBeenExecuted = true; lock.unlock(); } } } @Override public final void run() { // If the executor was the sameThreadExecutor then we might still be holding the lock and // hasBeenExecuted may not have been assigned yet so we unlock now to ensure that we are not // still holding the lock while execute is called. if (lock.isHeldByCurrentThread()) { hasBeenExecuted = true; lock.unlock(); } runnable.run(); } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Concurrency utilities. * * <p>Commonly used types include {@link * com.google.common.util.concurrent.ListenableFuture} and {@link * com.google.common.util.concurrent.Service}. * * <p>Commonly used utilities include {@link * com.google.common.util.concurrent.Futures}, {@link * com.google.common.util.concurrent.MoreExecutors}, and {@link * com.google.common.util.concurrent.ThreadFactoryBuilder}. * * <p>This package is a part of the open-source * <a href="http://guava-libraries.googlecode.com">Guava libraries</a>. */ @ParametersAreNonnullByDefault package com.google.common.util.concurrent; import javax.annotation.ParametersAreNonnullByDefault;
Java
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.collect.ForwardingQueue; import java.util.Collection; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; /** * A {@link BlockingQueue} which forwards all its method calls to another * {@link BlockingQueue}. Subclasses should override one or more methods to * modify the behavior of the backing collection as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Raimundo Mirisola * * @param <E> the type of elements held in this collection * @since 4.0 */ public abstract class ForwardingBlockingQueue<E> extends ForwardingQueue<E> implements BlockingQueue<E> { /** Constructor for use by subclasses. */ protected ForwardingBlockingQueue() {} @Override protected abstract BlockingQueue<E> delegate(); @Override public int drainTo( Collection<? super E> c, int maxElements) { return delegate().drainTo(c, maxElements); } @Override public int drainTo(Collection<? super E> c) { return delegate().drainTo(c); } @Override public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException { return delegate().offer(e, timeout, unit); } @Override public E poll(long timeout, TimeUnit unit) throws InterruptedException { return delegate().poll(timeout, unit); } @Override public void put(E e) throws InterruptedException { delegate().put(e); } @Override public int remainingCapacity() { return delegate().remainingCapacity(); } @Override public E take() throws InterruptedException { return delegate().take(); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.Beta; import com.google.common.base.Supplier; 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 executor = MoreExecutors.renamingDecorator(executor(), new Supplier<String>() { @Override public String get() { return serviceName(); } }); 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 #serviceName} */ protected Executor executor() { return new Executor() { @Override public void execute(Runnable command) { MoreExecutors.newThread(serviceName(), command).start(); } }; } @Override public String toString() { return serviceName() + " [" + 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(); } /** * @since 13.0 */ @Override public final void addListener(Listener listener, Executor executor) { delegate.addListener(listener, executor); } /** * @since 14.0 */ @Override public final Throwable failureCause() { return delegate.failureCause(); } /** * Returns the name of this service. {@link AbstractExecutionThreadService} * may include the name in debugging output. * * <p>Subclasses may override this method. * * @since 14.0 (present in 10.0 as getServiceName) */ protected String serviceName() { return getClass().getSimpleName(); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.base.Preconditions; import com.google.common.collect.ForwardingObject; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * A {@link Future} which forwards all its method calls to another future. * Subclasses should override one or more methods to modify the behavior of * the backing future as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p>Most subclasses can just use {@link SimpleForwardingFuture}. * * @author Sven Mawson * @since 1.0 */ public abstract class ForwardingFuture<V> extends ForwardingObject implements Future<V> { /** Constructor for use by subclasses. */ protected ForwardingFuture() {} @Override protected abstract Future<V> delegate(); @Override public boolean cancel(boolean mayInterruptIfRunning) { return delegate().cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return delegate().isCancelled(); } @Override public boolean isDone() { return delegate().isDone(); } @Override public V get() throws InterruptedException, ExecutionException { return delegate().get(); } @Override public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return delegate().get(timeout, unit); } /* * TODO(cpovirk): Use standard Javadoc form for SimpleForwarding* class and * constructor */ /** * A simplified version of {@link ForwardingFuture} where subclasses * can pass in an already constructed {@link Future} as the delegate. * * @since 9.0 */ public abstract static class SimpleForwardingFuture<V> extends ForwardingFuture<V> { private final Future<V> delegate; protected SimpleForwardingFuture(Future<V> delegate) { this.delegate = Preconditions.checkNotNull(delegate); } @Override protected final Future<V> delegate() { return delegate; } } }
Java
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; /** * An {@link ExecutorService} that returns {@link ListenableFuture} instances. To create an instance * from an existing {@link ExecutorService}, call * {@link MoreExecutors#listeningDecorator(ExecutorService)}. * * @author Chris Povirk * @since 10.0 */ public interface ListeningExecutorService extends ExecutorService { /** * @return a {@code ListenableFuture} representing pending completion of the task * @throws RejectedExecutionException {@inheritDoc} */ @Override <T> ListenableFuture<T> submit(Callable<T> task); /** * @return a {@code ListenableFuture} representing pending completion of the task * @throws RejectedExecutionException {@inheritDoc} */ @Override ListenableFuture<?> submit(Runnable task); /** * @return a {@code ListenableFuture} representing pending completion of the task * @throws RejectedExecutionException {@inheritDoc} */ @Override <T> ListenableFuture<T> submit(Runnable task, T result); /** * {@inheritDoc} * * <p>All elements in the returned list must be {@link ListenableFuture} instances. The easiest * way to obtain a {@code List<ListenableFuture<T>>} from this method is an unchecked (but safe) * cast:<pre> * {@code @SuppressWarnings("unchecked") // guaranteed by invokeAll contract} * {@code List<ListenableFuture<T>> futures = (List) executor.invokeAll(tasks);} * </pre> * * @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. The easiest * way to obtain a {@code List<ListenableFuture<T>>} from this method is an unchecked (but safe) * cast:<pre> * {@code @SuppressWarnings("unchecked") // guaranteed by invokeAll contract} * {@code List<ListenableFuture<T>> futures = (List) executor.invokeAll(tasks, timeout, unit);} * </pre> * * @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) 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.util.concurrent; import com.google.common.annotations.Beta; import java.util.concurrent.ScheduledFuture; /** * Helper interface to implement both {@link ListenableFuture} and * {@link ScheduledFuture}. * * @author Anthony Zana * * @since 15.0 */ @Beta public interface ListenableScheduledFuture<V> extends ScheduledFuture<V>, ListenableFuture<V> {}
Java
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.checkNotNull; 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) { checkNotNull(target); checkNotNull(interfaceType); checkNotNull(timeoutUnit); return target; // ha ha } @Override public <T> T callWithTimeout(Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean amInterruptible) throws Exception { checkNotNull(timeoutUnit); return callable.call(); // fooled you } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import javax.annotation.Nullable; /** * A {@link FutureTask} that also implements the {@link ListenableFuture} * interface. Unlike {@code FutureTask}, {@code ListenableFutureTask} does not * provide an overrideable {@link FutureTask#done() done()} method. For similar * functionality, call {@link #addListener}. * * <p> * * @author Sven Mawson * @since 1.0 */ public class ListenableFutureTask<V> extends FutureTask<V> implements ListenableFuture<V> { // TODO(cpovirk): explore ways of making ListenableFutureTask final. There are // some valid reasons such as BoundedQueueExecutorService to allow extends but it // would be nice to make it final to avoid unintended usage. // 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); } ListenableFutureTask(Callable<V> callable) { super(callable); } 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) 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.base.Throwables; import com.google.common.collect.ImmutableList; 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.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * An abstract {@code ExecutorService} that allows subclasses to * {@linkplain #wrapTask(Callable) wrap} tasks before they are submitted * to the underlying executor. * * <p>Note that task wrapping may occur even if the task is never executed. * * <p>For delegation without task-wrapping, see * {@link ForwardingExecutorService}. * * @author Chris Nokleberg */ abstract class WrappingExecutorService implements ExecutorService { private final ExecutorService delegate; protected WrappingExecutorService(ExecutorService delegate) { this.delegate = checkNotNull(delegate); } /** * Wraps a task before it is submitted to the underlying Executor. * Though specified in terms of Callable, this method is also applied to * Runnable tasks. */ protected abstract <T> Callable<T> wrapTask(Callable<T> callable); /** * Wraps a task before it is submitted to the underlying Executor. This * delegates to {@link #wrapTask(Callable)} by default, but should be * overridden if there is a better implementation for {@link Runnable * runnables}. */ protected Runnable wrapTask(Runnable command) { final Callable<Object> wrapped = wrapTask( Executors.callable(command, null)); return new Runnable() { @Override public void run() { try { wrapped.call(); } catch (Exception e) { Throwables.propagate(e); } } }; } /** * Wraps a collection of tasks. * * @throws NullPointerException if any element of {@code tasks} is null */ private final <T> ImmutableList<Callable<T>> wrapTasks( Collection<? extends Callable<T>> tasks) { ImmutableList.Builder<Callable<T>> builder = ImmutableList.builder(); for (Callable<T> task : tasks) { builder.add(wrapTask(task)); } return builder.build(); } // These methods wrap before delegating. @Override public final void execute(Runnable command) { delegate.execute(wrapTask(command)); } @Override public final <T> Future<T> submit(Callable<T> task) { return delegate.submit(wrapTask(checkNotNull(task))); } @Override public final Future<?> submit(Runnable task) { return delegate.submit(wrapTask(task)); } @Override public final <T> Future<T> submit(Runnable task, T result) { return delegate.submit(wrapTask(task), result); } @Override public final <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks) throws InterruptedException { return delegate.invokeAll(wrapTasks(tasks)); } @Override public final <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { return delegate.invokeAll(wrapTasks(tasks), timeout, unit); } @Override public final <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { return delegate.invokeAny(wrapTasks(tasks)); } @Override public final <T> T invokeAny( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return delegate.invokeAny(wrapTasks(tasks), timeout, unit); } // The remaining methods just delegate. @Override public final void shutdown() { delegate.shutdown(); } @Override public final List<Runnable> shutdownNow() { return delegate.shutdownNow(); } @Override public final boolean isShutdown() { return delegate.isShutdown(); } @Override public final boolean isTerminated() { return delegate.isTerminated(); } @Override public final boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return delegate.awaitTermination(timeout, unit); } }
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> * <p>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. For * example, {@code "rpc-pool-%d"} will generate thread names like * {@code "rpc-pool-0"}, {@code "rpc-pool-1"}, {@code "rpc-pool-2"}, etc. * @return this for the builder pattern */ @SuppressWarnings("ReturnValueIgnored") public ThreadFactoryBuilder setNameFormat(String nameFormat) { String.format(nameFormat, 0); // fail fast if the format is bad or null this.nameFormat = nameFormat; return this; } /** * Sets daemon or not for new threads created with this ThreadFactory. * * @param daemon whether or not new Threads created with this ThreadFactory * will be daemon threads * @return this for the builder pattern */ public ThreadFactoryBuilder setDaemon(boolean daemon) { this.daemon = daemon; return this; } /** * Sets the priority for new threads created with this ThreadFactory. * * @param priority the priority for new Threads created with this * ThreadFactory * @return this for the builder pattern */ public ThreadFactoryBuilder setPriority(int priority) { // Thread#setPriority() already checks for validity. These error messages // are nicer though and will fail-fast. checkArgument(priority >= Thread.MIN_PRIORITY, "Thread priority (%s) must be >= %s", priority, Thread.MIN_PRIORITY); checkArgument(priority <= Thread.MAX_PRIORITY, "Thread priority (%s) must be <= %s", priority, Thread.MAX_PRIORITY); this.priority = priority; return this; } /** * Sets the {@link UncaughtExceptionHandler} for new threads created with this * ThreadFactory. * * @param uncaughtExceptionHandler the uncaught exception handler for new * Threads created with this ThreadFactory * @return this for the builder pattern */ public ThreadFactoryBuilder setUncaughtExceptionHandler( UncaughtExceptionHandler uncaughtExceptionHandler) { this.uncaughtExceptionHandler = checkNotNull(uncaughtExceptionHandler); return this; } /** * Sets the backing {@link ThreadFactory} for new threads created with this * ThreadFactory. Threads will be created by invoking #newThread(Runnable) on * this backing {@link ThreadFactory}. * * @param backingThreadFactory the backing {@link ThreadFactory} which will * be delegated to during thread creation. * @return this for the builder pattern * * @see MoreExecutors */ public ThreadFactoryBuilder setThreadFactory( ThreadFactory backingThreadFactory) { this.backingThreadFactory = checkNotNull(backingThreadFactory); return this; } /** * Returns a new thread factory using the options supplied during the building * process. After building, it is still possible to change the options used to * build the ThreadFactory and/or build again. State is not shared amongst * built instances. * * @return the fully constructed {@link ThreadFactory} */ public ThreadFactory build() { return build(this); } private static ThreadFactory build(ThreadFactoryBuilder builder) { final String nameFormat = builder.nameFormat; final Boolean daemon = builder.daemon; final Integer priority = builder.priority; final UncaughtExceptionHandler uncaughtExceptionHandler = builder.uncaughtExceptionHandler; final ThreadFactory backingThreadFactory = (builder.backingThreadFactory != null) ? builder.backingThreadFactory : Executors.defaultThreadFactory(); final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null; return new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread thread = backingThreadFactory.newThread(runnable); if (nameFormat != null) { thread.setName(String.format(nameFormat, count.getAndIncrement())); } if (daemon != null) { thread.setDaemon(daemon); } if (priority != null) { thread.setPriority(priority); } if (uncaughtExceptionHandler != null) { thread.setUncaughtExceptionHandler(uncaughtExceptionHandler); } return thread; } }; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.RejectedExecutionException; /** * A {@link Future} that accepts completion listeners. Each listener has an * associated executor, and it is invoked using this executor once the future's * computation is {@linkplain Future#isDone() complete}. If the computation has * already completed when the listener is added, the listener will execute * immediately. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained"> * {@code ListenableFuture}</a>. * * <h3>Purpose</h3> * * <p>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> * * <p>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> * * <p>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 this {@code Future} is done at the time {@code addListener} is * called, {@code addListener} will execute the listener inline. * <li>If this {@code Future} is not yet done, {@code addListener} will * schedule the listener to be run by the thread that completes this {@code * Future}, which may be an internal system thread such as an RPC network * thread. * </ul> * * <p>Also note that, regardless of which thread executes the * {@code sameThreadExecutor()} 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) 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.util.concurrent; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Ticker; import java.util.concurrent.TimeUnit; import javax.annotation.concurrent.ThreadSafe; /** * A rate limiter. Conceptually, a rate limiter distributes permits at a * configurable rate. Each {@link #acquire()} blocks if necessary until a permit is * available, and then takes it. Once acquired, permits need not be released. * * <p>Rate limiters are often used to restrict the rate at which some * physical or logical resource is accessed. This is in contrast to {@link * java.util.concurrent.Semaphore} which restricts the number of concurrent * accesses instead of the rate (note though that concurrency and rate are closely related, * e.g. see <a href="http://en.wikipedia.org/wiki/Little's_law">Little's Law</a>). * * <p>A {@code RateLimiter} is defined primarily by the rate at which permits * are issued. Absent additional configuration, permits will be distributed at a * fixed rate, defined in terms of permits per second. Permits will be distributed * smoothly, with the delay between individual permits being adjusted to ensure * that the configured rate is maintained. * * <p>It is possible to configure a {@code RateLimiter} to have a warmup * period during which time the permits issued each second steadily increases until * it hits the stable rate. * * <p>As an example, imagine that we have a list of tasks to execute, but we don't want to * submit more than 2 per second: *<pre> {@code * final RateLimiter rateLimiter = RateLimiter.create(2.0); // rate is "2 permits per second" * void submitTasks(List<Runnable> tasks, Executor executor) { * for (Runnable task : tasks) { * rateLimiter.acquire(); // may wait * executor.execute(task); * } * } *}</pre> * * <p>As another example, imagine that we produce a stream of data, and we want to cap it * at 5kb per second. This could be accomplished by requiring a permit per byte, and specifying * a rate of 5000 permits per second: *<pre> {@code * final RateLimiter rateLimiter = RateLimiter.create(5000.0); // rate = 5000 permits per second * void submitPacket(byte[] packet) { * rateLimiter.acquire(packet.length); * networkService.send(packet); * } *}</pre> * * <p>It is important to note that the number of permits requested <i>never</i> * affect the throttling of the request itself (an invocation to {@code acquire(1)} * and an invocation to {@code acquire(1000)} will result in exactly the same throttling, if any), * but it affects the throttling of the <i>next</i> request. I.e., if an expensive task * arrives at an idle RateLimiter, it will be granted immediately, but it is the <i>next</i> * request that will experience extra throttling, thus paying for the cost of the expensive * task. * * <p>Note: {@code RateLimiter} does not provide fairness guarantees. * * @author Dimitris Andreou * @since 13.0 */ // TODO(user): switch to nano precision. A natural unit of cost is "bytes", and a micro precision // would mean a maximum rate of "1MB/s", which might be small in some cases. @ThreadSafe @Beta public abstract class RateLimiter { /* * How is the RateLimiter designed, and why? * * The primary feature of a RateLimiter is its "stable rate", the maximum rate that * is should allow at normal conditions. This is enforced by "throttling" incoming * requests as needed, i.e. compute, for an incoming request, the appropriate throttle time, * and make the calling thread wait as much. * * The simplest way to maintain a rate of QPS is to keep the timestamp of the last * granted request, and ensure that (1/QPS) seconds have elapsed since then. For example, * for a rate of QPS=5 (5 tokens per second), if we ensure that a request isn't granted * earlier than 200ms after the the last one, then we achieve the intended rate. * If a request comes and the last request was granted only 100ms ago, then we wait for * another 100ms. At this rate, serving 15 fresh permits (i.e. for an acquire(15) request) * naturally takes 3 seconds. * * It is important to realize that such a RateLimiter has a very superficial memory * of the past: it only remembers the last request. What if the RateLimiter was unused for * a long period of time, then a request arrived and was immediately granted? * This RateLimiter would immediately forget about that past underutilization. This may * result in either underutilization or overflow, depending on the real world consequences * of not using the expected rate. * * Past underutilization could mean that excess resources are available. Then, the RateLimiter * should speed up for a while, to take advantage of these resources. This is important * when the rate is applied to networking (limiting bandwidth), where past underutilization * typically translates to "almost empty buffers", which can be filled immediately. * * On the other hand, past underutilization could mean that "the server responsible for * handling the request has become less ready for future requests", i.e. its caches become * stale, and requests become more likely to trigger expensive operations (a more extreme * case of this example is when a server has just booted, and it is mostly busy with getting * itself up to speed). * * To deal with such scenarios, we add an extra dimension, that of "past underutilization", * modeled by "storedPermits" variable. This variable is zero when there is no * underutilization, and it can grow up to maxStoredPermits, for sufficiently large * underutilization. So, the requested permits, by an invocation acquire(permits), * are served from: * - stored permits (if available) * - fresh permits (for any remaining permits) * * How this works is best explained with an example: * * For a RateLimiter that produces 1 token per second, every second * that goes by with the RateLimiter being unused, we increase storedPermits by 1. * Say we leave the RateLimiter unused for 10 seconds (i.e., we expected a request at time * X, but we are at time X + 10 seconds before a request actually arrives; this is * also related to the point made in the last paragraph), thus storedPermits * becomes 10.0 (assuming maxStoredPermits >= 10.0). At that point, a request of acquire(3) * arrives. We serve this request out of storedPermits, and reduce that to 7.0 (how this is * translated to throttling time is discussed later). Immediately after, assume that an * acquire(10) request arriving. We serve the request partly from storedPermits, * using all the remaining 7.0 permits, and the remaining 3.0, we serve them by fresh permits * produced by the rate limiter. * * We already know how much time it takes to serve 3 fresh permits: if the rate is * "1 token per second", then this will take 3 seconds. But what does it mean to serve 7 * stored permits? As explained above, there is no unique answer. If we are primarily * interested to deal with underutilization, then we want stored permits to be given out * /faster/ than fresh ones, because underutilization = free resources for the taking. * If we are primarily interested to deal with overflow, then stored permits could * be given out /slower/ than fresh ones. Thus, we require a (different in each case) * function that translates storedPermits to throtting time. * * This role is played by storedPermitsToWaitTime(double storedPermits, double permitsToTake). * The underlying model is a continuous function mapping storedPermits * (from 0.0 to maxStoredPermits) onto the 1/rate (i.e. intervals) that is effective at the given * storedPermits. "storedPermits" essentially measure unused time; we spend unused time * buying/storing permits. Rate is "permits / time", thus "1 / rate = time / permits". * Thus, "1/rate" (time / permits) times "permits" gives time, i.e., integrals on this * function (which is what storedPermitsToWaitTime() computes) correspond to minimum intervals * between subsequent requests, for the specified number of requested permits. * * Here is an example of storedPermitsToWaitTime: * If storedPermits == 10.0, and we want 3 permits, we take them from storedPermits, * reducing them to 7.0, and compute the throttling for these as a call to * storedPermitsToWaitTime(storedPermits = 10.0, permitsToTake = 3.0), which will * evaluate the integral of the function from 7.0 to 10.0. * * Using integrals guarantees that the effect of a single acquire(3) is equivalent * to { acquire(1); acquire(1); acquire(1); }, or { acquire(2); acquire(1); }, etc, * since the integral of the function in [7.0, 10.0] is equivalent to the sum of the * integrals of [7.0, 8.0], [8.0, 9.0], [9.0, 10.0] (and so on), no matter * what the function is. This guarantees that we handle correctly requests of varying weight * (permits), /no matter/ what the actual function is - so we can tweak the latter freely. * (The only requirement, obviously, is that we can compute its integrals). * * Note well that if, for this function, we chose a horizontal line, at height of exactly * (1/QPS), then the effect of the function is non-existent: we serve storedPermits at * exactly the same cost as fresh ones (1/QPS is the cost for each). We use this trick later. * * If we pick a function that goes /below/ that horizontal line, it means that we reduce * the area of the function, thus time. Thus, the RateLimiter becomes /faster/ after a * period of underutilization. If, on the other hand, we pick a function that * goes /above/ that horizontal line, then it means that the area (time) is increased, * thus storedPermits are more costly than fresh permits, thus the RateLimiter becomes * /slower/ after a period of underutilization. * * Last, but not least: consider a RateLimiter with rate of 1 permit per second, currently * completely unused, and an expensive acquire(100) request comes. It would be nonsensical * to just wait for 100 seconds, and /then/ start the actual task. Why wait without doing * anything? A much better approach is to /allow/ the request right away (as if it was an * acquire(1) request instead), and postpone /subsequent/ requests as needed. In this version, * we allow starting the task immediately, and postpone by 100 seconds future requests, * thus we allow for work to get done in the meantime instead of waiting idly. * * This has important consequences: it means that the RateLimiter doesn't remember the time * of the _last_ request, but it remembers the (expected) time of the _next_ request. This * also enables us to tell immediately (see tryAcquire(timeout)) whether a particular * timeout is enough to get us to the point of the next scheduling time, since we always * maintain that. And what we mean by "an unused RateLimiter" is also defined by that * notion: when we observe that the "expected arrival time of the next request" is actually * in the past, then the difference (now - past) is the amount of time that the RateLimiter * was formally unused, and it is that amount of time which we translate to storedPermits. * (We increase storedPermits with the amount of permits that would have been produced * in that idle time). So, if rate == 1 permit per second, and arrivals come exactly * one second after the previous, then storedPermits is _never_ increased -- we would only * increase it for arrivals _later_ than the expected one second. */ /** * Creates a {@code RateLimiter} with the specified stable throughput, given as * "permits per second" (commonly referred to as <i>QPS</i>, queries per second). * * <p>The returned {@code RateLimiter} ensures that on average no more than {@code * permitsPerSecond} are issued during any given second, with sustained requests * being smoothly spread over each second. When the incoming request rate exceeds * {@code permitsPerSecond} the rate limiter will release one permit every {@code * (1.0 / permitsPerSecond)} seconds. When the rate limiter is unused, * bursts of up to {@code permitsPerSecond} permits will be allowed, with subsequent * requests being smoothly limited at the stable rate of {@code permitsPerSecond}. * * @param permitsPerSecond the rate of the returned {@code RateLimiter}, measured in * how many permits become available per second. */ // TODO(user): "This is equivalent to // {@code createWithCapacity(permitsPerSecond, 1, TimeUnit.SECONDS)}". public static RateLimiter create(double permitsPerSecond) { /* * The default RateLimiter configuration can save the unused permits of up to one second. * This is to avoid unnecessary stalls in situations like this: A RateLimiter of 1qps, * and 4 threads, all calling acquire() at these moments: * * T0 at 0 seconds * T1 at 1.05 seconds * T2 at 2 seconds * T3 at 3 seconds * * Due to the slight delay of T1, T2 would have to sleep till 2.05 seconds, * and T3 would also have to sleep till 3.05 seconds. */ return create(SleepingTicker.SYSTEM_TICKER, permitsPerSecond); } @VisibleForTesting static RateLimiter create(SleepingTicker ticker, double permitsPerSecond) { RateLimiter rateLimiter = new Bursty(ticker, 1.0 /* maxBurstSeconds */); rateLimiter.setRate(permitsPerSecond); return rateLimiter; } /** * Creates a {@code RateLimiter} with the specified stable throughput, given as * "permits per second" (commonly referred to as <i>QPS</i>, queries per second), and a * <i>warmup period</i>, during which the {@code RateLimiter} smoothly ramps up its rate, * until it reaches its maximum rate at the end of the period (as long as there are enough * requests to saturate it). Similarly, if the {@code RateLimiter} is left <i>unused</i> for * a duration of {@code warmupPeriod}, it will gradually return to its "cold" state, * i.e. it will go through the same warming up process as when it was first created. * * <p>The returned {@code RateLimiter} is intended for cases where the resource that actually * fulfills the requests (e.g., a remote server) needs "warmup" time, rather than * being immediately accessed at the stable (maximum) rate. * * <p>The returned {@code RateLimiter} starts in a "cold" state (i.e. the warmup period * will follow), and if it is left unused for long enough, it will return to that state. * * @param permitsPerSecond the rate of the returned {@code RateLimiter}, measured in * how many permits become available per second * @param warmupPeriod the duration of the period where the {@code RateLimiter} ramps up its * rate, before reaching its stable (maximum) rate * @param unit the time unit of the warmupPeriod argument */ public static RateLimiter create(double permitsPerSecond, long warmupPeriod, TimeUnit unit) { return create(SleepingTicker.SYSTEM_TICKER, permitsPerSecond, warmupPeriod, unit); } @VisibleForTesting static RateLimiter create( SleepingTicker ticker, double permitsPerSecond, long warmupPeriod, TimeUnit unit) { RateLimiter rateLimiter = new WarmingUp(ticker, warmupPeriod, unit); rateLimiter.setRate(permitsPerSecond); return rateLimiter; } @VisibleForTesting static RateLimiter createWithCapacity( SleepingTicker ticker, double permitsPerSecond, long maxBurstBuildup, TimeUnit unit) { double maxBurstSeconds = unit.toNanos(maxBurstBuildup) / 1E+9; Bursty rateLimiter = new Bursty(ticker, maxBurstSeconds); rateLimiter.setRate(permitsPerSecond); return rateLimiter; } /** * The underlying timer; used both to measure elapsed time and sleep as necessary. A separate * object to facilitate testing. */ private final SleepingTicker ticker; /** * The timestamp when the RateLimiter was created; used to avoid possible overflow/time-wrapping * errors. */ private final long offsetNanos; /** * The currently stored permits. */ double storedPermits; /** * The maximum number of stored permits. */ double maxPermits; /** * The interval between two unit requests, at our stable rate. E.g., a stable rate of 5 permits * per second has a stable interval of 200ms. */ volatile double stableIntervalMicros; private final Object mutex = new Object(); /** * The time when the next request (no matter its size) will be granted. After granting a request, * this is pushed further in the future. Large requests push this further than small requests. */ private long nextFreeTicketMicros = 0L; // could be either in the past or future private RateLimiter(SleepingTicker ticker) { this.ticker = ticker; this.offsetNanos = ticker.read(); } /** * Updates the stable rate of this {@code RateLimiter}, that is, the * {@code permitsPerSecond} argument provided in the factory method that * constructed the {@code RateLimiter}. Currently throttled threads will <b>not</b> * be awakened as a result of this invocation, thus they do not observe the new rate; * only subsequent requests will. * * <p>Note though that, since each request repays (by waiting, if necessary) the cost * of the <i>previous</i> request, this means that the very next request * after an invocation to {@code setRate} will not be affected by the new rate; * it will pay the cost of the previous request, which is in terms of the previous rate. * * <p>The behavior of the {@code RateLimiter} is not modified in any other way, * e.g. if the {@code RateLimiter} was configured with a warmup period of 20 seconds, * it still has a warmup period of 20 seconds after this method invocation. * * @param permitsPerSecond the new stable rate of this {@code RateLimiter}. */ public final void setRate(double permitsPerSecond) { Preconditions.checkArgument(permitsPerSecond > 0.0 && !Double.isNaN(permitsPerSecond), "rate must be positive"); synchronized (mutex) { resync(readSafeMicros()); double stableIntervalMicros = TimeUnit.SECONDS.toMicros(1L) / permitsPerSecond; this.stableIntervalMicros = stableIntervalMicros; doSetRate(permitsPerSecond, stableIntervalMicros); } } abstract void doSetRate(double permitsPerSecond, double stableIntervalMicros); /** * Returns the stable rate (as {@code permits per seconds}) with which this * {@code RateLimiter} is configured with. The initial value of this is the same as * the {@code permitsPerSecond} argument passed in the factory method that produced * this {@code RateLimiter}, and it is only updated after invocations * to {@linkplain #setRate}. */ public final double getRate() { return TimeUnit.SECONDS.toMicros(1L) / stableIntervalMicros; } /** * Acquires a permit from this {@code RateLimiter}, blocking until the request can be granted. * * <p>This method is equivalent to {@code acquire(1)}. */ public void acquire() { acquire(1); } /** * Acquires the given number of permits from this {@code RateLimiter}, blocking until the * request be granted. * * @param permits the number of permits to acquire */ public void acquire(int permits) { checkPermits(permits); long microsToWait; synchronized (mutex) { microsToWait = reserveNextTicket(permits, readSafeMicros()); } ticker.sleepMicrosUninterruptibly(microsToWait); } /** * Acquires a permit from this {@code RateLimiter} if it can be obtained * without exceeding the specified {@code timeout}, or returns {@code false} * immediately (without waiting) if the permit would not have been granted * before the timeout expired. * * <p>This method is equivalent to {@code tryAcquire(1, timeout, unit)}. * * @param timeout the maximum time to wait for the permit * @param unit the time unit of the timeout argument * @return {@code true} if the permit was acquired, {@code false} otherwise */ public boolean tryAcquire(long timeout, TimeUnit unit) { return tryAcquire(1, timeout, unit); } /** * Acquires permits from this {@link RateLimiter} if it can be acquired immediately without delay. * * <p> * This method is equivalent to {@code tryAcquire(permits, 0, anyUnit)}. * * @param permits the number of permits to acquire * @return {@code true} if the permits were acquired, {@code false} otherwise * @since 14.0 */ public boolean tryAcquire(int permits) { return tryAcquire(permits, 0, TimeUnit.MICROSECONDS); } /** * Acquires a permit from this {@link RateLimiter} if it can be acquired immediately without * delay. * * <p> * This method is equivalent to {@code tryAcquire(1)}. * * @return {@code true} if the permit was acquired, {@code false} otherwise * @since 14.0 */ public boolean tryAcquire() { return tryAcquire(1, 0, TimeUnit.MICROSECONDS); } /** * Acquires the given number of permits from this {@code RateLimiter} if it can be obtained * without exceeding the specified {@code timeout}, or returns {@code false} * immediately (without waiting) if the permits would not have been granted * before the timeout expired. * * @param permits the number of permits to acquire * @param timeout the maximum time to wait for the permits * @param unit the time unit of the timeout argument * @return {@code true} if the permits were acquired, {@code false} otherwise */ public boolean tryAcquire(int permits, long timeout, TimeUnit unit) { long timeoutMicros = unit.toMicros(timeout); checkPermits(permits); long microsToWait; synchronized (mutex) { long nowMicros = readSafeMicros(); if (nextFreeTicketMicros > nowMicros + timeoutMicros) { return false; } else { microsToWait = reserveNextTicket(permits, nowMicros); } } ticker.sleepMicrosUninterruptibly(microsToWait); return true; } private static void checkPermits(int permits) { Preconditions.checkArgument(permits > 0, "Requested permits must be positive"); } /** * Reserves next ticket and returns the wait time that the caller must wait for. */ private long reserveNextTicket(double requiredPermits, long nowMicros) { resync(nowMicros); long microsToNextFreeTicket = nextFreeTicketMicros - nowMicros; double storedPermitsToSpend = Math.min(requiredPermits, this.storedPermits); double freshPermits = requiredPermits - storedPermitsToSpend; long waitMicros = storedPermitsToWaitTime(this.storedPermits, storedPermitsToSpend) + (long) (freshPermits * stableIntervalMicros); this.nextFreeTicketMicros = nextFreeTicketMicros + waitMicros; this.storedPermits -= storedPermitsToSpend; return microsToNextFreeTicket; } /** * Translates a specified portion of our currently stored permits which we want to * spend/acquire, into a throttling time. Conceptually, this evaluates the integral * of the underlying function we use, for the range of * [(storedPermits - permitsToTake), storedPermits]. * * This always holds: {@code 0 <= permitsToTake <= storedPermits} */ abstract long storedPermitsToWaitTime(double storedPermits, double permitsToTake); private void resync(long nowMicros) { // if nextFreeTicket is in the past, resync to now if (nowMicros > nextFreeTicketMicros) { storedPermits = Math.min(maxPermits, storedPermits + (nowMicros - nextFreeTicketMicros) / stableIntervalMicros); nextFreeTicketMicros = nowMicros; } } private long readSafeMicros() { return TimeUnit.NANOSECONDS.toMicros(ticker.read() - offsetNanos); } @Override public String toString() { return String.format("RateLimiter[stableRate=%3.1fqps]", 1000000.0 / stableIntervalMicros); } /** * This implements the following function: * * ^ throttling * | * 3*stable + / * interval | /. * (cold) | / . * | / . <-- "warmup period" is the area of the trapezoid between * 2*stable + / . halfPermits and maxPermits * interval | / . * | / . * | / . * stable +----------/ WARM . } * interval | . UP . } <-- this rectangle (from 0 to maxPermits, and * | . PERIOD. } height == stableInterval) defines the cooldown period, * | . . } and we want cooldownPeriod == warmupPeriod * |---------------------------------> storedPermits * (halfPermits) (maxPermits) * * Before going into the details of this particular function, let's keep in mind the basics: * 1) The state of the RateLimiter (storedPermits) is a vertical line in this figure. * 2) When the RateLimiter is not used, this goes right (up to maxPermits) * 3) When the RateLimiter is used, this goes left (down to zero), since if we have storedPermits, * we serve from those first * 4) When _unused_, we go right at the same speed (rate)! I.e., if our rate is * 2 permits per second, and 3 unused seconds pass, we will always save 6 permits * (no matter what our initial position was), up to maxPermits. * If we invert the rate, we get the "stableInterval" (interval between two requests * in a perfectly spaced out sequence of requests of the given rate). Thus, if you * want to see "how much time it will take to go from X storedPermits to X+K storedPermits?", * the answer is always stableInterval * K. In the same example, for 2 permits per second, * stableInterval is 500ms. Thus to go from X storedPermits to X+6 storedPermits, we * require 6 * 500ms = 3 seconds. * * In short, the time it takes to move to the right (save K permits) is equal to the * rectangle of width == K and height == stableInterval. * 4) When _used_, the time it takes, as explained in the introductory class note, is * equal to the integral of our function, between X permits and X-K permits, assuming * we want to spend K saved permits. * * In summary, the time it takes to move to the left (spend K permits), is equal to the * area of the function of width == K. * * Let's dive into this function now: * * When we have storedPermits <= halfPermits (the left portion of the function), then * we spend them at the exact same rate that * fresh permits would be generated anyway (that rate is 1/stableInterval). We size * this area to be equal to _half_ the specified warmup period. Why we need this? * And why half? We'll explain shortly below (after explaining the second part). * * Stored permits that are beyond halfPermits, are mapped to an ascending line, that goes * from stableInterval to 3 * stableInterval. The average height for that part is * 2 * stableInterval, and is sized appropriately to have an area _equal_ to the * specified warmup period. Thus, by point (4) above, it takes "warmupPeriod" amount of time * to go from maxPermits to halfPermits. * * BUT, by point (3) above, it only takes "warmupPeriod / 2" amount of time to return back * to maxPermits, from halfPermits! (Because the trapezoid has double the area of the rectangle * of height stableInterval and equivalent width). We decided that the "cooldown period" * time should be equivalent to "warmup period", thus a fully saturated RateLimiter * (with zero stored permits, serving only fresh ones) can go to a fully unsaturated * (with storedPermits == maxPermits) in the same amount of time it takes for a fully * unsaturated RateLimiter to return to the stableInterval -- which happens in halfPermits, * since beyond that point, we use a horizontal line of "stableInterval" height, simulating * the regular rate. * * Thus, we have figured all dimensions of this shape, to give all the desired * properties: * - the width is warmupPeriod / stableInterval, to make cooldownPeriod == warmupPeriod * - the slope starts at the middle, and goes from stableInterval to 3*stableInterval so * to have halfPermits being spend in double the usual time (half the rate), while their * respective rate is steadily ramping up */ private static class WarmingUp extends RateLimiter { final long warmupPeriodMicros; /** * The slope of the line from the stable interval (when permits == 0), to the cold interval * (when permits == maxPermits) */ private double slope; private double halfPermits; WarmingUp(SleepingTicker ticker, long warmupPeriod, TimeUnit timeUnit) { super(ticker); this.warmupPeriodMicros = timeUnit.toMicros(warmupPeriod); } @Override void doSetRate(double permitsPerSecond, double stableIntervalMicros) { double oldMaxPermits = maxPermits; maxPermits = warmupPeriodMicros / stableIntervalMicros; halfPermits = maxPermits / 2.0; // Stable interval is x, cold is 3x, so on average it's 2x. Double the time -> halve the rate double coldIntervalMicros = stableIntervalMicros * 3.0; slope = (coldIntervalMicros - stableIntervalMicros) / halfPermits; if (oldMaxPermits == Double.POSITIVE_INFINITY) { // if we don't special-case this, we would get storedPermits == NaN, below storedPermits = 0.0; } else { storedPermits = (oldMaxPermits == 0.0) ? maxPermits // initial state is cold : storedPermits * maxPermits / oldMaxPermits; } } @Override long storedPermitsToWaitTime(double storedPermits, double permitsToTake) { double availablePermitsAboveHalf = storedPermits - halfPermits; long micros = 0; // measuring the integral on the right part of the function (the climbing line) if (availablePermitsAboveHalf > 0.0) { double permitsAboveHalfToTake = Math.min(availablePermitsAboveHalf, permitsToTake); micros = (long) (permitsAboveHalfToTake * (permitsToTime(availablePermitsAboveHalf) + permitsToTime(availablePermitsAboveHalf - permitsAboveHalfToTake)) / 2.0); permitsToTake -= permitsAboveHalfToTake; } // measuring the integral on the left part of the function (the horizontal line) micros += (stableIntervalMicros * permitsToTake); return micros; } private double permitsToTime(double permits) { return stableIntervalMicros + permits * slope; } } /** * This implements a "bursty" RateLimiter, where storedPermits are translated to * zero throttling. The maximum number of permits that can be saved (when the RateLimiter is * unused) is defined in terms of time, in this sense: if a RateLimiter is 2qps, and this * time is specified as 10 seconds, we can save up to 2 * 10 = 20 permits. */ private static class Bursty extends RateLimiter { /** The work (permits) of how many seconds can be saved up if this RateLimiter is unused? */ final double maxBurstSeconds; Bursty(SleepingTicker ticker, double maxBurstSeconds) { super(ticker); this.maxBurstSeconds = maxBurstSeconds; } @Override void doSetRate(double permitsPerSecond, double stableIntervalMicros) { double oldMaxPermits = this.maxPermits; maxPermits = maxBurstSeconds * permitsPerSecond; storedPermits = (oldMaxPermits == 0.0) ? 0.0 // initial state : storedPermits * maxPermits / oldMaxPermits; } @Override long storedPermitsToWaitTime(double storedPermits, double permitsToTake) { return 0L; } } @VisibleForTesting static abstract class SleepingTicker extends Ticker { abstract void sleepMicrosUninterruptibly(long micros); static final SleepingTicker SYSTEM_TICKER = new SleepingTicker() { @Override public long read() { return systemTicker().read(); } @Override public void sleepMicrosUninterruptibly(long micros) { if (micros > 0) { Uninterruptibles.sleepUninterruptibly(micros, TimeUnit.MICROSECONDS); } } }; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.Beta; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * A delegating wrapper around a {@link ListenableFuture} that adds support for * the {@link #checkedGet()} and {@link #checkedGet(long, TimeUnit)} methods. * * @author Sven Mawson * @since 1.0 */ @Beta public abstract class AbstractCheckedFuture<V, X extends Exception> extends ForwardingListenableFuture.SimpleForwardingListenableFuture<V> implements CheckedFuture<V, X> { /** * Constructs an {@code AbstractCheckedFuture} that wraps a delegate. */ protected AbstractCheckedFuture(ListenableFuture<V> delegate) { super(delegate); } /** * Translates from an {@link InterruptedException}, * {@link CancellationException} or {@link ExecutionException} thrown by * {@code get} to an exception of type {@code X} to be thrown by * {@code checkedGet}. Subclasses must implement this method. * * <p>If {@code e} is an {@code InterruptedException}, the calling * {@code checkedGet} method has already restored the interrupt after catching * the exception. If an implementation of {@link #mapException(Exception)} * wishes to swallow the interrupt, it can do so by calling * {@link Thread#interrupted()}. * * <p>Subclasses may choose to throw, rather than return, a subclass of * {@code RuntimeException} to allow creating a CheckedFuture that throws * both checked and unchecked exceptions. */ protected abstract X mapException(Exception e); /** * {@inheritDoc} * * <p>This implementation calls {@link #get()} and maps that method's standard * exceptions to instances of type {@code X} using {@link #mapException}. * * <p>In addition, if {@code get} throws an {@link InterruptedException}, this * implementation will set the current thread's interrupt status before * calling {@code mapException}. * * @throws X if {@link #get()} throws an {@link InterruptedException}, * {@link CancellationException}, or {@link ExecutionException} */ @Override public V checkedGet() throws X { try { return get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw mapException(e); } catch (CancellationException e) { throw mapException(e); } catch (ExecutionException e) { throw mapException(e); } } /** * {@inheritDoc} * * <p>This implementation calls {@link #get(long, TimeUnit)} and maps that * method's standard exceptions (excluding {@link TimeoutException}, which is * propagated) to instances of type {@code X} using {@link #mapException}. * * <p>In addition, if {@code get} throws an {@link InterruptedException}, this * implementation will set the current thread's interrupt status before * calling {@code mapException}. * * @throws X if {@link #get()} throws an {@link InterruptedException}, * {@link CancellationException}, or {@link ExecutionException} * @throws TimeoutException {@inheritDoc} */ @Override public V checkedGet(long timeout, TimeUnit unit) throws TimeoutException, X { try { return get(timeout, unit); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw mapException(e); } catch (CancellationException e) { throw mapException(e); } catch (ExecutionException e) { throw mapException(e); } } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import javax.annotation.Nullable; /** * A {@link ListenableFuture} whose result may be set by a {@link #set(Object)} * or {@link #setException(Throwable)} call. It may also be cancelled. * * @author Sven Mawson * @since 9.0 (in 1.0 as {@code ValueFuture}) */ public final class SettableFuture<V> extends AbstractFuture<V> { /** * Creates a new {@code SettableFuture} in the default state. */ public static <V> SettableFuture<V> create() { return new SettableFuture<V>(); } /** * Explicit private constructor, use the {@link #create} factory method to * create instances of {@code SettableFuture}. */ private SettableFuture() {} /** * Sets the value of this future. This method will return {@code true} if * the value was successfully set, or {@code false} if the future has already * been set or cancelled. * * @param value the value the future should hold. * @return true if the value was successfully set. */ @Override public boolean set(@Nullable V value) { return super.set(value); } /** * Sets the future to having failed with the given exception. This exception * will be wrapped in an {@code ExecutionException} and thrown from the {@code * get} methods. This method will return {@code true} if the exception was * successfully set, or {@code false} if the future has already been set or * cancelled. * * @param throwable the exception the future should hold. * @return true if the exception was successfully set. */ @Override public boolean setException(Throwable throwable) { return super.setException(throwable); } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * A future which forwards all its method calls to another future. Subclasses * should override one or more methods to modify the behavior of the backing * future as desired per the <a href= * "http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p>Most subclasses can simply extend {@link SimpleForwardingCheckedFuture}. * * @param <V> The result type returned by this Future's {@code get} method * @param <X> The type of the Exception thrown by the Future's * {@code checkedGet} method * * @author Anthony Zana * @since 9.0 */ @Beta public abstract class ForwardingCheckedFuture<V, X extends Exception> extends ForwardingListenableFuture<V> implements CheckedFuture<V, X> { @Override public V checkedGet() throws X { return delegate().checkedGet(); } @Override public V checkedGet(long timeout, TimeUnit unit) throws TimeoutException, X { return delegate().checkedGet(timeout, unit); } @Override protected abstract CheckedFuture<V, X> delegate(); // TODO(cpovirk): Use Standard Javadoc form for SimpleForwarding* /** * A simplified version of {@link ForwardingCheckedFuture} where subclasses * can pass in an already constructed {@link CheckedFuture} as the delegate. * * @since 9.0 */ @Beta public abstract static class SimpleForwardingCheckedFuture< V, X extends Exception> extends ForwardingCheckedFuture<V, X> { private final CheckedFuture<V, X> delegate; protected SimpleForwardingCheckedFuture(CheckedFuture<V, X> delegate) { this.delegate = Preconditions.checkNotNull(delegate); } @Override protected final CheckedFuture<V, X> delegate() { return delegate; } } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.Beta; import 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) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.GwtCompatible; import javax.annotation.Nullable; /** * 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 */ @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(@Nullable String message) { super(message); } /** * Creates a new instance with the given detail message and cause. */ public UncheckedExecutionException(@Nullable String message, @Nullable Throwable cause) { super(message, cause); } /** * Creates a new instance with the given cause. */ public UncheckedExecutionException(@Nullable Throwable cause) { super(cause); } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; 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.ThreadFactory; 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> * * <p>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> * * <p>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 = MoreExecutors.renamingDecorator(executor(), new Supplier<String>() { @Override public String get() { return serviceName() + " " + state(); } }); 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); } } }); } }; /** Constructor for use by subclasses. */ protected AbstractScheduledService() {} /** * 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 sets the name of the thread to the {@linkplain #serviceName() service name}. * Also, the pool will be {@linkplain ScheduledExecutorService#shutdown() shut down} when the * service {@linkplain Service.State#TERMINATED terminates} or * {@linkplain Service.State#TERMINATED fails}. */ protected ScheduledExecutorService executor() { final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor( new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { return MoreExecutors.newThread(serviceName(), runnable); } }); // 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 terminated(State from) { executor.shutdown(); } @Override public void failed(State from, Throwable failure) { executor.shutdown(); }}, MoreExecutors.sameThreadExecutor()); return executor; } /** * Returns the name of this service. {@link AbstractScheduledService} may include the name in * debugging output. * * @since 14.0 */ protected String serviceName() { return getClass().getSimpleName(); } @Override public String toString() { return serviceName() + " [" + 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(); } /** * @since 13.0 */ @Override public final void addListener(Listener listener, Executor executor) { delegate.addListener(listener, executor); } /** * @since 14.0 */ @Override public final Throwable failureCause() { return delegate.failureCause(); } /** * A {@link Scheduler} that provides a convenient way for the {@link AbstractScheduledService} to * use a dynamically changing schedule. After every execution of the task, assuming it hasn't * been cancelled, the {@link #getNextSchedule} method will be called. * * @author Luke Sandberg * @since 11.0 */ @Beta public abstract static class CustomScheduler extends Scheduler { /** * A callable class that can reschedule itself using a {@link CustomScheduler}. */ private class ReschedulableCallable extends ForwardingFuture<Void> implements Callable<Void> { /** The underlying task. */ private final Runnable wrappedRunnable; /** The executor on which this Callable will be scheduled. */ private final ScheduledExecutorService executor; /** * The service that is managing this callable. This is used so that failure can be * reported properly. */ private final AbstractService service; /** * This lock is used to ensure safe and correct cancellation, it ensures that a new task is * not scheduled while a cancel is ongoing. Also it protects the currentFuture variable to * ensure that it is assigned atomically with being scheduled. */ private final ReentrantLock lock = new ReentrantLock(); /** The future that represents the next execution of this task.*/ @GuardedBy("lock") private Future<Void> currentFuture; ReschedulableCallable(AbstractService service, ScheduledExecutorService executor, Runnable runnable) { this.wrappedRunnable = runnable; this.executor = executor; this.service = service; } @Override public Void call() throws Exception { wrappedRunnable.run(); reschedule(); return null; } /** * Atomically reschedules this task and assigns the new future to {@link #currentFuture}. */ public void reschedule() { // We reschedule ourselves with a lock held for two reasons. 1. we want to make sure that // cancel calls cancel on the correct future. 2. we want to make sure that the assignment // to currentFuture doesn't race with itself so that currentFuture is assigned in the // correct order. lock.lock(); try { if (currentFuture == null || !currentFuture.isCancelled()) { final Schedule schedule = CustomScheduler.this.getNextSchedule(); currentFuture = executor.schedule(this, schedule.delay, schedule.unit); } } catch (Throwable e) { // If an exception is thrown by the subclass then we need to make sure that the service // notices and transitions to the FAILED state. We do it by calling notifyFailed directly // because the service does not monitor the state of the future so if the exception is not // caught and forwarded to the service the task would stop executing but the service would // have no idea. service.notifyFailed(e); } finally { lock.unlock(); } } // N.B. Only protect cancel and isCancelled because those are the only methods that are // invoked by the AbstractScheduledService. @Override public boolean cancel(boolean mayInterruptIfRunning) { // Ensure that a task cannot be rescheduled while a cancel is ongoing. lock.lock(); try { return currentFuture.cancel(mayInterruptIfRunning); } finally { lock.unlock(); } } @Override protected Future<Void> delegate() { throw new UnsupportedOperationException("Only cancel is supported by this future"); } } @Override final Future<?> schedule(AbstractService service, ScheduledExecutorService executor, Runnable runnable) { ReschedulableCallable task = new ReschedulableCallable(service, executor, runnable); task.reschedule(); return task; } /** * A value object that represents an absolute delay until a task should be invoked. * * @author Luke Sandberg * @since 11.0 */ @Beta protected static final class Schedule { private final long delay; private final TimeUnit unit; /** * @param delay the time from now to delay execution * @param unit the time unit of the delay parameter */ public Schedule(long delay, TimeUnit unit) { this.delay = delay; this.unit = Preconditions.checkNotNull(unit); } } /** * Calculates the time at which to next invoke the task. * * <p>This is guaranteed to be called immediately after the task has completed an iteration and * on the same thread as the previous execution of {@link * AbstractScheduledService#runOneIteration}. * * @return a schedule that defines the delay before the next execution. */ protected abstract Schedule getNextSchedule() throws Exception; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import java.util.concurrent.Executor; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; /** * <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. @VisibleForTesting static final Logger log = Logger.getLogger(ExecutionList.class.getName()); /** * The runnable, executor pairs to execute. This acts as a stack threaded through the * {@link RunnableExecutorPair#next} field. */ @GuardedBy("this") private RunnableExecutorPair runnables; @GuardedBy("this") private boolean executed; /** 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."); // 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 (this) { if (!executed) { runnables = new RunnableExecutorPair(runnable, executor, runnables); return; } } // 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. executeListener(runnable, executor); } /** * 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. RunnableExecutorPair list; synchronized (this) { if (executed) { return; } executed = true; list = runnables; runnables = null; // allow GC to free listeners even if this stays around for a while. } // If we succeeded then list holds all the runnables we to execute. The pairs in the stack are // in the opposite order from how they were added so we need to reverse the list to fulfill our // contract. // This is somewhat annoying, but turns out to be very fast in practice. Alternatively, we // could drop the contract on the method that enforces this queue like behavior since depending // on it is likely to be a bug anyway. // N.B. All writes to the list and the next pointers must have happened before the above // synchronized block, so we can iterate the list without the lock held here. RunnableExecutorPair reversedList = null; while (list != null) { RunnableExecutorPair tmp = list; list = list.next; tmp.next = reversedList; reversedList = tmp; } while (reversedList != null) { executeListener(reversedList.runnable, reversedList.executor); reversedList = reversedList.next; } } /** * Submits the given runnable to the given {@link Executor} catching and logging all * {@linkplain RuntimeException runtime exceptions} thrown by the executor. */ private static void executeListener(Runnable runnable, Executor executor) { 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); } } private static final class RunnableExecutorPair { final Runnable runnable; final Executor executor; @Nullable RunnableExecutorPair next; RunnableExecutorPair(Runnable runnable, Executor executor, RunnableExecutorPair next) { this.runnable = runnable; this.executor = executor; this.next = next; } } }
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 static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly; 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 * 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 { /* * Threads from our private pool are never interrupted. Threads * from a user-supplied executor might be, but... what can we do? * This is another reason to return a proper ListenableFuture * instead of using listenInPoolThread. */ getUninterruptibly(delegate); } catch (Error e) { throw e; } catch (Throwable e) { // ExecutionException / CancellationException / RuntimeException // The task is done, run the listeners. } executionList.execute(); } }); } } } private JdkFutureAdapters() {} }
Java
/* * Copyright (C) 2013 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.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * An abstract {@code ScheduledExecutorService} that allows subclasses to * {@linkplain #wrapTask(Callable) wrap} tasks before they are submitted to the underlying executor. * * <p>Note that task wrapping may occur even if the task is never executed. * * @author Luke Sandberg */ abstract class WrappingScheduledExecutorService extends WrappingExecutorService implements ScheduledExecutorService { final ScheduledExecutorService delegate; WrappingScheduledExecutorService(ScheduledExecutorService delegate) { super(delegate); this.delegate = delegate; } @Override public final ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return delegate.schedule(wrapTask(command), delay, unit); } @Override public final <V> ScheduledFuture<V> schedule(Callable<V> task, long delay, TimeUnit unit) { return delegate.schedule(wrapTask(task), delay, unit); } @Override public final ScheduledFuture<?> scheduleAtFixedRate( Runnable command, long initialDelay, long period, TimeUnit unit) { return delegate.scheduleAtFixedRate(wrapTask(command), initialDelay, period, unit); } @Override public final ScheduledFuture<?> scheduleWithFixedDelay( Runnable command, long initialDelay, long delay, TimeUnit unit) { return delegate.scheduleWithFixedDelay(wrapTask(command), initialDelay, delay, unit); } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.GwtCompatible; import javax.annotation.Nullable; /** * {@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 */ @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(@Nullable String message) { super(message); } /** * Creates a new instance with the given detail message and cause. */ public ExecutionError(@Nullable String message, @Nullable Error cause) { super(message, cause); } /** * Creates a new instance with the given cause. */ public ExecutionError(@Nullable Error cause) { super(cause); } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import 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 */ 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) 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.AbstractExecutorService; import java.util.concurrent.Callable; import javax.annotation.Nullable; /** * Abstract {@link ListeningExecutorService} implementation that creates * {@link ListenableFutureTask} instances for each {@link Runnable} and {@link Callable} submitted * to it. These tasks are run with the abstract {@link #execute execute(Runnable)} method. * * <p>In addition to {@link #execute}, subclasses must implement all methods related to shutdown and * termination. * * @author Chris Povirk * @since 14.0 */ @Beta public abstract class AbstractListeningExecutorService extends AbstractExecutorService implements ListeningExecutorService { @Override protected final <T> ListenableFutureTask<T> newTaskFor(Runnable runnable, T value) { return ListenableFutureTask.create(runnable, value); } @Override protected final <T> ListenableFutureTask<T> newTaskFor(Callable<T> callable) { return ListenableFutureTask.create(callable); } @Override public ListenableFuture<?> submit(Runnable task) { return (ListenableFuture<?>) super.submit(task); } @Override public <T> ListenableFuture<T> submit(Runnable task, @Nullable T result) { return (ListenableFuture<T>) super.submit(task, result); } @Override public <T> ListenableFuture<T> submit(Callable<T> task) { return (ListenableFuture<T>) super.submit(task); } }
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.Callable; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * A {@link ScheduledExecutorService} that returns {@link ListenableFuture} * instances from its {@code ExecutorService} methods. To create an instance * from an existing {@link ScheduledExecutorService}, call * {@link MoreExecutors#listeningDecorator(ScheduledExecutorService)}. * * @author Chris Povirk * @since 10.0 */ @Beta public interface ListeningScheduledExecutorService extends ScheduledExecutorService, ListeningExecutorService { /** @since 15.0 (previously returned ScheduledFuture) */ @Override ListenableScheduledFuture<?> schedule( Runnable command, long delay, TimeUnit unit); /** @since 15.0 (previously returned ScheduledFuture) */ @Override <V> ListenableScheduledFuture<V> schedule( Callable<V> callable, long delay, TimeUnit unit); /** @since 15.0 (previously returned ScheduledFuture) */ @Override ListenableScheduledFuture<?> scheduleAtFixedRate( Runnable command, long initialDelay, long period, TimeUnit unit); /** @since 15.0 (previously returned ScheduledFuture) */ @Override ListenableScheduledFuture<?> scheduleWithFixedDelay( Runnable command, long initialDelay, long delay, TimeUnit unit); }
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.Supplier; 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 { /* Thread names will look like {@code "MyService STARTING"}. */ private final Supplier<String> threadNameSupplier = new Supplier<String>() { @Override public String get() { return serviceName() + " " + state(); } }; /* use AbstractService for state management */ private final Service delegate = new AbstractService() { @Override protected final void doStart() { MoreExecutors.renamingDecorator(executor(), threadNameSupplier) .execute(new Runnable() { @Override public void run() { try { startUp(); notifyStarted(); } catch (Throwable t) { notifyFailed(t); throw Throwables.propagate(t); } } }); } @Override protected final void doStop() { MoreExecutors.renamingDecorator(executor(), threadNameSupplier) .execute(new Runnable() { @Override public void run() { try { shutDown(); notifyStopped(); } catch (Throwable t) { notifyFailed(t); throw Throwables.propagate(t); } } }); } }; /** Constructor for use by subclasses. */ protected AbstractIdleService() {} /** 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. */ protected Executor executor() { return new Executor() { @Override public void execute(Runnable command) { MoreExecutors.newThread(threadNameSupplier.get(), command).start(); } }; } @Override public String toString() { return serviceName() + " [" + 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(); } /** * @since 13.0 */ @Override public final void addListener(Listener listener, Executor executor) { delegate.addListener(listener, executor); } /** * @since 14.0 */ @Override public final Throwable failureCause() { return delegate.failureCause(); } /** * Returns the name of this service. {@link AbstractIdleService} may include the name in debugging * output. * * @since 14.0 */ protected String serviceName() { return getClass().getSimpleName(); } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import java.util.concurrent.Callable; /** * A listening executor service which forwards all its method calls to another * listening executor service. Subclasses should override one or more methods to * modify the behavior of the backing executor service as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Isaac Shum * @since 10.0 */ public abstract class ForwardingListeningExecutorService extends ForwardingExecutorService implements ListeningExecutorService { /** Constructor for use by subclasses. */ protected ForwardingListeningExecutorService() {} @Override protected abstract ListeningExecutorService delegate(); @Override public <T> ListenableFuture<T> submit(Callable<T> task) { return delegate().submit(task); } @Override public ListenableFuture<?> submit(Runnable task) { return delegate().submit(task); } @Override public <T> ListenableFuture<T> submit(Runnable task, T result) { return delegate().submit(task, result); } }
Java
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import 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 */ public final class Atomics { private Atomics() {} /** * Creates an {@code AtomicReference} instance with no initial value. * * @return a new {@code AtomicReference} with no initial value */ public static <V> AtomicReference<V> newReference() { return new AtomicReference<V>(); } /** * Creates an {@code AtomicReference} instance with the given initial value. * * @param initialValue the initial value * @return a new {@code AtomicReference} with the given initial value */ public static <V> AtomicReference<V> newReference(@Nullable V initialValue) { return new AtomicReference<V>(initialValue); } /** * Creates an {@code AtomicReferenceArray} instance of given length. * * @param length the length of the array * @return a new {@code AtomicReferenceArray} with the given length */ public static <E> AtomicReferenceArray<E> newReferenceArray(int length) { return new AtomicReferenceArray<E>(length); } /** * Creates an {@code AtomicReferenceArray} instance with the same length as, * and all elements copied from, the given array. * * @param array the array to copy elements from * @return a new {@code AtomicReferenceArray} copied from the given array */ public static <E> AtomicReferenceArray<E> newReferenceArray(E[] array) { return new AtomicReferenceArray<E>(array); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.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.util.concurrent.Service.State; // javadoc needs this import java.util.List; 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 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 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 calling * {@link ExecutionQueue#execute()} should not be protected. */ private final ExecutionQueue queuedListeners = new ExecutionQueue(); /** * 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); /** Constructor for use by subclasses. */ 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 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 (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 { State previous = state(); switch (previous) { 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: " + previous); } } 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 { // We have to examine the internal state of the snapshot here to properly handle the stop // while starting case. 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 { // We check the internal state of the snapshot instead of state() directly so we don't allow // notifyStopped() to be called while STARTING, even if stop() has already been called. State previous = snapshot.state; if (previous != State.STOPPING && previous != State.RUNNING) { IllegalStateException failure = new IllegalStateException( "Cannot notifyStopped() when the service is " + previous); notifyFailed(failure); throw failure; } 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 { State previous = state(); switch (previous) { case NEW: case TERMINATED: throw new IllegalStateException("Failed while in state:" + previous, cause); case RUNNING: case STARTING: case STOPPING: snapshot = new StateSnapshot(State.FAILED, false, cause); failed(previous, cause); break; case FAILED: // Do nothing break; default: throw new AssertionError("Unexpected state: " + previous); } } finally { lock.unlock(); executeListeners(); } } @Override public final boolean isRunning() { return state() == State.RUNNING; } @Override public final State state() { return snapshot.externalState(); } /** * @since 14.0 */ @Override public final Throwable failureCause() { return snapshot.failureCause(); } /** * @since 13.0 */ @Override public final void addListener(Listener listener, Executor executor) { checkNotNull(listener, "listener"); checkNotNull(executor, "executor"); lock.lock(); try { State currentState = state(); if (currentState != State.TERMINATED && currentState != 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()) { queuedListeners.execute(); } } @GuardedBy("lock") private void starting() { for (final ListenerExecutorPair pair : listeners) { queuedListeners.add(new Runnable() { @Override public void run() { pair.listener.starting(); } }, pair.executor); } } @GuardedBy("lock") private void running() { for (final ListenerExecutorPair pair : listeners) { queuedListeners.add(new Runnable() { @Override public void run() { pair.listener.running(); } }, pair.executor); } } @GuardedBy("lock") private void stopping(final State from) { for (final ListenerExecutorPair pair : listeners) { queuedListeners.add(new Runnable() { @Override public void run() { pair.listener.stopping(from); } }, pair.executor); } } @GuardedBy("lock") private void terminated(final State from) { for (final ListenerExecutorPair pair : listeners) { queuedListeners.add(new Runnable() { @Override public void run() { pair.listener.terminated(from); } }, pair.executor); } // 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.listener.failed(from, cause); } }, pair.executor); } // 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; } } /** * 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.base.Supplier; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.collect.Queues; import com.google.common.util.concurrent.ForwardingListenableFuture.SimpleForwardingListenableFuture; import java.lang.reflect.InvocationTargetException; 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.Delayed; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; 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) { checkNotNull(service); checkNotNull(timeUnit); addShutdownHook(MoreExecutors.newThread("DelayedShutdownHook-for-" + service, 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. } } })); } 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 * ListeningScheduledExecutorService} 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 * ListeningScheduledExecutorService}. * * <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 { private 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 ListenableScheduledFuture<?> schedule( Runnable command, long delay, TimeUnit unit) { ListenableFutureTask<Void> task = ListenableFutureTask.create(command, null); ScheduledFuture<?> scheduled = delegate.schedule(task, delay, unit); return new ListenableScheduledTask<Void>(task, scheduled); } @Override public <V> ListenableScheduledFuture<V> schedule( Callable<V> callable, long delay, TimeUnit unit) { ListenableFutureTask<V> task = ListenableFutureTask.create(callable); ScheduledFuture<?> scheduled = delegate.schedule(task, delay, unit); return new ListenableScheduledTask<V>(task, scheduled); } @Override public ListenableScheduledFuture<?> scheduleAtFixedRate( Runnable command, long initialDelay, long period, TimeUnit unit) { NeverSuccessfulListenableFutureTask task = new NeverSuccessfulListenableFutureTask(command); ScheduledFuture<?> scheduled = delegate.scheduleAtFixedRate(task, initialDelay, period, unit); return new ListenableScheduledTask<Void>(task, scheduled); } @Override public ListenableScheduledFuture<?> scheduleWithFixedDelay( Runnable command, long initialDelay, long delay, TimeUnit unit) { NeverSuccessfulListenableFutureTask task = new NeverSuccessfulListenableFutureTask(command); ScheduledFuture<?> scheduled = delegate.scheduleWithFixedDelay(task, initialDelay, delay, unit); return new ListenableScheduledTask<Void>(task, scheduled); } private static final class ListenableScheduledTask<V> extends SimpleForwardingListenableFuture<V> implements ListenableScheduledFuture<V> { private final ScheduledFuture<?> scheduledDelegate; public ListenableScheduledTask( ListenableFuture<V> listenableDelegate, ScheduledFuture<?> scheduledDelegate) { super(listenableDelegate); this.scheduledDelegate = scheduledDelegate; } @Override public boolean cancel(boolean mayInterruptIfRunning) { boolean cancelled = super.cancel(mayInterruptIfRunning); if (cancelled) { // Unless it is cancelled, the delegate may continue being scheduled scheduledDelegate.cancel(mayInterruptIfRunning); // TODO(user): Cancel "this" if "scheduledDelegate" is cancelled. } return cancelled; } @Override public long getDelay(TimeUnit unit) { return scheduledDelegate.getDelay(unit); } @Override public int compareTo(Delayed other) { return scheduledDelegate.compareTo(other); } } private static final class NeverSuccessfulListenableFutureTask extends AbstractFuture<Void> implements Runnable { private final Runnable delegate; public NeverSuccessfulListenableFutureTask(Runnable delegate) { this.delegate = checkNotNull(delegate); } @Override public void run() { try { delegate.run(); } catch (Throwable t) { setException(t); throw Throwables.propagate(t); } } } } /* * 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 { checkNotNull(executorService); 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; } /** * Returns a default thread factory used to create new threads. * * <p>On AppEngine, returns {@code ThreadManager.currentRequestThreadFactory()}. * Otherwise, returns {@link Executors#defaultThreadFactory()}. * * @since 14.0 */ @Beta public static ThreadFactory platformThreadFactory() { if (!isAppEngine()) { return Executors.defaultThreadFactory(); } try { return (ThreadFactory) Class.forName("com.google.appengine.api.ThreadManager") .getMethod("currentRequestThreadFactory") .invoke(null); } catch (IllegalAccessException e) { throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); } catch (ClassNotFoundException e) { throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); } catch (NoSuchMethodException e) { throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); } catch (InvocationTargetException e) { throw Throwables.propagate(e.getCause()); } } private static boolean isAppEngine() { if (System.getProperty("com.google.appengine.runtime.environment") == null) { return false; } try { // If the current environment is null, we're not inside AppEngine. return Class.forName("com.google.apphosting.api.ApiProxy") .getMethod("getCurrentEnvironment") .invoke(null) != null; } catch (ClassNotFoundException e) { // If ApiProxy doesn't exist, we're not on AppEngine at all. return false; } catch (InvocationTargetException e) { // If ApiProxy throws an exception, we're not in a proper AppEngine environment. return false; } catch (IllegalAccessException e) { // If the method isn't accessible, we're not on a supported version of AppEngine; return false; } catch (NoSuchMethodException e) { // If the method doesn't exist, we're not on a supported version of AppEngine; return false; } } /** * Creates a thread using {@link #platformThreadFactory}, and sets its name to {@code name} * unless changing the name is forbidden by the security manager. */ static Thread newThread(String name, Runnable runnable) { checkNotNull(name); checkNotNull(runnable); Thread result = platformThreadFactory().newThread(runnable); try { result.setName(name); } catch (SecurityException e) { // OK if we can't set the name in this environment. } return result; } // TODO(user): provide overloads for ListeningExecutorService? ListeningScheduledExecutorService? // TODO(user): provide overloads that take constant strings? Function<Runnable, String>s to // calculate names? /** * Creates an {@link Executor} that renames the {@link Thread threads} that its tasks run in. * * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed * right before each task is run. The renaming is best effort, if a {@link SecurityManager} * prevents the renaming then it will be skipped but the tasks will still execute. * * @param executor The executor to decorate * @param nameSupplier The source of names for each task */ static Executor renamingDecorator(final Executor executor, final Supplier<String> nameSupplier) { checkNotNull(executor); checkNotNull(nameSupplier); if (isAppEngine()) { // AppEngine doesn't support thread renaming, so don't even try return executor; } return new Executor() { @Override public void execute(Runnable command) { executor.execute(Callables.threadRenaming(command, nameSupplier)); } }; } /** * Creates an {@link ExecutorService} that renames the {@link Thread threads} that its tasks run * in. * * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed * right before each task is run. The renaming is best effort, if a {@link SecurityManager} * prevents the renaming then it will be skipped but the tasks will still execute. * * @param service The executor to decorate * @param nameSupplier The source of names for each task */ static ExecutorService renamingDecorator(final ExecutorService service, final Supplier<String> nameSupplier) { checkNotNull(service); checkNotNull(nameSupplier); if (isAppEngine()) { // AppEngine doesn't support thread renaming, so don't even try. return service; } return new WrappingExecutorService(service) { @Override protected <T> Callable<T> wrapTask(Callable<T> callable) { return Callables.threadRenaming(callable, nameSupplier); } @Override protected Runnable wrapTask(Runnable command) { return Callables.threadRenaming(command, nameSupplier); } }; } /** * Creates a {@link ScheduledExecutorService} that renames the {@link Thread threads} that its * tasks run in. * * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed * right before each task is run. The renaming is best effort, if a {@link SecurityManager} * prevents the renaming then it will be skipped but the tasks will still execute. * * @param service The executor to decorate * @param nameSupplier The source of names for each task */ static ScheduledExecutorService renamingDecorator(final ScheduledExecutorService service, final Supplier<String> nameSupplier) { checkNotNull(service); checkNotNull(nameSupplier); if (isAppEngine()) { // AppEngine doesn't support thread renaming, so don't even try. return service; } return new WrappingScheduledExecutorService(service) { @Override protected <T> Callable<T> wrapTask(Callable<T> callable) { return Callables.threadRenaming(callable, nameSupplier); } @Override protected Runnable wrapTask(Runnable command) { return Callables.threadRenaming(command, nameSupplier); } }; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.io.FileWriteMode.APPEND; import com.google.common.annotations.Beta; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.TreeTraverser; import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Provides utility methods for working with files. * * <p>All method parameters must be non-null unless documented otherwise. * * @author Chris Nokleberg * @author Colin Decker * @since 1.0 */ @Beta public final class Files { /** Maximum loop count when creating temp directories. */ private static final int TEMP_DIR_ATTEMPTS = 10000; private Files() {} /** * Returns a buffered reader that reads from a file using the given * character set. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link * Charsets} for helpful predefined constants * @return the buffered reader */ public static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException { checkNotNull(file); checkNotNull(charset); return new BufferedReader( new InputStreamReader(new FileInputStream(file), charset)); } /** * Returns a buffered writer that writes to a file using the given * character set. * * @param file the file to write to * @param charset the charset used to encode the output stream; see {@link * Charsets} for helpful predefined constants * @return the buffered writer */ public static BufferedWriter newWriter(File file, Charset charset) throws FileNotFoundException { checkNotNull(file); checkNotNull(charset); return new BufferedWriter( new OutputStreamWriter(new FileOutputStream(file), charset)); } /** * Returns a new {@link ByteSource} for reading bytes from the given file. * * @since 14.0 */ public static ByteSource asByteSource(File file) { return new FileByteSource(file); } private static final class FileByteSource extends ByteSource { private final File file; private FileByteSource(File file) { this.file = checkNotNull(file); } @Override public FileInputStream openStream() throws IOException { return new FileInputStream(file); } @Override public long size() throws IOException { if (!file.isFile()) { throw new FileNotFoundException(file.toString()); } return file.length(); } @Override public byte[] read() throws IOException { long size = file.length(); // some special files may return size 0 but have content // read normally to be sure if (size == 0) { return super.read(); } // can't initialize a large enough array // technically, this could probably be Integer.MAX_VALUE - 5 if (size > Integer.MAX_VALUE) { // OOME is what would be thrown if we tried to initialize the array throw new OutOfMemoryError("file is too large to fit in a byte array: " + size + " bytes"); } // initialize the array to the current size of the file byte[] bytes = new byte[(int) size]; Closer closer = Closer.create(); try { InputStream in = closer.register(openStream()); int off = 0; int read = 0; // read until we've read size bytes or reached EOF while (off < size && ((read = in.read(bytes, off, (int) size - off)) != -1)) { off += read; } if (off < size) { // encountered EOF early; truncate the result return Arrays.copyOf(bytes, off); } // otherwise, exactly size bytes were read int b = in.read(); // check for EOF if (b == -1) { // EOF; the file did not change size, so return the original array return bytes; } // the file got larger, so read the rest normally InternalByteArrayOutputStream out = new InternalByteArrayOutputStream(); out.write(b); // write the byte we read when testing for EOF ByteStreams.copy(in, out); byte[] result = new byte[bytes.length + out.size()]; System.arraycopy(bytes, 0, result, 0, bytes.length); out.writeTo(result, bytes.length); return result; } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } @Override public String toString() { return "Files.asByteSource(" + file + ")"; } } /** * BAOS subclass for direct access to its internal buffer. */ private static final class InternalByteArrayOutputStream extends ByteArrayOutputStream { /** * Writes the contents of the internal buffer to the given array starting * at the given offset. Assumes the array has space to hold count bytes. */ void writeTo(byte[] b, int off) { System.arraycopy(buf, 0, b, off, count); } } /** * Returns a new {@link ByteSink} for writing bytes to the given file. The * given {@code modes} control how the file is opened for writing. When no * mode is provided, the file will be truncated before writing. When the * {@link FileWriteMode#APPEND APPEND} mode is provided, writes will * append to the end of the file without truncating it. * * @since 14.0 */ public static ByteSink asByteSink(File file, FileWriteMode... modes) { return new FileByteSink(file, modes); } private static final class FileByteSink extends ByteSink { private final File file; private final ImmutableSet<FileWriteMode> modes; private FileByteSink(File file, FileWriteMode... modes) { this.file = checkNotNull(file); this.modes = ImmutableSet.copyOf(modes); } @Override public FileOutputStream openStream() throws IOException { return new FileOutputStream(file, modes.contains(APPEND)); } @Override public String toString() { return "Files.asByteSink(" + file + ", " + modes + ")"; } } /** * Returns a new {@link CharSource} for reading character data from the given * file using the given character set. * * @since 14.0 */ public static CharSource asCharSource(File file, Charset charset) { return asByteSource(file).asCharSource(charset); } /** * Returns a new {@link CharSink} for writing character data to the given * file using the given character set. The given {@code modes} control how * the file is opened for writing. When no mode is provided, the file * will be truncated before writing. When the * {@link FileWriteMode#APPEND APPEND} mode is provided, writes will * append to the end of the file without truncating it. * * @since 14.0 */ public static CharSink asCharSink(File file, Charset charset, FileWriteMode... modes) { return asByteSink(file, modes).asCharSink(charset); } /** * Returns a factory that will supply instances of {@link FileInputStream} * that read from a file. * * @param file the file to read from * @return the factory */ public static InputSupplier<FileInputStream> newInputStreamSupplier( final File file) { return ByteStreams.asInputSupplier(asByteSource(file)); } /** * Returns a factory that will supply instances of {@link FileOutputStream} * that write to a file. * * @param file the file to write to * @return the factory */ public static OutputSupplier<FileOutputStream> newOutputStreamSupplier( File file) { return newOutputStreamSupplier(file, false); } /** * Returns a factory that will supply instances of {@link FileOutputStream} * that write to or append to a file. * * @param file the file to write to * @param append if true, the encoded characters will be appended to the file; * otherwise the file is overwritten * @return the factory */ public static OutputSupplier<FileOutputStream> newOutputStreamSupplier( final File file, final boolean append) { return ByteStreams.asOutputSupplier(asByteSink(file, modes(append))); } private static FileWriteMode[] modes(boolean append) { return append ? new FileWriteMode[]{ FileWriteMode.APPEND } : new FileWriteMode[0]; } /** * Returns a factory that will supply instances of * {@link InputStreamReader} that read a file using the given character set. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link * Charsets} for helpful predefined constants * @return the factory */ public static InputSupplier<InputStreamReader> newReaderSupplier(File file, Charset charset) { return CharStreams.asInputSupplier(asCharSource(file, charset)); } /** * Returns a factory that will supply instances of {@link OutputStreamWriter} * that write to a file using the given character set. * * @param file the file to write to * @param charset the charset used to encode the output stream; see {@link * Charsets} for helpful predefined constants * @return the factory */ public static OutputSupplier<OutputStreamWriter> newWriterSupplier(File file, Charset charset) { return newWriterSupplier(file, charset, false); } /** * Returns a factory that will supply instances of {@link OutputStreamWriter} * that write to or append to a file using the given character set. * * @param file the file to write to * @param charset the charset used to encode the output stream; see {@link * Charsets} for helpful predefined constants * @param append if true, the encoded characters will be appended to the file; * otherwise the file is overwritten * @return the factory */ public static OutputSupplier<OutputStreamWriter> newWriterSupplier(File file, Charset charset, boolean append) { return CharStreams.asOutputSupplier(asCharSink(file, charset, modes(append))); } /** * Reads all bytes from a file into a byte array. * * @param file the file to read from * @return a byte array containing all the bytes from file * @throws IllegalArgumentException if the file is bigger than the largest * possible byte array (2^31 - 1) * @throws IOException if an I/O error occurs */ public static byte[] toByteArray(File file) throws IOException { return asByteSource(file).read(); } /** * Reads all characters from a file into a {@link String}, using the given * character set. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link * Charsets} for helpful predefined constants * @return a string containing all the characters from the file * @throws IOException if an I/O error occurs */ public static String toString(File file, Charset charset) throws IOException { return asCharSource(file, charset).read(); } /** * Copies to a file all bytes from an {@link InputStream} supplied by a * factory. * * @param from the input factory * @param to the destination file * @throws IOException if an I/O error occurs */ public static void copy(InputSupplier<? extends InputStream> from, File to) throws IOException { ByteStreams.asByteSource(from).copyTo(asByteSink(to)); } /** * Overwrites a file with the contents of a byte array. * * @param from the bytes to write * @param to the destination file * @throws IOException if an I/O error occurs */ public static void write(byte[] from, File to) throws IOException { asByteSink(to).write(from); } /** * Copies all bytes from a file to an {@link OutputStream} supplied by * a factory. * * @param from the source file * @param to the output factory * @throws IOException if an I/O error occurs */ public static void copy(File from, OutputSupplier<? extends OutputStream> to) throws IOException { asByteSource(from).copyTo(ByteStreams.asByteSink(to)); } /** * Copies all bytes from a file to an output stream. * * @param from the source file * @param to the output stream * @throws IOException if an I/O error occurs */ public static void copy(File from, OutputStream to) throws IOException { asByteSource(from).copyTo(to); } /** * Copies all the bytes from one file to another. * * <p><b>Warning:</b> If {@code to} represents an existing file, that file * will be overwritten with the contents of {@code from}. If {@code to} and * {@code from} refer to the <i>same</i> file, the contents of that file * will be deleted. * * @param from the source file * @param to the destination file * @throws IOException if an I/O error occurs * @throws IllegalArgumentException if {@code from.equals(to)} */ public static void copy(File from, File to) throws IOException { checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to); asByteSource(from).copyTo(asByteSink(to)); } /** * Copies to a file all characters from a {@link Readable} and * {@link Closeable} object supplied by a factory, using the given * character set. * * @param from the readable supplier * @param to the destination file * @param charset the charset used to encode the output stream; see {@link * Charsets} for helpful predefined constants * @throws IOException if an I/O error occurs */ public static <R extends Readable & Closeable> void copy( InputSupplier<R> from, File to, Charset charset) throws IOException { CharStreams.asCharSource(from).copyTo(asCharSink(to, charset)); } /** * Writes a character sequence (such as a string) to a file using the given * character set. * * @param from the character sequence to write * @param to the destination file * @param charset the charset used to encode the output stream; see {@link * Charsets} for helpful predefined constants * @throws IOException if an I/O error occurs */ public static void write(CharSequence from, File to, Charset charset) throws IOException { asCharSink(to, charset).write(from); } /** * Appends a character sequence (such as a string) to a file using the given * character set. * * @param from the character sequence to append * @param to the destination file * @param charset the charset used to encode the output stream; see {@link * Charsets} for helpful predefined constants * @throws IOException if an I/O error occurs */ public static void append(CharSequence from, File to, Charset charset) throws IOException { write(from, to, charset, true); } /** * Private helper method. Writes a character sequence to a file, * optionally appending. * * @param from the character sequence to append * @param to the destination file * @param charset the charset used to encode the output stream; see {@link * Charsets} for helpful predefined constants * @param append true to append, false to overwrite * @throws IOException if an I/O error occurs */ private static void write(CharSequence from, File to, Charset charset, boolean append) throws IOException { asCharSink(to, charset, modes(append)).write(from); } /** * Copies all characters from a file to a {@link Appendable} & * {@link Closeable} object supplied by a factory, using the given * character set. * * @param from the source file * @param charset the charset used to decode the input stream; see {@link * Charsets} for helpful predefined constants * @param to the appendable supplier * @throws IOException if an I/O error occurs */ public static <W extends Appendable & Closeable> void copy(File from, Charset charset, OutputSupplier<W> to) throws IOException { asCharSource(from, charset).copyTo(CharStreams.asCharSink(to)); } /** * Copies all characters from a file to an appendable object, * using the given character set. * * @param from the source file * @param charset the charset used to decode the input stream; see {@link * Charsets} for helpful predefined constants * @param to the appendable object * @throws IOException if an I/O error occurs */ public static void copy(File from, Charset charset, Appendable to) throws IOException { asCharSource(from, charset).copyTo(to); } /** * Returns true if the files contains the same bytes. * * @throws IOException if an I/O error occurs */ public static boolean equal(File file1, File file2) throws IOException { checkNotNull(file1); checkNotNull(file2); if (file1 == file2 || file1.equals(file2)) { return true; } /* * Some operating systems may return zero as the length for files * denoting system-dependent entities such as devices or pipes, in * which case we must fall back on comparing the bytes directly. */ long len1 = file1.length(); long len2 = file2.length(); if (len1 != 0 && len2 != 0 && len1 != len2) { return false; } return asByteSource(file1).contentEquals(asByteSource(file2)); } /** * Atomically creates a new directory somewhere beneath the system's * temporary directory (as defined by the {@code java.io.tmpdir} system * property), and returns its name. * * <p>Use this method instead of {@link File#createTempFile(String, String)} * when you wish to create a directory, not a regular file. A common pitfall * is to call {@code createTempFile}, delete the file and create a * directory in its place, but this leads a race condition which can be * exploited to create security vulnerabilities, especially when executable * files are to be written into the directory. * * <p>This method assumes that the temporary volume is writable, has free * inodes and free blocks, and that it will not be called thousands of times * per second. * * @return the newly-created directory * @throws IllegalStateException if the directory could not be created */ public static File createTempDir() { File baseDir = new File(System.getProperty("java.io.tmpdir")); String baseName = System.currentTimeMillis() + "-"; for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) { File tempDir = new File(baseDir, baseName + counter); if (tempDir.mkdir()) { return tempDir; } } throw new IllegalStateException("Failed to create directory within " + TEMP_DIR_ATTEMPTS + " attempts (tried " + baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')'); } /** * Creates an empty file or updates the last updated timestamp on the * same as the unix command of the same name. * * @param file the file to create or update * @throws IOException if an I/O error occurs */ public static void touch(File file) throws IOException { checkNotNull(file); if (!file.createNewFile() && !file.setLastModified(System.currentTimeMillis())) { throw new IOException("Unable to update modification time of " + file); } } /** * Creates any necessary but nonexistent parent directories of the specified * file. Note that if this operation fails it may have succeeded in creating * some (but not all) of the necessary parent directories. * * @throws IOException if an I/O error occurs, or if any necessary but * nonexistent parent directories of the specified file could not be * created. * @since 4.0 */ public static void createParentDirs(File file) throws IOException { checkNotNull(file); File parent = file.getCanonicalFile().getParentFile(); if (parent == null) { /* * The given directory is a filesystem root. All zero of its ancestors * exist. This doesn't mean that the root itself exists -- consider x:\ on * a Windows machine without such a drive -- or even that the caller can * create it, but this method makes no such guarantees even for non-root * files. */ return; } parent.mkdirs(); if (!parent.isDirectory()) { throw new IOException("Unable to create parent directories of " + file); } } /** * Moves the file from one path to another. This method can rename a file or * move it to a different directory, like the Unix {@code mv} command. * * @param from the source file * @param to the destination file * @throws IOException if an I/O error occurs * @throws IllegalArgumentException if {@code from.equals(to)} */ public static void move(File from, File to) throws IOException { checkNotNull(from); checkNotNull(to); checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to); if (!from.renameTo(to)) { copy(from, to); if (!from.delete()) { if (!to.delete()) { throw new IOException("Unable to delete " + to); } throw new IOException("Unable to delete " + from); } } } /** * Reads the first line from a file. The line does not include * line-termination characters, but does include other leading and * trailing whitespace. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link * Charsets} for helpful predefined constants * @return the first line, or null if the file is empty * @throws IOException if an I/O error occurs */ public static String readFirstLine(File file, Charset charset) throws IOException { return asCharSource(file, charset).readFirstLine(); } /** * Reads all of the lines from a file. The lines do not include * line-termination characters, but do include other leading and * trailing whitespace. * * <p>This method returns a mutable {@code List}. For an * {@code ImmutableList}, use * {@code Files.asCharSource(file, charset).readLines()}. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link * Charsets} for helpful predefined constants * @return a mutable {@link List} containing all the lines * @throws IOException if an I/O error occurs */ public static List<String> readLines(File file, Charset charset) throws IOException { // don't use asCharSource(file, charset).readLines() because that returns // an immutable list, which would change the behavior of this method return readLines(file, charset, new LineProcessor<List<String>>() { final List<String> result = Lists.newArrayList(); @Override public boolean processLine(String line) { result.add(line); return true; } @Override public List<String> getResult() { return result; } }); } /** * Streams lines from a {@link File}, stopping when our callback returns * false, or we have read all of the lines. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link * Charsets} for helpful predefined constants * @param callback the {@link LineProcessor} to use to handle the lines * @return the output of processing the lines * @throws IOException if an I/O error occurs */ public static <T> T readLines(File file, Charset charset, LineProcessor<T> callback) throws IOException { return CharStreams.readLines(newReaderSupplier(file, charset), callback); } /** * Process the bytes of a file. * * <p>(If this seems too complicated, maybe you're looking for * {@link #toByteArray}.) * * @param file the file to read * @param processor the object to which the bytes of the file are passed. * @return the result of the byte processor * @throws IOException if an I/O error occurs */ public static <T> T readBytes(File file, ByteProcessor<T> processor) throws IOException { return ByteStreams.readBytes(newInputStreamSupplier(file), processor); } /** * Computes the hash code of the {@code file} using {@code hashFunction}. * * @param file the file to read * @param hashFunction the hash function to use to hash the data * @return the {@link HashCode} of all of the bytes in the file * @throws IOException if an I/O error occurs * @since 12.0 */ public static HashCode hash(File file, HashFunction hashFunction) throws IOException { return asByteSource(file).hash(hashFunction); } /** * Fully maps a file read-only in to memory as per * {@link FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}. * * <p>Files are mapped from offset 0 to its length. * * <p>This only works for files <= {@link Integer#MAX_VALUE} bytes. * * @param file the file to map * @return a read-only buffer reflecting {@code file} * @throws FileNotFoundException if the {@code file} does not exist * @throws IOException if an I/O error occurs * * @see FileChannel#map(MapMode, long, long) * @since 2.0 */ public static MappedByteBuffer map(File file) throws IOException { checkNotNull(file); return map(file, MapMode.READ_ONLY); } /** * Fully maps a file in to memory as per * {@link FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)} * using the requested {@link MapMode}. * * <p>Files are mapped from offset 0 to its length. * * <p>This only works for files <= {@link Integer#MAX_VALUE} bytes. * * @param file the file to map * @param mode the mode to use when mapping {@code file} * @return a buffer reflecting {@code file} * @throws FileNotFoundException if the {@code file} does not exist * @throws IOException if an I/O error occurs * * @see FileChannel#map(MapMode, long, long) * @since 2.0 */ public static MappedByteBuffer map(File file, MapMode mode) throws IOException { checkNotNull(file); checkNotNull(mode); if (!file.exists()) { throw new FileNotFoundException(file.toString()); } return map(file, mode, file.length()); } /** * Maps a file in to memory as per * {@link FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)} * using the requested {@link MapMode}. * * <p>Files are mapped from offset 0 to {@code size}. * * <p>If the mode is {@link MapMode#READ_WRITE} and the file does not exist, * it will be created with the requested {@code size}. Thus this method is * useful for creating memory mapped files which do not yet exist. * * <p>This only works for files <= {@link Integer#MAX_VALUE} bytes. * * @param file the file to map * @param mode the mode to use when mapping {@code file} * @return a buffer reflecting {@code file} * @throws IOException if an I/O error occurs * * @see FileChannel#map(MapMode, long, long) * @since 2.0 */ public static MappedByteBuffer map(File file, MapMode mode, long size) throws FileNotFoundException, IOException { checkNotNull(file); checkNotNull(mode); Closer closer = Closer.create(); try { RandomAccessFile raf = closer.register( new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw")); return map(raf, mode, size); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } private static MappedByteBuffer map(RandomAccessFile raf, MapMode mode, long size) throws IOException { Closer closer = Closer.create(); try { FileChannel channel = closer.register(raf.getChannel()); return channel.map(mode, 0, size); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Returns the lexically cleaned form of the path name, <i>usually</i> (but * not always) equivalent to the original. The following heuristics are used: * * <ul> * <li>empty string becomes . * <li>. stays as . * <li>fold out ./ * <li>fold out ../ when possible * <li>collapse multiple slashes * <li>delete trailing slashes (unless the path is just "/") * </ul> * * <p>These heuristics do not always match the behavior of the filesystem. In * particular, consider the path {@code a/../b}, which {@code simplifyPath} * will change to {@code b}. If {@code a} is a symlink to {@code x}, {@code * a/../b} may refer to a sibling of {@code x}, rather than the sibling of * {@code a} referred to by {@code b}. * * @since 11.0 */ public static String simplifyPath(String pathname) { checkNotNull(pathname); if (pathname.length() == 0) { return "."; } // split the path apart Iterable<String> components = Splitter.on('/').omitEmptyStrings().split(pathname); List<String> path = new ArrayList<String>(); // resolve ., .., and // for (String component : components) { if (component.equals(".")) { continue; } else if (component.equals("..")) { if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) { path.remove(path.size() - 1); } else { path.add(".."); } } else { path.add(component); } } // put it back together String result = Joiner.on('/').join(path); if (pathname.charAt(0) == '/') { result = "/" + result; } while (result.startsWith("/../")) { result = result.substring(3); } if (result.equals("/..")) { result = "/"; } else if ("".equals(result)) { result = "."; } return result; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Filename_extension">file * extension</a> for the given file name, or the empty string if the file has * no extension. The result does not include the '{@code .}'. * * @since 11.0 */ public static String getFileExtension(String fullName) { checkNotNull(fullName); String fileName = new File(fullName).getName(); int dotIndex = fileName.lastIndexOf('.'); return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1); } /** * Returns the file name without its * <a href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> or path. This is * similar to the {@code basename} unix command. The result does not include the '{@code .}'. * * @param file The name of the file to trim the extension from. This can be either a fully * qualified file name (including a path) or just a file name. * @return The file name without its path or extension. * @since 14.0 */ public static String getNameWithoutExtension(String file) { checkNotNull(file); String fileName = new File(file).getName(); int dotIndex = fileName.lastIndexOf('.'); return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex); } /** * Returns a {@link TreeTraverser} instance for {@link File} trees. * * <p><b>Warning:</b> {@code File} provides no support for symbolic links, and as such there is no * way to ensure that a symbolic link to a directory is not followed when traversing the tree. * In this case, iterables created by this traverser could contain files that are outside of the * given directory or even be infinite if there is a symbolic link loop. * * @since 15.0 */ public static TreeTraverser<File> fileTreeTraverser() { return FILE_TREE_TRAVERSER; } private static final TreeTraverser<File> FILE_TREE_TRAVERSER = new TreeTraverser<File>() { @Override public Iterable<File> children(File file) { // check isDirectory() just because it may be faster than listFiles() on a non-directory if (file.isDirectory()) { File[] files = file.listFiles(); if (files != null) { return Collections.unmodifiableList(Arrays.asList(files)); } } return Collections.emptyList(); } @Override public String toString() { return "Files.fileTreeTraverser()"; } }; /** * Returns a predicate that returns the result of {@link File#isDirectory} on input files. * * @since 15.0 */ public static Predicate<File> isDirectory() { return FilePredicate.IS_DIRECTORY; } /** * Returns a predicate that returns the result of {@link File#isFile} on input files. * * @since 15.0 */ public static Predicate<File> isFile() { return FilePredicate.IS_FILE; } private enum FilePredicate implements Predicate<File> { IS_DIRECTORY { @Override public boolean apply(File file) { return file.isDirectory(); } @Override public String toString() { return "Files.isDirectory()"; } }, IS_FILE { @Override public boolean apply(File file) { return file.isFile(); } @Override public String toString() { return "Files.isFile()"; } }; } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import java.io.DataInput; import java.io.IOException; /** * An extension of {@code DataInput} for reading from in-memory byte arrays; its * methods offer identical functionality but do not throw {@link IOException}. * * <p><b>Warning:<b> The caller is responsible for not attempting to read past * the end of the array. If any method encounters the end of the array * prematurely, it throws {@link IllegalStateException} to signify <i>programmer * error</i>. This behavior is a technical violation of the supertype's * contract, which specifies a checked exception. * * @author Kevin Bourrillion * @since 1.0 */ public interface ByteArrayDataInput extends DataInput { @Override void readFully(byte b[]); @Override void readFully(byte b[], int off, int len); @Override int skipBytes(int n); @Override boolean readBoolean(); @Override byte readByte(); @Override int readUnsignedByte(); @Override short readShort(); @Override int readUnsignedShort(); @Override char readChar(); @Override int readInt(); @Override long readLong(); @Override float readFloat(); @Override double readDouble(); @Override String readLine(); @Override String readUTF(); }
Java
/* * Copyright (C) 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.io; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Splitter; import com.google.common.collect.AbstractIterator; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; import javax.annotation.Nullable; /** * A readable source of characters, such as a text file. Unlike a {@link Reader}, a * {@code CharSource} is not an open, stateful stream of characters that can be read and closed. * Instead, it is an immutable <i>supplier</i> of {@code Reader} instances. * * <p>{@code CharSource} provides two kinds of methods: * <ul> * <li><b>Methods that return a reader:</b> These methods should return a <i>new</i>, independent * instance each time they are called. The caller is responsible for ensuring that the returned * reader is closed. * <li><b>Convenience methods:</b> These are implementations of common operations that are * typically implemented by opening a reader using one of the methods in the first category, * doing something and finally closing the reader that was opened. * </ul> * * <p>Several methods in this class, such as {@link #readLines()}, break the contents of the * source into lines. Like {@link BufferedReader}, these methods break lines on any of {@code \n}, * {@code \r} or {@code \r\n}, do not include the line separator in each line and do not consider * there to be an empty line at the end if the contents are terminated with a line separator. * * <p>Any {@link ByteSource} containing text encoded with a specific {@linkplain Charset character * encoding} may be viewed as a {@code CharSource} using {@link ByteSource#asCharSource(Charset)}. * * @since 14.0 * @author Colin Decker */ public abstract class CharSource implements InputSupplier<Reader> { /** * Opens a new {@link Reader} for reading from this source. This method should return a new, * independent reader each time it is called. * * <p>The caller is responsible for ensuring that the returned reader is closed. * * @throws IOException if an I/O error occurs in the process of opening the reader */ public abstract Reader openStream() throws IOException; /** * This method is a temporary method provided for easing migration from suppliers to sources and * sinks. * * @since 15.0 * @deprecated This method is only provided for temporary compatibility with the * {@link InputSupplier} interface and should not be called directly. Use {@link #openStream} * instead. */ @Override @Deprecated public final Reader getInput() throws IOException { return openStream(); } /** * Opens a new {@link BufferedReader} for reading from this source. This method should return a * new, independent reader each time it is called. * * <p>The caller is responsible for ensuring that the returned reader is closed. * * @throws IOException if an I/O error occurs in the process of opening the reader */ public BufferedReader openBufferedStream() throws IOException { Reader reader = openStream(); return (reader instanceof BufferedReader) ? (BufferedReader) reader : new BufferedReader(reader); } /** * Appends the contents of this source to the given {@link Appendable} (such as a {@link Writer}). * Does not close {@code appendable} if it is {@code Closeable}. * * @throws IOException if an I/O error occurs in the process of reading from this source or * writing to {@code appendable} */ public long copyTo(Appendable appendable) throws IOException { checkNotNull(appendable); Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); return CharStreams.copy(reader, appendable); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Copies the contents of this source to the given sink. * * @throws IOException if an I/O error occurs in the process of reading from this source or * writing to {@code sink} */ public long copyTo(CharSink sink) throws IOException { checkNotNull(sink); Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); Writer writer = closer.register(sink.openStream()); return CharStreams.copy(reader, writer); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Reads the contents of this source as a string. * * @throws IOException if an I/O error occurs in the process of reading from this source */ public String read() throws IOException { Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); return CharStreams.toString(reader); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Reads the first link of this source as a string. Returns {@code null} if this source is empty. * * <p>Like {@link BufferedReader}, this method breaks lines on any of {@code \n}, {@code \r} or * {@code \r\n}, does not include the line separator in the returned line and does not consider * there to be an extra empty line at the end if the content is terminated with a line separator. * * @throws IOException if an I/O error occurs in the process of reading from this source */ public @Nullable String readFirstLine() throws IOException { Closer closer = Closer.create(); try { BufferedReader reader = closer.register(openBufferedStream()); return reader.readLine(); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Reads all the lines of this source as a list of strings. The returned list will be empty if * this source is empty. * * <p>Like {@link BufferedReader}, this method breaks lines on any of {@code \n}, {@code \r} or * {@code \r\n}, does not include the line separator in the returned lines and does not consider * there to be an extra empty line at the end if the content is terminated with a line separator. * * @throws IOException if an I/O error occurs in the process of reading from this source */ public ImmutableList<String> readLines() throws IOException { Closer closer = Closer.create(); try { BufferedReader reader = closer.register(openBufferedStream()); List<String> result = Lists.newArrayList(); String line; while ((line = reader.readLine()) != null) { result.add(line); } return ImmutableList.copyOf(result); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Returns whether the source has zero chars. The default implementation is to open a stream and * check for EOF. * * @throws IOException if an I/O error occurs * @since 15.0 */ public boolean isEmpty() throws IOException { Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); return reader.read() == -1; } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Concatenates multiple {@link CharSource} instances into a single source. * Streams returned from the source will contain the concatenated data from * the streams of the underlying sources. * * <p>Only one underlying stream will be open at a time. Closing the * concatenated stream will close the open underlying stream. * * @param sources the sources to concatenate * @return a {@code CharSource} containing the concatenated data * @throws NullPointerException if any of {@code sources} is {@code null} * @since 15.0 */ public static CharSource concat(Iterable<? extends CharSource> sources) { return new ConcatenatedCharSource(sources); } /** * Concatenates multiple {@link CharSource} instances into a single source. * Streams returned from the source will contain the concatenated data from * the streams of the underlying sources. * * <p>Only one underlying stream will be open at a time. Closing the * concatenated stream will close the open underlying stream. * * @param sources the sources to concatenate * @return a {@code CharSource} containing the concatenated data * @throws NullPointerException if any of {@code sources} is {@code null} * @since 15.0 */ public static CharSource concat(Iterator<? extends CharSource> sources) { return concat(ImmutableList.copyOf(sources)); } /** * Concatenates multiple {@link CharSource} instances into a single source. * Streams returned from the source will contain the concatenated data from * the streams of the underlying sources. * * <p>Only one underlying stream will be open at a time. Closing the * concatenated stream will close the open underlying stream. * * @param sources the sources to concatenate * @return a {@code CharSource} containing the concatenated data * @throws NullPointerException if any of {@code sources} is {@code null} * @since 15.0 */ public static CharSource concat(CharSource... sources) { return concat(ImmutableList.copyOf(sources)); } /** * Returns a view of the given character sequence as a {@link CharSource}. The behavior of the * returned {@code CharSource} and any {@code Reader} instances created by it is unspecified if * the {@code charSequence} is mutated while it is being read, so don't do that. * * @since 15.0 (since 14.0 as {@code CharStreams.asCharSource(String)}) */ public static CharSource wrap(CharSequence charSequence) { return new CharSequenceCharSource(charSequence); } /** * Returns an immutable {@link CharSource} that contains no characters. * * @since 15.0 */ public static CharSource empty() { return EmptyCharSource.INSTANCE; } private static class CharSequenceCharSource extends CharSource { private static final Splitter LINE_SPLITTER = Splitter.on(Pattern.compile("\r\n|\n|\r")); private final CharSequence seq; protected CharSequenceCharSource(CharSequence seq) { this.seq = checkNotNull(seq); } @Override public Reader openStream() { return new CharSequenceReader(seq); } @Override public String read() { return seq.toString(); } @Override public boolean isEmpty() { return seq.length() == 0; } /** * Returns an iterable over the lines in the string. If the string ends in * a newline, a final empty string is not included to match the behavior of * BufferedReader/LineReader.readLine(). */ private Iterable<String> lines() { return new Iterable<String>() { @Override public Iterator<String> iterator() { return new AbstractIterator<String>() { Iterator<String> lines = LINE_SPLITTER.split(seq).iterator(); @Override protected String computeNext() { if (lines.hasNext()) { String next = lines.next(); // skip last line if it's empty if (lines.hasNext() || !next.isEmpty()) { return next; } } return endOfData(); } }; } }; } @Override public String readFirstLine() { Iterator<String> lines = lines().iterator(); return lines.hasNext() ? lines.next() : null; } @Override public ImmutableList<String> readLines() { return ImmutableList.copyOf(lines()); } @Override public String toString() { CharSequence shortened = (seq.length() <= 15) ? seq : seq.subSequence(0, 12) + "..."; return "CharSource.wrap(" + shortened + ")"; } } private static final class EmptyCharSource extends CharSequenceCharSource { private static final EmptyCharSource INSTANCE = new EmptyCharSource(); private EmptyCharSource() { super(""); } @Override public String toString() { return "CharSource.empty()"; } } private static final class ConcatenatedCharSource extends CharSource { private final ImmutableList<CharSource> sources; ConcatenatedCharSource(Iterable<? extends CharSource> sources) { this.sources = ImmutableList.copyOf(sources); } @Override public Reader openStream() throws IOException { return new MultiReader(sources.iterator()); } @Override public boolean isEmpty() throws IOException { for (CharSource source : sources) { if (!source.isEmpty()) { return false; } } return true; } @Override public String toString() { return "CharSource.concat(" + sources + ")"; } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndex; import com.google.common.annotations.Beta; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.EOFException; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.Arrays; /** * Provides utility methods for working with byte arrays and I/O streams. * * @author Chris Nokleberg * @author Colin Decker * @since 1.0 */ @Beta public final class ByteStreams { private static final int BUF_SIZE = 0x1000; // 4K private ByteStreams() {} /** * Returns a factory that will supply instances of * {@link ByteArrayInputStream} that read from the given byte array. * * @param b the input buffer * @return the factory */ public static InputSupplier<ByteArrayInputStream> newInputStreamSupplier( byte[] b) { return asInputSupplier(ByteSource.wrap(b)); } /** * Returns a factory that will supply instances of * {@link ByteArrayInputStream} that read from the given byte array. * * @param b the input buffer * @param off the offset in the buffer of the first byte to read * @param len the maximum number of bytes to read from the buffer * @return the factory */ public static InputSupplier<ByteArrayInputStream> newInputStreamSupplier( final byte[] b, final int off, final int len) { return asInputSupplier(ByteSource.wrap(b).slice(off, len)); } /** * Returns a new {@link ByteSource} that reads bytes from the given byte array. * * @since 14.0 * @deprecated Use {@link ByteSource#wrap(byte[])} instead. This method is * scheduled to be removed in Guava 16.0. */ @Deprecated public static ByteSource asByteSource(byte[] b) { return ByteSource.wrap(b); } /** * Writes a byte array to an output stream from the given supplier. * * @param from the bytes to write * @param to the output supplier * @throws IOException if an I/O error occurs */ public static void write(byte[] from, OutputSupplier<? extends OutputStream> to) throws IOException { asByteSink(to).write(from); } /** * Opens input and output streams from the given suppliers, copies all * bytes from the input to the output, and closes the streams. * * @param from the input factory * @param to the output factory * @return the number of bytes copied * @throws IOException if an I/O error occurs */ public static long copy(InputSupplier<? extends InputStream> from, OutputSupplier<? extends OutputStream> to) throws IOException { return asByteSource(from).copyTo(asByteSink(to)); } /** * Opens an input stream from the supplier, copies all bytes from the * input to the output, and closes the input stream. Does not close * or flush the output stream. * * @param from the input factory * @param to the output stream to write to * @return the number of bytes copied * @throws IOException if an I/O error occurs */ public static long copy(InputSupplier<? extends InputStream> from, OutputStream to) throws IOException { return asByteSource(from).copyTo(to); } /** * Opens an output stream from the supplier, copies all bytes from the input * to the output, and closes the output stream. Does not close or flush the * input stream. * * @param from the input stream to read from * @param to the output factory * @return the number of bytes copied * @throws IOException if an I/O error occurs * @since 10.0 */ public static long copy(InputStream from, OutputSupplier<? extends OutputStream> to) throws IOException { return asByteSink(to).writeFrom(from); } /** * Copies all bytes from the input stream to the output stream. * Does not close or flush either stream. * * @param from the input stream to read from * @param to the output stream to write to * @return the number of bytes copied * @throws IOException if an I/O error occurs */ public static long copy(InputStream from, OutputStream to) throws IOException { checkNotNull(from); checkNotNull(to); byte[] buf = new byte[BUF_SIZE]; long total = 0; while (true) { int r = from.read(buf); if (r == -1) { break; } to.write(buf, 0, r); total += r; } return total; } /** * Copies all bytes from the readable channel to the writable channel. * Does not close or flush either channel. * * @param from the readable channel to read from * @param to the writable channel to write to * @return the number of bytes copied * @throws IOException if an I/O error occurs */ public static long copy(ReadableByteChannel from, WritableByteChannel to) throws IOException { checkNotNull(from); checkNotNull(to); ByteBuffer buf = ByteBuffer.allocate(BUF_SIZE); long total = 0; while (from.read(buf) != -1) { buf.flip(); while (buf.hasRemaining()) { total += to.write(buf); } buf.clear(); } return total; } /** * Reads all bytes from an input stream into a byte array. * Does not close the stream. * * @param in the input stream to read from * @return a byte array containing all the bytes from the stream * @throws IOException if an I/O error occurs */ public static byte[] toByteArray(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); copy(in, out); return out.toByteArray(); } /** * Returns the data from a {@link InputStream} factory as a byte array. * * @param supplier the factory * @throws IOException if an I/O error occurs */ public static byte[] toByteArray( InputSupplier<? extends InputStream> supplier) throws IOException { return asByteSource(supplier).read(); } /** * Returns a new {@link ByteArrayDataInput} instance to read from the {@code * bytes} array from the beginning. */ public static ByteArrayDataInput newDataInput(byte[] bytes) { return new ByteArrayDataInputStream(bytes); } /** * Returns a new {@link ByteArrayDataInput} instance to read from the {@code * bytes} array, starting at the given position. * * @throws IndexOutOfBoundsException if {@code start} is negative or greater * than the length of the array */ public static ByteArrayDataInput newDataInput(byte[] bytes, int start) { checkPositionIndex(start, bytes.length); return new ByteArrayDataInputStream(bytes, start); } private static class ByteArrayDataInputStream implements ByteArrayDataInput { final DataInput input; ByteArrayDataInputStream(byte[] bytes) { this.input = new DataInputStream(new ByteArrayInputStream(bytes)); } ByteArrayDataInputStream(byte[] bytes, int start) { this.input = new DataInputStream( new ByteArrayInputStream(bytes, start, bytes.length - start)); } @Override public void readFully(byte b[]) { try { input.readFully(b); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void readFully(byte b[], int off, int len) { try { input.readFully(b, off, len); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public int skipBytes(int n) { try { return input.skipBytes(n); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public boolean readBoolean() { try { return input.readBoolean(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public byte readByte() { try { return input.readByte(); } catch (EOFException e) { throw new IllegalStateException(e); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public int readUnsignedByte() { try { return input.readUnsignedByte(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public short readShort() { try { return input.readShort(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public int readUnsignedShort() { try { return input.readUnsignedShort(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public char readChar() { try { return input.readChar(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public int readInt() { try { return input.readInt(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public long readLong() { try { return input.readLong(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public float readFloat() { try { return input.readFloat(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public double readDouble() { try { return input.readDouble(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public String readLine() { try { return input.readLine(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public String readUTF() { try { return input.readUTF(); } catch (IOException e) { throw new IllegalStateException(e); } } } /** * Returns a new {@link ByteArrayDataOutput} instance with a default size. */ public static ByteArrayDataOutput newDataOutput() { return new ByteArrayDataOutputStream(); } /** * Returns a new {@link ByteArrayDataOutput} instance sized to hold * {@code size} bytes before resizing. * * @throws IllegalArgumentException if {@code size} is negative */ public static ByteArrayDataOutput newDataOutput(int size) { checkArgument(size >= 0, "Invalid size: %s", size); return new ByteArrayDataOutputStream(size); } @SuppressWarnings("deprecation") // for writeBytes private static class ByteArrayDataOutputStream implements ByteArrayDataOutput { final DataOutput output; final ByteArrayOutputStream byteArrayOutputSteam; ByteArrayDataOutputStream() { this(new ByteArrayOutputStream()); } ByteArrayDataOutputStream(int size) { this(new ByteArrayOutputStream(size)); } ByteArrayDataOutputStream(ByteArrayOutputStream byteArrayOutputSteam) { this.byteArrayOutputSteam = byteArrayOutputSteam; output = new DataOutputStream(byteArrayOutputSteam); } @Override public void write(int b) { try { output.write(b); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void write(byte[] b) { try { output.write(b); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void write(byte[] b, int off, int len) { try { output.write(b, off, len); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeBoolean(boolean v) { try { output.writeBoolean(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeByte(int v) { try { output.writeByte(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeBytes(String s) { try { output.writeBytes(s); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeChar(int v) { try { output.writeChar(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeChars(String s) { try { output.writeChars(s); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeDouble(double v) { try { output.writeDouble(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeFloat(float v) { try { output.writeFloat(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeInt(int v) { try { output.writeInt(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeLong(long v) { try { output.writeLong(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeShort(int v) { try { output.writeShort(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeUTF(String s) { try { output.writeUTF(s); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public byte[] toByteArray() { return byteArrayOutputSteam.toByteArray(); } } private static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() { /** Discards the specified byte. */ @Override public void write(int b) { } /** Discards the specified byte array. */ @Override public void write(byte[] b) { checkNotNull(b); } /** Discards the specified byte array. */ @Override public void write(byte[] b, int off, int len) { checkNotNull(b); } @Override public String toString() { return "ByteStreams.nullOutputStream()"; } }; /** * Returns an {@link OutputStream} that simply discards written bytes. * * @since 14.0 (since 1.0 as com.google.common.io.NullOutputStream) */ public static OutputStream nullOutputStream() { return NULL_OUTPUT_STREAM; } /** * Wraps a {@link InputStream}, limiting the number of bytes which can be * read. * * @param in the input stream to be wrapped * @param limit the maximum number of bytes to be read * @return a length-limited {@link InputStream} * @since 14.0 (since 1.0 as com.google.common.io.LimitInputStream) */ public static InputStream limit(InputStream in, long limit) { return new LimitedInputStream(in, limit); } private static final class LimitedInputStream extends FilterInputStream { private long left; private long mark = -1; LimitedInputStream(InputStream in, long limit) { super(in); checkNotNull(in); checkArgument(limit >= 0, "limit must be non-negative"); left = limit; } @Override public int available() throws IOException { return (int) Math.min(in.available(), left); } // it's okay to mark even if mark isn't supported, as reset won't work @Override public synchronized void mark(int readLimit) { in.mark(readLimit); mark = left; } @Override public int read() throws IOException { if (left == 0) { return -1; } int result = in.read(); if (result != -1) { --left; } return result; } @Override public int read(byte[] b, int off, int len) throws IOException { if (left == 0) { return -1; } len = (int) Math.min(len, left); int result = in.read(b, off, len); if (result != -1) { left -= result; } return result; } @Override public synchronized void reset() throws IOException { if (!in.markSupported()) { throw new IOException("Mark not supported"); } if (mark == -1) { throw new IOException("Mark not set"); } in.reset(); left = mark; } @Override public long skip(long n) throws IOException { n = Math.min(n, left); long skipped = in.skip(n); left -= skipped; return skipped; } } /** Returns the length of a supplied input stream, in bytes. */ public static long length( InputSupplier<? extends InputStream> supplier) throws IOException { return asByteSource(supplier).size(); } /** * Returns true if the supplied input streams contain the same bytes. * * @throws IOException if an I/O error occurs */ public static boolean equal(InputSupplier<? extends InputStream> supplier1, InputSupplier<? extends InputStream> supplier2) throws IOException { return asByteSource(supplier1).contentEquals(asByteSource(supplier2)); } /** * Attempts to read enough bytes from the stream to fill the given byte array, * with the same behavior as {@link DataInput#readFully(byte[])}. * Does not close the stream. * * @param in the input stream to read from. * @param b the buffer into which the data is read. * @throws EOFException if this stream reaches the end before reading all * the bytes. * @throws IOException if an I/O error occurs. */ public static void readFully(InputStream in, byte[] b) throws IOException { readFully(in, b, 0, b.length); } /** * Attempts to read {@code len} bytes from the stream into the given array * starting at {@code off}, with the same behavior as * {@link DataInput#readFully(byte[], int, int)}. Does not close the * stream. * * @param in the input stream to read from. * @param b the buffer into which the data is read. * @param off an int specifying the offset into the data. * @param len an int specifying the number of bytes to read. * @throws EOFException if this stream reaches the end before reading all * the bytes. * @throws IOException if an I/O error occurs. */ public static void readFully( InputStream in, byte[] b, int off, int len) throws IOException { int read = read(in, b, off, len); if (read != len) { throw new EOFException("reached end of stream after reading " + read + " bytes; " + len + " bytes expected"); } } /** * Discards {@code n} bytes of data from the input stream. This method * will block until the full amount has been skipped. Does not close the * stream. * * @param in the input stream to read from * @param n the number of bytes to skip * @throws EOFException if this stream reaches the end before skipping all * the bytes * @throws IOException if an I/O error occurs, or the stream does not * support skipping */ public static void skipFully(InputStream in, long n) throws IOException { long toSkip = n; while (n > 0) { long amt = in.skip(n); if (amt == 0) { // Force a blocking read to avoid infinite loop if (in.read() == -1) { long skipped = toSkip - n; throw new EOFException("reached end of stream after skipping " + skipped + " bytes; " + toSkip + " bytes expected"); } n--; } else { n -= amt; } } } /** * Process the bytes of a supplied stream * * @param supplier the input stream factory * @param processor the object to which to pass the bytes of the stream * @return the result of the byte processor * @throws IOException if an I/O error occurs */ public static <T> T readBytes( InputSupplier<? extends InputStream> supplier, ByteProcessor<T> processor) throws IOException { checkNotNull(supplier); checkNotNull(processor); Closer closer = Closer.create(); try { InputStream in = closer.register(supplier.getInput()); return readBytes(in, processor); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Process the bytes of the given input stream using the given processor. * * @param input the input stream to process * @param processor the object to which to pass the bytes of the stream * @return the result of the byte processor * @throws IOException if an I/O error occurs * @since 14.0 */ public static <T> T readBytes( InputStream input, ByteProcessor<T> processor) throws IOException { checkNotNull(input); checkNotNull(processor); byte[] buf = new byte[BUF_SIZE]; int read; do { read = input.read(buf); } while (read != -1 && processor.processBytes(buf, 0, read)); return processor.getResult(); } /** * Computes the hash code of the data supplied by {@code supplier} using {@code * hashFunction}. * * @param supplier the input stream factory * @param hashFunction the hash function to use to hash the data * @return the {@link HashCode} of all of the bytes in the input stream * @throws IOException if an I/O error occurs * @since 12.0 */ public static HashCode hash( InputSupplier<? extends InputStream> supplier, HashFunction hashFunction) throws IOException { return asByteSource(supplier).hash(hashFunction); } /** * Reads some bytes from an input stream and stores them into the buffer array * {@code b}. This method blocks until {@code len} bytes of input data have * been read into the array, or end of file is detected. The number of bytes * read is returned, possibly zero. Does not close the stream. * * <p>A caller can detect EOF if the number of bytes read is less than * {@code len}. All subsequent calls on the same stream will return zero. * * <p>If {@code b} is null, a {@code NullPointerException} is thrown. If * {@code off} is negative, or {@code len} is negative, or {@code off+len} is * greater than the length of the array {@code b}, then an * {@code IndexOutOfBoundsException} is thrown. If {@code len} is zero, then * no bytes are read. Otherwise, the first byte read is stored into element * {@code b[off]}, the next one into {@code b[off+1]}, and so on. The number * of bytes read is, at most, equal to {@code len}. * * @param in the input stream to read from * @param b the buffer into which the data is read * @param off an int specifying the offset into the data * @param len an int specifying the number of bytes to read * @return the number of bytes read * @throws IOException if an I/O error occurs */ public static int read(InputStream in, byte[] b, int off, int len) throws IOException { checkNotNull(in); checkNotNull(b); if (len < 0) { throw new IndexOutOfBoundsException("len is negative"); } int total = 0; while (total < len) { int result = in.read(b, off + total, len - total); if (result == -1) { break; } total += result; } return total; } /** * Returns an {@link InputSupplier} that returns input streams from the * an underlying supplier, where each stream starts at the given * offset and is limited to the specified number of bytes. * * @param supplier the supplier from which to get the raw streams * @param offset the offset in bytes into the underlying stream where * the returned streams will start * @param length the maximum length of the returned streams * @throws IllegalArgumentException if offset or length are negative */ public static InputSupplier<InputStream> slice( final InputSupplier<? extends InputStream> supplier, final long offset, final long length) { return asInputSupplier(asByteSource(supplier).slice(offset, length)); } /** * Joins multiple {@link InputStream} suppliers into a single supplier. * Streams returned from the supplier will contain the concatenated data from * the streams of the underlying suppliers. * * <p>Only one underlying input stream will be open at a time. Closing the * joined stream will close the open underlying stream. * * <p>Reading from the joined stream will throw a {@link NullPointerException} * if any of the suppliers are null or return null. * * @param suppliers the suppliers to concatenate * @return a supplier that will return a stream containing the concatenated * stream data */ public static InputSupplier<InputStream> join( final Iterable<? extends InputSupplier<? extends InputStream>> suppliers) { checkNotNull(suppliers); Iterable<ByteSource> sources = Iterables.transform(suppliers, new Function<InputSupplier<? extends InputStream>, ByteSource>() { @Override public ByteSource apply(InputSupplier<? extends InputStream> input) { return asByteSource(input); } }); return asInputSupplier(ByteSource.concat(sources)); } /** Varargs form of {@link #join(Iterable)}. */ public static InputSupplier<InputStream> join( InputSupplier<? extends InputStream>... suppliers) { return join(Arrays.asList(suppliers)); } // TODO(user): Remove these once Input/OutputSupplier methods are removed /** * Returns a view of the given {@code InputStream} supplier as a * {@code ByteSource}. * * <p>This method is a temporary method provided for easing migration from * suppliers to sources and sinks. * * @since 15.0 */ public static ByteSource asByteSource( final InputSupplier<? extends InputStream> supplier) { checkNotNull(supplier); return new ByteSource() { @Override public InputStream openStream() throws IOException { return supplier.getInput(); } @Override public String toString() { return "ByteStreams.asByteSource(" + supplier + ")"; } }; } /** * Returns a view of the given {@code OutputStream} supplier as a * {@code ByteSink}. * * <p>This method is a temporary method provided for easing migration from * suppliers to sources and sinks. * * @since 15.0 */ public static ByteSink asByteSink( final OutputSupplier<? extends OutputStream> supplier) { checkNotNull(supplier); return new ByteSink() { @Override public OutputStream openStream() throws IOException { return supplier.getOutput(); } @Override public String toString() { return "ByteStreams.asByteSink(" + supplier + ")"; } }; } @SuppressWarnings("unchecked") // used internally where known to be safe static <S extends InputStream> InputSupplier<S> asInputSupplier( final ByteSource source) { return (InputSupplier) checkNotNull(source); } @SuppressWarnings("unchecked") // used internally where known to be safe static <S extends OutputStream> OutputSupplier<S> asOutputSupplier( final ByteSink sink) { return (OutputSupplier) checkNotNull(sink); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.Beta; import com.google.common.base.Charsets; import com.google.common.base.Function; import com.google.common.collect.Iterables; import java.io.Closeable; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.StringReader; import java.io.Writer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Provides utility methods for working with character streams. * * <p>All method parameters must be non-null unless documented otherwise. * * <p>Some of the methods in this class take arguments with a generic type of * {@code Readable & Closeable}. A {@link java.io.Reader} implements both of * those interfaces. Similarly for {@code Appendable & Closeable} and * {@link java.io.Writer}. * * @author Chris Nokleberg * @author Bin Zhu * @author Colin Decker * @since 1.0 */ @Beta public final class CharStreams { private static final int BUF_SIZE = 0x800; // 2K chars (4K bytes) private CharStreams() {} /** * Returns a factory that will supply instances of {@link StringReader} that * read a string value. * * @param value the string to read * @return the factory */ public static InputSupplier<StringReader> newReaderSupplier( final String value) { return asInputSupplier(CharSource.wrap(value)); } /** * Returns a {@link CharSource} that reads the given string value. * * @since 14.0 * @deprecated Use {@link CharSource#wrap(CharSequence)} instead. This method * is scheduled to be removed in Guava 16.0. */ @Deprecated public static CharSource asCharSource(String string) { return CharSource.wrap(string); } /** * Returns a factory that will supply instances of {@link InputStreamReader}, * using the given {@link InputStream} factory and character set. * * @param in the factory that will be used to open input streams * @param charset the charset used to decode the input stream; see {@link * Charsets} for helpful predefined constants * @return the factory */ public static InputSupplier<InputStreamReader> newReaderSupplier( final InputSupplier<? extends InputStream> in, final Charset charset) { return asInputSupplier( ByteStreams.asByteSource(in).asCharSource(charset)); } /** * Returns a factory that will supply instances of {@link OutputStreamWriter}, * using the given {@link OutputStream} factory and character set. * * @param out the factory that will be used to open output streams * @param charset the charset used to encode the output stream; see {@link * Charsets} for helpful predefined constants * @return the factory */ public static OutputSupplier<OutputStreamWriter> newWriterSupplier( final OutputSupplier<? extends OutputStream> out, final Charset charset) { return asOutputSupplier( ByteStreams.asByteSink(out).asCharSink(charset)); } /** * Writes a character sequence (such as a string) to an appendable * object from the given supplier. * * @param from the character sequence to write * @param to the output supplier * @throws IOException if an I/O error occurs */ public static <W extends Appendable & Closeable> void write(CharSequence from, OutputSupplier<W> to) throws IOException { asCharSink(to).write(from); } /** * Opens {@link Readable} and {@link Appendable} objects from the * given factories, copies all characters between the two, and closes * them. * * @param from the input factory * @param to the output factory * @return the number of characters copied * @throws IOException if an I/O error occurs */ public static <R extends Readable & Closeable, W extends Appendable & Closeable> long copy(InputSupplier<R> from, OutputSupplier<W> to) throws IOException { return asCharSource(from).copyTo(asCharSink(to)); } /** * Opens a {@link Readable} object from the supplier, copies all characters * to the {@link Appendable} object, and closes the input. Does not close * or flush the output. * * @param from the input factory * @param to the object to write to * @return the number of characters copied * @throws IOException if an I/O error occurs */ public static <R extends Readable & Closeable> long copy( InputSupplier<R> from, Appendable to) throws IOException { return asCharSource(from).copyTo(to); } /** * Copies all characters between the {@link Readable} and {@link Appendable} * objects. Does not close or flush either object. * * @param from the object to read from * @param to the object to write to * @return the number of characters copied * @throws IOException if an I/O error occurs */ public static long copy(Readable from, Appendable to) throws IOException { checkNotNull(from); checkNotNull(to); CharBuffer buf = CharBuffer.allocate(BUF_SIZE); long total = 0; while (from.read(buf) != -1) { buf.flip(); to.append(buf); total += buf.remaining(); buf.clear(); } return total; } /** * Reads all characters from a {@link Readable} object into a {@link String}. * Does not close the {@code Readable}. * * @param r the object to read from * @return a string containing all the characters * @throws IOException if an I/O error occurs */ public static String toString(Readable r) throws IOException { return toStringBuilder(r).toString(); } /** * Returns the characters from a {@link Readable} & {@link Closeable} object * supplied by a factory as a {@link String}. * * @param supplier the factory to read from * @return a string containing all the characters * @throws IOException if an I/O error occurs */ public static <R extends Readable & Closeable> String toString( InputSupplier<R> supplier) throws IOException { return asCharSource(supplier).read(); } /** * Reads all characters from a {@link Readable} object into a new * {@link StringBuilder} instance. Does not close the {@code Readable}. * * @param r the object to read from * @return a {@link StringBuilder} containing all the characters * @throws IOException if an I/O error occurs */ private static StringBuilder toStringBuilder(Readable r) throws IOException { StringBuilder sb = new StringBuilder(); copy(r, sb); return sb; } /** * Reads the first line from a {@link Readable} & {@link Closeable} object * supplied by a factory. The line does not include line-termination * characters, but does include other leading and trailing whitespace. * * @param supplier the factory to read from * @return the first line, or null if the reader is empty * @throws IOException if an I/O error occurs */ public static <R extends Readable & Closeable> String readFirstLine( InputSupplier<R> supplier) throws IOException { return asCharSource(supplier).readFirstLine(); } /** * Reads all of the lines from a {@link Readable} & {@link Closeable} object * supplied by a factory. The lines do not include line-termination * characters, but do include other leading and trailing whitespace. * * @param supplier the factory to read from * @return a mutable {@link List} containing all the lines * @throws IOException if an I/O error occurs */ public static <R extends Readable & Closeable> List<String> readLines( InputSupplier<R> supplier) throws IOException { Closer closer = Closer.create(); try { R r = closer.register(supplier.getInput()); return readLines(r); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Reads all of the lines from a {@link Readable} object. The lines do * not include line-termination characters, but do include other * leading and trailing whitespace. * * <p>Does not close the {@code Readable}. If reading files or resources you * should use the {@link Files#readLines} and {@link Resources#readLines} * methods. * * @param r the object to read from * @return a mutable {@link List} containing all the lines * @throws IOException if an I/O error occurs */ public static List<String> readLines(Readable r) throws IOException { List<String> result = new ArrayList<String>(); LineReader lineReader = new LineReader(r); String line; while ((line = lineReader.readLine()) != null) { result.add(line); } return result; } /** * Streams lines from a {@link Readable} object, stopping when the processor * returns {@code false} or all lines have been read and returning the result * produced by the processor. Does not close {@code readable}. Note that this * method may not fully consume the contents of {@code readable} if the * processor stops processing early. * * @throws IOException if an I/O error occurs * @since 14.0 */ public static <T> T readLines( Readable readable, LineProcessor<T> processor) throws IOException { checkNotNull(readable); checkNotNull(processor); LineReader lineReader = new LineReader(readable); String line; while ((line = lineReader.readLine()) != null) { if (!processor.processLine(line)) { break; } } return processor.getResult(); } /** * Streams lines from a {@link Readable} and {@link Closeable} object * supplied by a factory, stopping when our callback returns false, or we * have read all of the lines. * * @param supplier the factory to read from * @param callback the LineProcessor to use to handle the lines * @return the output of processing the lines * @throws IOException if an I/O error occurs */ public static <R extends Readable & Closeable, T> T readLines( InputSupplier<R> supplier, LineProcessor<T> callback) throws IOException { checkNotNull(supplier); checkNotNull(callback); Closer closer = Closer.create(); try { R r = closer.register(supplier.getInput()); return readLines(r, callback); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Joins multiple {@link Reader} suppliers into a single supplier. * Reader returned from the supplier will contain the concatenated data * from the readers of the underlying suppliers. * * <p>Reading from the joined reader will throw a {@link NullPointerException} * if any of the suppliers are null or return null. * * <p>Only one underlying reader will be open at a time. Closing the * joined reader will close the open underlying reader. * * @param suppliers the suppliers to concatenate * @return a supplier that will return a reader containing the concatenated * data */ public static InputSupplier<Reader> join( final Iterable<? extends InputSupplier<? extends Reader>> suppliers) { checkNotNull(suppliers); Iterable<CharSource> sources = Iterables.transform(suppliers, new Function<InputSupplier<? extends Reader>, CharSource>() { @Override public CharSource apply(InputSupplier<? extends Reader> input) { return asCharSource(input); } }); return asInputSupplier(CharSource.concat(sources)); } /** Varargs form of {@link #join(Iterable)}. */ public static InputSupplier<Reader> join( InputSupplier<? extends Reader>... suppliers) { return join(Arrays.asList(suppliers)); } /** * Discards {@code n} characters of data from the reader. This method * will block until the full amount has been skipped. Does not close the * reader. * * @param reader the reader to read from * @param n the number of characters to skip * @throws EOFException if this stream reaches the end before skipping all * the characters * @throws IOException if an I/O error occurs */ public static void skipFully(Reader reader, long n) throws IOException { checkNotNull(reader); while (n > 0) { long amt = reader.skip(n); if (amt == 0) { // force a blocking read if (reader.read() == -1) { throw new EOFException(); } n--; } else { n -= amt; } } } /** * Returns a {@link Writer} that simply discards written chars. * * @since 15.0 */ public static Writer nullWriter() { return NullWriter.INSTANCE; } private static final class NullWriter extends Writer { private static final NullWriter INSTANCE = new NullWriter(); @Override public void write(int c) { } @Override public void write(char[] cbuf) { checkNotNull(cbuf); } @Override public void write(char[] cbuf, int off, int len) { checkPositionIndexes(off, off + len, cbuf.length); } @Override public void write(String str) { checkNotNull(str); } @Override public void write(String str, int off, int len) { checkPositionIndexes(off, off + len, str.length()); } @Override public Writer append(CharSequence csq) { checkNotNull(csq); return this; } @Override public Writer append(CharSequence csq, int start, int end) { checkPositionIndexes(start, end, csq.length()); return this; } @Override public Writer append(char c) { return this; } @Override public void flush() { } @Override public void close() { } @Override public String toString() { return "CharStreams.nullWriter()"; } } /** * Returns a Writer that sends all output to the given {@link Appendable} * target. Closing the writer will close the target if it is {@link * Closeable}, and flushing the writer will flush the target if it is {@link * java.io.Flushable}. * * @param target the object to which output will be sent * @return a new Writer object, unless target is a Writer, in which case the * target is returned */ public static Writer asWriter(Appendable target) { if (target instanceof Writer) { return (Writer) target; } return new AppendableWriter(target); } // TODO(user): Remove these once Input/OutputSupplier methods are removed static Reader asReader(final Readable readable) { checkNotNull(readable); if (readable instanceof Reader) { return (Reader) readable; } return new Reader() { @Override public int read(char[] cbuf, int off, int len) throws IOException { return read(CharBuffer.wrap(cbuf, off, len)); } @Override public int read(CharBuffer target) throws IOException { return readable.read(target); } @Override public void close() throws IOException { if (readable instanceof Closeable) { ((Closeable) readable).close(); } } }; } /** * Returns a view of the given {@code Readable} supplier as a * {@code CharSource}. * * <p>This method is a temporary method provided for easing migration from * suppliers to sources and sinks. * * @since 15.0 */ public static CharSource asCharSource( final InputSupplier<? extends Readable> supplier) { checkNotNull(supplier); return new CharSource() { @Override public Reader openStream() throws IOException { return asReader(supplier.getInput()); } @Override public String toString() { return "CharStreams.asCharSource(" + supplier + ")"; } }; } /** * Returns a view of the given {@code Appendable} supplier as a * {@code CharSink}. * * <p>This method is a temporary method provided for easing migration from * suppliers to sources and sinks. * * @since 15.0 */ public static CharSink asCharSink( final OutputSupplier<? extends Appendable> supplier) { checkNotNull(supplier); return new CharSink() { @Override public Writer openStream() throws IOException { return asWriter(supplier.getOutput()); } @Override public String toString() { return "CharStreams.asCharSink(" + supplier + ")"; } }; } @SuppressWarnings("unchecked") // used internally where known to be safe static <R extends Reader> InputSupplier<R> asInputSupplier( CharSource source) { return (InputSupplier) checkNotNull(source); } @SuppressWarnings("unchecked") // used internally where known to be safe static <W extends Writer> OutputSupplier<W> asOutputSupplier( CharSink sink) { return (OutputSupplier) checkNotNull(sink); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import java.io.IOException; /** * A factory for readable streams of bytes or characters. * * @author Chris Nokleberg * @since 1.0 */ public interface InputSupplier<T> { /** * Returns an object that encapsulates a readable resource. * <p> * Like {@link Iterable#iterator}, this method may be called repeatedly to * get independent channels to the same underlying resource. * <p> * Where the channel maintains a position within the resource, moving that * cursor within one channel should not affect the starting position of * channels returned by other calls. */ T getInput() throws IOException; }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import static com.google.common.base.Preconditions.checkNotNull; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import javax.annotation.Nullable; /** * An {@link InputStream} that concatenates multiple substreams. At most * one stream will be open at a time. * * @author Chris Nokleberg * @since 1.0 */ final class MultiInputStream extends InputStream { private Iterator<? extends ByteSource> it; private InputStream in; /** * Creates a new instance. * * @param it an iterator of I/O suppliers that will provide each substream */ public MultiInputStream( Iterator<? extends ByteSource> it) throws IOException { this.it = checkNotNull(it); advance(); } @Override public void close() throws IOException { if (in != null) { try { in.close(); } finally { in = null; } } } /** * Closes the current input stream and opens the next one, if any. */ private void advance() throws IOException { close(); if (it.hasNext()) { in = it.next().openStream(); } } @Override public int available() throws IOException { if (in == null) { return 0; } return in.available(); } @Override public boolean markSupported() { return false; } @Override public int read() throws IOException { if (in == null) { return -1; } int result = in.read(); if (result == -1) { advance(); return read(); } return result; } @Override public int read(@Nullable byte[] b, int off, int len) throws IOException { if (in == null) { return -1; } int result = in.read(b, off, len); if (result == -1) { advance(); return read(b, off, len); } return result; } @Override public long skip(long n) throws IOException { if (in == null || n <= 0) { return 0; } long result = in.skip(n); if (result != 0) { return result; } if (read() == -1) { return 0; } return 1 + in.skip(n - 1); } }
Java
/* * Copyright (C) 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.io; import static com.google.common.base.Preconditions.checkNotNull; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; /** * A destination to which bytes can be written, such as a file. Unlike an {@link OutputStream}, a * {@code ByteSink} is not an open, stateful stream that can be written to and closed. Instead, it * is an immutable <i>supplier</i> of {@code OutputStream} instances. * * <p>{@code ByteSink} provides two kinds of methods: * <ul> * <li><b>Methods that return a stream:</b> These methods should return a <i>new</i>, independent * instance each time they are called. The caller is responsible for ensuring that the returned * stream is closed. * <li><b>Convenience methods:</b> These are implementations of common operations that are * typically implemented by opening a stream using one of the methods in the first category, doing * something and finally closing the stream or channel that was opened. * </ul> * * @since 14.0 * @author Colin Decker */ public abstract class ByteSink implements OutputSupplier<OutputStream> { /** * Returns a {@link CharSink} view of this {@code ByteSink} that writes characters to this sink * as bytes encoded with the given {@link Charset charset}. */ public CharSink asCharSink(Charset charset) { return new AsCharSink(charset); } /** * Opens a new {@link OutputStream} for writing to this sink. This method should return a new, * independent stream each time it is called. * * <p>The caller is responsible for ensuring that the returned stream is closed. * * @throws IOException if an I/O error occurs in the process of opening the stream */ public abstract OutputStream openStream() throws IOException; /** * This method is a temporary method provided for easing migration from suppliers to sources and * sinks. * * @since 15.0 * @deprecated This method is only provided for temporary compatibility with the * {@link OutputSupplier} interface and should not be called directly. Use * {@link #openStream} instead. */ @Override @Deprecated public final OutputStream getOutput() throws IOException { return openStream(); } /** * Opens a new buffered {@link OutputStream} for writing to this sink. The returned stream is * not required to be a {@link BufferedOutputStream} in order to allow implementations to simply * delegate to {@link #openStream()} when the stream returned by that method does not benefit * from additional buffering (for example, a {@code ByteArrayOutputStream}). This method should * return a new, independent stream each time it is called. * * <p>The caller is responsible for ensuring that the returned stream is closed. * * @throws IOException if an I/O error occurs in the process of opening the stream * @since 15.0 (in 14.0 with return type {@link BufferedOutputStream}) */ public OutputStream openBufferedStream() throws IOException { OutputStream out = openStream(); return (out instanceof BufferedOutputStream) ? (BufferedOutputStream) out : new BufferedOutputStream(out); } /** * Writes all the given bytes to this sink. * * @throws IOException if an I/O occurs in the process of writing to this sink */ public void write(byte[] bytes) throws IOException { checkNotNull(bytes); Closer closer = Closer.create(); try { OutputStream out = closer.register(openStream()); out.write(bytes); out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Writes all the bytes from the given {@code InputStream} to this sink. Does not close * {@code input}. * * @throws IOException if an I/O occurs in the process of reading from {@code input} or writing to * this sink */ public long writeFrom(InputStream input) throws IOException { checkNotNull(input); Closer closer = Closer.create(); try { OutputStream out = closer.register(openStream()); long written = ByteStreams.copy(input, out); out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 return written; } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * A char sink that encodes written characters with a charset and writes resulting bytes to this * byte sink. */ private final class AsCharSink extends CharSink { private final Charset charset; private AsCharSink(Charset charset) { this.charset = checkNotNull(charset); } @Override public Writer openStream() throws IOException { return new OutputStreamWriter(ByteSink.this.openStream(), charset); } @Override public String toString() { return ByteSink.this.toString() + ".asCharSink(" + charset + ")"; } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import java.io.Closeable; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; /** * Utility methods for working with {@link Closeable} objects. * * @author Michael Lancaster * @since 1.0 */ @Beta public final class Closeables { @VisibleForTesting static final Logger logger = Logger.getLogger(Closeables.class.getName()); private Closeables() {} /** * Closes a {@link Closeable}, with control over whether an {@code IOException} may be thrown. * This is primarily useful in a finally block, where a thrown exception needs to be logged but * not propagated (otherwise the original exception will be lost). * * <p>If {@code swallowIOException} is true then we never throw {@code IOException} but merely log * it. * * <p>Example: <pre> {@code * * public void useStreamNicely() throws IOException { * SomeStream stream = new SomeStream("foo"); * boolean threw = true; * try { * // ... code which does something with the stream ... * threw = false; * } finally { * // If an exception occurs, rethrow it only if threw==false: * Closeables.close(stream, threw); * } * }}</pre> * * @param closeable the {@code Closeable} object to be closed, or null, in which case this method * does nothing * @param swallowIOException if true, don't propagate IO exceptions thrown by the {@code close} * methods * @throws IOException if {@code swallowIOException} is false and {@code close} throws an * {@code IOException}. */ public static void close(@Nullable Closeable closeable, boolean swallowIOException) throws IOException { if (closeable == null) { return; } try { closeable.close(); } catch (IOException e) { if (swallowIOException) { logger.log(Level.WARNING, "IOException thrown while closing Closeable.", e); } else { throw e; } } } /** * Equivalent to calling {@code close(closeable, true)}, but with no IOException in the signature. * * @param closeable the {@code Closeable} object to be closed, or null, in which case this method * does nothing */ public static void closeQuietly(@Nullable Closeable closeable) { try { close(closeable, true); } catch (IOException e) { logger.log(Level.SEVERE, "IOException should not have been thrown.", e); } } }
Java
/* * Copyright (C) 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.io; import static com.google.common.base.Preconditions.checkNotNull; import java.io.BufferedWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; /** * A destination to which characters can be written, such as a text file. Unlike a {@link Writer}, a * {@code CharSink} is not an open, stateful stream that can be written to and closed. Instead, it * is an immutable <i>supplier</i> of {@code Writer} instances. * * <p>{@code CharSink} provides two kinds of methods: * <ul> * <li><b>Methods that return a writer:</b> These methods should return a <i>new</i>, * independent instance each time they are called. The caller is responsible for ensuring that the * returned writer is closed. * <li><b>Convenience methods:</b> These are implementations of common operations that are * typically implemented by opening a writer using one of the methods in the first category, * doing something and finally closing the writer that was opened. * </ul> * * <p>Any {@link ByteSink} may be viewed as a {@code CharSink} with a specific {@linkplain Charset * character encoding} using {@link ByteSink#asCharSink(Charset)}. Characters written to the * resulting {@code CharSink} will written to the {@code ByteSink} as encoded bytes. * * @since 14.0 * @author Colin Decker */ public abstract class CharSink implements OutputSupplier<Writer> { /** * Opens a new {@link Writer} for writing to this sink. This method should return a new, * independent writer each time it is called. * * <p>The caller is responsible for ensuring that the returned writer is closed. * * @throws IOException if an I/O error occurs in the process of opening the writer */ public abstract Writer openStream() throws IOException; /** * This method is a temporary method provided for easing migration from suppliers to sources and * sinks. * * @since 15.0 * @deprecated This method is only provided for temporary compatibility with the * {@link OutputSupplier} interface and should not be called directly. Use * {@link #openStream} instead. */ @Override @Deprecated public final Writer getOutput() throws IOException { return openStream(); } /** * Opens a new buffered {@link Writer} for writing to this sink. The returned stream is not * required to be a {@link BufferedWriter} in order to allow implementations to simply delegate * to {@link #openStream()} when the stream returned by that method does not benefit from * additional buffering. This method should return a new, independent writer each time it is * called. * * <p>The caller is responsible for ensuring that the returned writer is closed. * * @throws IOException if an I/O error occurs in the process of opening the writer * @since 15.0 (in 14.0 with return type {@link BufferedWriter}) */ public Writer openBufferedStream() throws IOException { Writer writer = openStream(); return (writer instanceof BufferedWriter) ? (BufferedWriter) writer : new BufferedWriter(writer); } /** * Writes the given character sequence to this sink. * * @throws IOException if an I/O error in the process of writing to this sink */ public void write(CharSequence charSequence) throws IOException { checkNotNull(charSequence); Closer closer = Closer.create(); try { Writer out = closer.register(openStream()); out.append(charSequence); out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Writes the given lines of text to this sink with each line (including the last) terminated with * the operating system's default line separator. This method is equivalent to * {@code writeLines(lines, System.getProperty("line.separator"))}. * * @throws IOException if an I/O error occurs in the process of writing to this sink */ public void writeLines(Iterable<? extends CharSequence> lines) throws IOException { writeLines(lines, System.getProperty("line.separator")); } /** * Writes the given lines of text to this sink with each line (including the last) terminated with * the given line separator. * * @throws IOException if an I/O error occurs in the process of writing to this sink */ public void writeLines(Iterable<? extends CharSequence> lines, String lineSeparator) throws IOException { checkNotNull(lines); checkNotNull(lineSeparator); Closer closer = Closer.create(); try { Writer out = closer.register(openBufferedStream()); for (CharSequence line : lines) { out.append(line).append(lineSeparator); } out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Writes all the text from the given {@link Readable} (such as a {@link Reader}) to this sink. * Does not close {@code readable} if it is {@code Closeable}. * * @throws IOException if an I/O error occurs in the process of reading from {@code readable} or * writing to this sink */ public long writeFrom(Readable readable) throws IOException { checkNotNull(readable); Closer closer = Closer.create(); try { Writer out = closer.register(openStream()); long written = CharStreams.copy(readable, out); out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 return written; } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import java.io.IOException; import java.io.Reader; import java.nio.CharBuffer; import java.util.LinkedList; import java.util.Queue; /** * A class for reading lines of text. Provides the same functionality * as {@link java.io.BufferedReader#readLine()} but for all {@link Readable} * objects, not just instances of {@link Reader}. * * @author Chris Nokleberg * @since 1.0 */ @Beta public final class LineReader { private final Readable readable; private final Reader reader; private final char[] buf = new char[0x1000]; // 4K private final CharBuffer cbuf = CharBuffer.wrap(buf); private final Queue<String> lines = new LinkedList<String>(); private final LineBuffer lineBuf = new LineBuffer() { @Override protected void handleLine(String line, String end) { lines.add(line); } }; /** * Creates a new instance that will read lines from the given * {@code Readable} object. */ public LineReader(Readable readable) { Preconditions.checkNotNull(readable); this.readable = readable; this.reader = (readable instanceof Reader) ? (Reader) readable : null; } /** * Reads a line of text. A line is considered to be terminated by any * one of a line feed ({@code '\n'}), a carriage return * ({@code '\r'}), or a carriage return followed immediately by a linefeed * ({@code "\r\n"}). * * @return a {@code String} containing the contents of the line, not * including any line-termination characters, or {@code null} if the * end of the stream has been reached. * @throws IOException if an I/O error occurs */ public String readLine() throws IOException { while (lines.peek() == null) { cbuf.clear(); // The default implementation of Reader#read(CharBuffer) allocates a // temporary char[], so we call Reader#read(char[], int, int) instead. int read = (reader != null) ? reader.read(buf, 0, buf.length) : readable.read(cbuf); if (read == -1) { lineBuf.finish(); break; } lineBuf.add(buf, 0, read); } return lines.poll(); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import com.google.common.primitives.Longs; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; /** * An implementation of {@link DataOutput} that uses little-endian byte ordering * for writing {@code char}, {@code short}, {@code int}, {@code float}, {@code * double}, and {@code long} values. * <p> * <b>Note:</b> This class intentionally violates the specification of its * supertype {@code DataOutput}, which explicitly requires big-endian byte * order. * * @author Chris Nokleberg * @author Keith Bottner * @since 8.0 */ @Beta public class LittleEndianDataOutputStream extends FilterOutputStream implements DataOutput { /** * Creates a {@code LittleEndianDataOutputStream} that wraps the given stream. * * @param out the stream to delegate to */ public LittleEndianDataOutputStream(OutputStream out) { super(new DataOutputStream(Preconditions.checkNotNull(out))); } @Override public void write(byte[] b, int off, int len) throws IOException { // Override slow FilterOutputStream impl out.write(b, off, len); } @Override public void writeBoolean(boolean v) throws IOException { ((DataOutputStream) out).writeBoolean(v); } @Override public void writeByte(int v) throws IOException { ((DataOutputStream) out).writeByte(v); } /** * @deprecated The semantics of {@code writeBytes(String s)} are considered * dangerous. Please use {@link #writeUTF(String s)}, * {@link #writeChars(String s)} or another write method instead. */ @Deprecated @Override public void writeBytes(String s) throws IOException { ((DataOutputStream) out).writeBytes(s); } /** * Writes a char as specified by {@link DataOutputStream#writeChar(int)}, * except using little-endian byte order. * * @throws IOException if an I/O error occurs */ @Override public void writeChar(int v) throws IOException { writeShort(v); } /** * Writes a {@code String} as specified by * {@link DataOutputStream#writeChars(String)}, except each character is * written using little-endian byte order. * * @throws IOException if an I/O error occurs */ @Override public void writeChars(String s) throws IOException { for (int i = 0; i < s.length(); i++) { writeChar(s.charAt(i)); } } /** * Writes a {@code double} as specified by * {@link DataOutputStream#writeDouble(double)}, except using little-endian * byte order. * * @throws IOException if an I/O error occurs */ @Override public void writeDouble(double v) throws IOException { writeLong(Double.doubleToLongBits(v)); } /** * Writes a {@code float} as specified by * {@link DataOutputStream#writeFloat(float)}, except using little-endian byte * order. * * @throws IOException if an I/O error occurs */ @Override public void writeFloat(float v) throws IOException { writeInt(Float.floatToIntBits(v)); } /** * Writes an {@code int} as specified by * {@link DataOutputStream#writeInt(int)}, except using little-endian byte * order. * * @throws IOException if an I/O error occurs */ @Override public void writeInt(int v) throws IOException { out.write(0xFF & v); out.write(0xFF & (v >> 8)); out.write(0xFF & (v >> 16)); out.write(0xFF & (v >> 24)); } /** * Writes a {@code long} as specified by * {@link DataOutputStream#writeLong(long)}, except using little-endian byte * order. * * @throws IOException if an I/O error occurs */ @Override public void writeLong(long v) throws IOException { byte[] bytes = Longs.toByteArray(Long.reverseBytes(v)); write(bytes, 0, bytes.length); } /** * Writes a {@code short} as specified by * {@link DataOutputStream#writeShort(int)}, except using little-endian byte * order. * * @throws IOException if an I/O error occurs */ @Override public void writeShort(int v) throws IOException { out.write(0xFF & v); out.write(0xFF & (v >> 8)); } @Override public void writeUTF(String str) throws IOException { ((DataOutputStream) out).writeUTF(str); } }
Java
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import java.io.File; import java.io.FilenameFilter; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.annotation.Nullable; /** * File name filter that only accepts files matching a regular expression. This * class is thread-safe and immutable. * * @author Apple Chow * @since 1.0 */ @Beta public final class PatternFilenameFilter implements FilenameFilter { private final Pattern pattern; /** * Constructs a pattern file name filter object. * @param patternStr the pattern string on which to filter file names * * @throws PatternSyntaxException if pattern compilation fails (runtime) */ public PatternFilenameFilter(String patternStr) { this(Pattern.compile(patternStr)); } /** * Constructs a pattern file name filter object. * @param pattern the pattern on which to filter file names */ public PatternFilenameFilter(Pattern pattern) { this.pattern = Preconditions.checkNotNull(pattern); } @Override public boolean accept(@Nullable File dir, String fileName) { return pattern.matcher(fileName).matches(); } }
Java
/* * Copyright (C) 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.io; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import static com.google.common.base.Preconditions.checkState; import static com.google.common.io.GwtWorkarounds.asCharInput; import static com.google.common.io.GwtWorkarounds.asCharOutput; import static com.google.common.io.GwtWorkarounds.asInputStream; import static com.google.common.io.GwtWorkarounds.asOutputStream; import static com.google.common.io.GwtWorkarounds.stringBuilderOutput; import static com.google.common.math.IntMath.divide; import static com.google.common.math.IntMath.log2; import static java.math.RoundingMode.CEILING; import static java.math.RoundingMode.FLOOR; import static java.math.RoundingMode.UNNECESSARY; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Ascii; import com.google.common.base.CharMatcher; import com.google.common.io.GwtWorkarounds.ByteInput; import com.google.common.io.GwtWorkarounds.ByteOutput; import com.google.common.io.GwtWorkarounds.CharInput; import com.google.common.io.GwtWorkarounds.CharOutput; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.util.Arrays; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; /** * A binary encoding scheme for reversibly translating between byte sequences and printable ASCII * strings. This class includes several constants for encoding schemes specified by <a * href="http://tools.ietf.org/html/rfc4648">RFC 4648</a>. For example, the expression: * * <pre> {@code * BaseEncoding.base32().encode("foo".getBytes(Charsets.US_ASCII))}</pre> * * <p>returns the string {@code "MZXW6==="}, and <pre> {@code * byte[] decoded = BaseEncoding.base32().decode("MZXW6===");}</pre> * * <p>...returns the ASCII bytes of the string {@code "foo"}. * * <p>By default, {@code BaseEncoding}'s behavior is relatively strict and in accordance with * RFC 4648. Decoding rejects characters in the wrong case, though padding is optional. * To modify encoding and decoding behavior, use configuration methods to obtain a new encoding * with modified behavior: * * <pre> {@code * BaseEncoding.base16().lowerCase().decode("deadbeef");}</pre> * * <p>Warning: BaseEncoding instances are immutable. Invoking a configuration method has no effect * on the receiving instance; you must store and use the new encoding instance it returns, instead. * * <pre> {@code * // Do NOT do this * BaseEncoding hex = BaseEncoding.base16(); * hex.lowerCase(); // does nothing! * return hex.decode("deadbeef"); // throws an IllegalArgumentException}</pre> * * <p>It is guaranteed that {@code encoding.decode(encoding.encode(x))} is always equal to * {@code x}, but the reverse does not necessarily hold. * * <p> * <table> * <tr> * <th>Encoding * <th>Alphabet * <th>{@code char:byte} ratio * <th>Default padding * <th>Comments * <tr> * <td>{@link #base16()} * <td>0-9 A-F * <td>2.00 * <td>N/A * <td>Traditional hexadecimal. Defaults to upper case. * <tr> * <td>{@link #base32()} * <td>A-Z 2-7 * <td>1.60 * <td>= * <td>Human-readable; no possibility of mixing up 0/O or 1/I. Defaults to upper case. * <tr> * <td>{@link #base32Hex()} * <td>0-9 A-V * <td>1.60 * <td>= * <td>"Numerical" base 32; extended from the traditional hex alphabet. Defaults to upper case. * <tr> * <td>{@link #base64()} * <td>A-Z a-z 0-9 + / * <td>1.33 * <td>= * <td> * <tr> * <td>{@link #base64Url()} * <td>A-Z a-z 0-9 - _ * <td>1.33 * <td>= * <td>Safe to use as filenames, or to pass in URLs without escaping * </table> * * <p> * All instances of this class are immutable, so they may be stored safely as static constants. * * @author Louis Wasserman * @since 14.0 */ @Beta @GwtCompatible(emulated = true) public abstract class BaseEncoding { // TODO(user): consider adding encodeTo(Appendable, byte[], [int, int]) BaseEncoding() {} /** * Exception indicating invalid base-encoded input encountered while decoding. * * @author Louis Wasserman * @since 15.0 */ public static final class DecodingException extends IOException { DecodingException(String message) { super(message); } DecodingException(Throwable cause) { super(cause); } } /** * Encodes the specified byte array, and returns the encoded {@code String}. */ public String encode(byte[] bytes) { return encode(checkNotNull(bytes), 0, bytes.length); } /** * Encodes the specified range of the specified byte array, and returns the encoded * {@code String}. */ public final String encode(byte[] bytes, int off, int len) { checkNotNull(bytes); checkPositionIndexes(off, off + len, bytes.length); CharOutput result = stringBuilderOutput(maxEncodedSize(len)); ByteOutput byteOutput = encodingStream(result); try { for (int i = 0; i < len; i++) { byteOutput.write(bytes[off + i]); } byteOutput.close(); } catch (IOException impossible) { throw new AssertionError("impossible"); } return result.toString(); } /** * Returns an {@code OutputStream} that encodes bytes using this encoding into the specified * {@code Writer}. When the returned {@code OutputStream} is closed, so is the backing * {@code Writer}. */ @GwtIncompatible("Writer,OutputStream") public final OutputStream encodingStream(Writer writer) { return asOutputStream(encodingStream(asCharOutput(writer))); } /** * Returns an {@code OutputSupplier} that supplies streams that encode bytes using this encoding * into writers from the specified {@code OutputSupplier}. * * @deprecated Use {@link #encodingSink(CharSink)} instead. This method is scheduled to be * removed in Guava 16.0. */ @Deprecated @GwtIncompatible("Writer,OutputStream") public final OutputSupplier<OutputStream> encodingStream( final OutputSupplier<? extends Writer> writerSupplier) { checkNotNull(writerSupplier); return new OutputSupplier<OutputStream>() { @Override public OutputStream getOutput() throws IOException { return encodingStream(writerSupplier.getOutput()); } }; } /** * Returns a {@code ByteSink} that writes base-encoded bytes to the specified {@code CharSink}. */ @GwtIncompatible("ByteSink,CharSink") public final ByteSink encodingSink(final CharSink encodedSink) { checkNotNull(encodedSink); return new ByteSink() { @Override public OutputStream openStream() throws IOException { return encodingStream(encodedSink.openStream()); } }; } // TODO(user): document the extent of leniency, probably after adding ignore(CharMatcher) private static byte[] extract(byte[] result, int length) { if (length == result.length) { return result; } else { byte[] trunc = new byte[length]; System.arraycopy(result, 0, trunc, 0, length); return trunc; } } /** * Decodes the specified character sequence, and returns the resulting {@code byte[]}. * This is the inverse operation to {@link #encode(byte[])}. * * @throws IllegalArgumentException if the input is not a valid encoded string according to this * encoding. */ public final byte[] decode(CharSequence chars) { try { return decodeChecked(chars); } catch (DecodingException badInput) { throw new IllegalArgumentException(badInput); } } /** * Decodes the specified character sequence, and returns the resulting {@code byte[]}. * This is the inverse operation to {@link #encode(byte[])}. * * @throws DecodingException if the input is not a valid encoded string according to this * encoding. */ final byte[] decodeChecked(CharSequence chars) throws DecodingException { chars = padding().trimTrailingFrom(chars); ByteInput decodedInput = decodingStream(asCharInput(chars)); byte[] tmp = new byte[maxDecodedSize(chars.length())]; int index = 0; try { for (int i = decodedInput.read(); i != -1; i = decodedInput.read()) { tmp[index++] = (byte) i; } } catch (DecodingException badInput) { throw badInput; } catch (IOException impossible) { throw new AssertionError(impossible); } return extract(tmp, index); } /** * Returns an {@code InputStream} that decodes base-encoded input from the specified * {@code Reader}. The returned stream throws a {@link DecodingException} upon decoding-specific * errors. */ @GwtIncompatible("Reader,InputStream") public final InputStream decodingStream(Reader reader) { return asInputStream(decodingStream(asCharInput(reader))); } /** * Returns an {@code InputSupplier} that supplies input streams that decode base-encoded input * from readers from the specified supplier. * * @deprecated Use {@link #decodingSource(CharSource)} instead. This method is scheduled to be * removed in Guava 16.0. */ @Deprecated @GwtIncompatible("Reader,InputStream") public final InputSupplier<InputStream> decodingStream( final InputSupplier<? extends Reader> readerSupplier) { checkNotNull(readerSupplier); return new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { return decodingStream(readerSupplier.getInput()); } }; } /** * Returns a {@code ByteSource} that reads base-encoded bytes from the specified * {@code CharSource}. */ @GwtIncompatible("ByteSource,CharSource") public final ByteSource decodingSource(final CharSource encodedSource) { checkNotNull(encodedSource); return new ByteSource() { @Override public InputStream openStream() throws IOException { return decodingStream(encodedSource.openStream()); } }; } // Implementations for encoding/decoding abstract int maxEncodedSize(int bytes); abstract ByteOutput encodingStream(CharOutput charOutput); abstract int maxDecodedSize(int chars); abstract ByteInput decodingStream(CharInput charInput); abstract CharMatcher padding(); // Modified encoding generators /** * Returns an encoding that behaves equivalently to this encoding, but omits any padding * characters as specified by <a href="http://tools.ietf.org/html/rfc4648#section-3.2">RFC 4648 * section 3.2</a>, Padding of Encoded Data. */ @CheckReturnValue public abstract BaseEncoding omitPadding(); /** * Returns an encoding that behaves equivalently to this encoding, but uses an alternate character * for padding. * * @throws IllegalArgumentException if this padding character is already used in the alphabet or a * separator */ @CheckReturnValue public abstract BaseEncoding withPadChar(char padChar); /** * Returns an encoding that behaves equivalently to this encoding, but adds a separator string * after every {@code n} characters. Any occurrences of any characters that occur in the separator * are skipped over in decoding. * * @throws IllegalArgumentException if any alphabet or padding characters appear in the separator * string, or if {@code n <= 0} * @throws UnsupportedOperationException if this encoding already uses a separator */ @CheckReturnValue public abstract BaseEncoding withSeparator(String separator, int n); /** * Returns an encoding that behaves equivalently to this encoding, but encodes and decodes with * uppercase letters. Padding and separator characters remain in their original case. * * @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and * lower-case characters */ @CheckReturnValue public abstract BaseEncoding upperCase(); /** * Returns an encoding that behaves equivalently to this encoding, but encodes and decodes with * lowercase letters. Padding and separator characters remain in their original case. * * @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and * lower-case characters */ @CheckReturnValue public abstract BaseEncoding lowerCase(); private static final BaseEncoding BASE64 = new StandardBaseEncoding( "base64()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", '='); /** * The "base64" base encoding specified by <a * href="http://tools.ietf.org/html/rfc4648#section-4">RFC 4648 section 4</a>, Base 64 Encoding. * (This is the same as the base 64 encoding from <a * href="http://tools.ietf.org/html/rfc3548#section-3">RFC 3548</a>.) * * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding() * omitted} or {@linkplain #withPadChar(char) replaced}. * * <p>No line feeds are added by default, as per <a * href="http://tools.ietf.org/html/rfc4648#section-3.1"> RFC 4648 section 3.1</a>, Line Feeds in * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}. */ public static BaseEncoding base64() { return BASE64; } private static final BaseEncoding BASE64_URL = new StandardBaseEncoding( "base64Url()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", '='); /** * The "base64url" encoding specified by <a * href="http://tools.ietf.org/html/rfc4648#section-5">RFC 4648 section 5</a>, Base 64 Encoding * with URL and Filename Safe Alphabet, also sometimes referred to as the "web safe Base64." * (This is the same as the base 64 encoding with URL and filename safe alphabet from <a * href="http://tools.ietf.org/html/rfc3548#section-4">RFC 3548</a>.) * * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding() * omitted} or {@linkplain #withPadChar(char) replaced}. * * <p>No line feeds are added by default, as per <a * href="http://tools.ietf.org/html/rfc4648#section-3.1"> RFC 4648 section 3.1</a>, Line Feeds in * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}. */ public static BaseEncoding base64Url() { return BASE64_URL; } private static final BaseEncoding BASE32 = new StandardBaseEncoding("base32()", "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", '='); /** * The "base32" encoding specified by <a * href="http://tools.ietf.org/html/rfc4648#section-6">RFC 4648 section 6</a>, Base 32 Encoding. * (This is the same as the base 32 encoding from <a * href="http://tools.ietf.org/html/rfc3548#section-5">RFC 3548</a>.) * * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding() * omitted} or {@linkplain #withPadChar(char) replaced}. * * <p>No line feeds are added by default, as per <a * href="http://tools.ietf.org/html/rfc4648#section-3.1"> RFC 4648 section 3.1</a>, Line Feeds in * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}. */ public static BaseEncoding base32() { return BASE32; } private static final BaseEncoding BASE32_HEX = new StandardBaseEncoding("base32Hex()", "0123456789ABCDEFGHIJKLMNOPQRSTUV", '='); /** * The "base32hex" encoding specified by <a * href="http://tools.ietf.org/html/rfc4648#section-7">RFC 4648 section 7</a>, Base 32 Encoding * with Extended Hex Alphabet. There is no corresponding encoding in RFC 3548. * * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding() * omitted} or {@linkplain #withPadChar(char) replaced}. * * <p>No line feeds are added by default, as per <a * href="http://tools.ietf.org/html/rfc4648#section-3.1"> RFC 4648 section 3.1</a>, Line Feeds in * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}. */ public static BaseEncoding base32Hex() { return BASE32_HEX; } private static final BaseEncoding BASE16 = new StandardBaseEncoding("base16()", "0123456789ABCDEF", null); /** * The "base16" encoding specified by <a * href="http://tools.ietf.org/html/rfc4648#section-8">RFC 4648 section 8</a>, Base 16 Encoding. * (This is the same as the base 16 encoding from <a * href="http://tools.ietf.org/html/rfc3548#section-6">RFC 3548</a>.) This is commonly known as * "hexadecimal" format. * * <p>No padding is necessary in base 16, so {@link #withPadChar(char)} and * {@link #omitPadding()} have no effect. * * <p>No line feeds are added by default, as per <a * href="http://tools.ietf.org/html/rfc4648#section-3.1"> RFC 4648 section 3.1</a>, Line Feeds in * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}. */ public static BaseEncoding base16() { return BASE16; } private static final class Alphabet extends CharMatcher { private final String name; // this is meant to be immutable -- don't modify it! private final char[] chars; final int mask; final int bitsPerChar; final int charsPerChunk; final int bytesPerChunk; private final byte[] decodabet; private final boolean[] validPadding; Alphabet(String name, char[] chars) { this.name = checkNotNull(name); this.chars = checkNotNull(chars); try { this.bitsPerChar = log2(chars.length, UNNECESSARY); } catch (ArithmeticException e) { throw new IllegalArgumentException("Illegal alphabet length " + chars.length, e); } /* * e.g. for base64, bitsPerChar == 6, charsPerChunk == 4, and bytesPerChunk == 3. This makes * for the smallest chunk size that still has charsPerChunk * bitsPerChar be a multiple of 8. */ int gcd = Math.min(8, Integer.lowestOneBit(bitsPerChar)); this.charsPerChunk = 8 / gcd; this.bytesPerChunk = bitsPerChar / gcd; this.mask = chars.length - 1; byte[] decodabet = new byte[Ascii.MAX + 1]; Arrays.fill(decodabet, (byte) -1); for (int i = 0; i < chars.length; i++) { char c = chars[i]; checkArgument(CharMatcher.ASCII.matches(c), "Non-ASCII character: %s", c); checkArgument(decodabet[c] == -1, "Duplicate character: %s", c); decodabet[c] = (byte) i; } this.decodabet = decodabet; boolean[] validPadding = new boolean[charsPerChunk]; for (int i = 0; i < bytesPerChunk; i++) { validPadding[divide(i * 8, bitsPerChar, CEILING)] = true; } this.validPadding = validPadding; } char encode(int bits) { return chars[bits]; } boolean isValidPaddingStartPosition(int index) { return validPadding[index % charsPerChunk]; } int decode(char ch) throws IOException { if (ch > Ascii.MAX || decodabet[ch] == -1) { throw new DecodingException("Unrecognized character: " + ch); } return decodabet[ch]; } private boolean hasLowerCase() { for (char c : chars) { if (Ascii.isLowerCase(c)) { return true; } } return false; } private boolean hasUpperCase() { for (char c : chars) { if (Ascii.isUpperCase(c)) { return true; } } return false; } Alphabet upperCase() { if (!hasLowerCase()) { return this; } else { checkState(!hasUpperCase(), "Cannot call upperCase() on a mixed-case alphabet"); char[] upperCased = new char[chars.length]; for (int i = 0; i < chars.length; i++) { upperCased[i] = Ascii.toUpperCase(chars[i]); } return new Alphabet(name + ".upperCase()", upperCased); } } Alphabet lowerCase() { if (!hasUpperCase()) { return this; } else { checkState(!hasLowerCase(), "Cannot call lowerCase() on a mixed-case alphabet"); char[] lowerCased = new char[chars.length]; for (int i = 0; i < chars.length; i++) { lowerCased[i] = Ascii.toLowerCase(chars[i]); } return new Alphabet(name + ".lowerCase()", lowerCased); } } @Override public boolean matches(char c) { return CharMatcher.ASCII.matches(c) && decodabet[c] != -1; } @Override public String toString() { return name; } } static final class StandardBaseEncoding extends BaseEncoding { // TODO(user): provide a useful toString private final Alphabet alphabet; @Nullable private final Character paddingChar; StandardBaseEncoding(String name, String alphabetChars, @Nullable Character paddingChar) { this(new Alphabet(name, alphabetChars.toCharArray()), paddingChar); } StandardBaseEncoding(Alphabet alphabet, @Nullable Character paddingChar) { this.alphabet = checkNotNull(alphabet); checkArgument(paddingChar == null || !alphabet.matches(paddingChar), "Padding character %s was already in alphabet", paddingChar); this.paddingChar = paddingChar; } @Override CharMatcher padding() { return (paddingChar == null) ? CharMatcher.NONE : CharMatcher.is(paddingChar.charValue()); } @Override int maxEncodedSize(int bytes) { return alphabet.charsPerChunk * divide(bytes, alphabet.bytesPerChunk, CEILING); } @Override ByteOutput encodingStream(final CharOutput out) { checkNotNull(out); return new ByteOutput() { int bitBuffer = 0; int bitBufferLength = 0; int writtenChars = 0; @Override public void write(byte b) throws IOException { bitBuffer <<= 8; bitBuffer |= b & 0xFF; bitBufferLength += 8; while (bitBufferLength >= alphabet.bitsPerChar) { int charIndex = (bitBuffer >> (bitBufferLength - alphabet.bitsPerChar)) & alphabet.mask; out.write(alphabet.encode(charIndex)); writtenChars++; bitBufferLength -= alphabet.bitsPerChar; } } @Override public void flush() throws IOException { out.flush(); } @Override public void close() throws IOException { if (bitBufferLength > 0) { int charIndex = (bitBuffer << (alphabet.bitsPerChar - bitBufferLength)) & alphabet.mask; out.write(alphabet.encode(charIndex)); writtenChars++; if (paddingChar != null) { while (writtenChars % alphabet.charsPerChunk != 0) { out.write(paddingChar.charValue()); writtenChars++; } } } out.close(); } }; } @Override int maxDecodedSize(int chars) { return (int) ((alphabet.bitsPerChar * (long) chars + 7L) / 8L); } @Override ByteInput decodingStream(final CharInput reader) { checkNotNull(reader); return new ByteInput() { int bitBuffer = 0; int bitBufferLength = 0; int readChars = 0; boolean hitPadding = false; final CharMatcher paddingMatcher = padding(); @Override public int read() throws IOException { while (true) { int readChar = reader.read(); if (readChar == -1) { if (!hitPadding && !alphabet.isValidPaddingStartPosition(readChars)) { throw new DecodingException("Invalid input length " + readChars); } return -1; } readChars++; char ch = (char) readChar; if (paddingMatcher.matches(ch)) { if (!hitPadding && (readChars == 1 || !alphabet.isValidPaddingStartPosition(readChars - 1))) { throw new DecodingException("Padding cannot start at index " + readChars); } hitPadding = true; } else if (hitPadding) { throw new DecodingException( "Expected padding character but found '" + ch + "' at index " + readChars); } else { bitBuffer <<= alphabet.bitsPerChar; bitBuffer |= alphabet.decode(ch); bitBufferLength += alphabet.bitsPerChar; if (bitBufferLength >= 8) { bitBufferLength -= 8; return (bitBuffer >> bitBufferLength) & 0xFF; } } } } @Override public void close() throws IOException { reader.close(); } }; } @Override public BaseEncoding omitPadding() { return (paddingChar == null) ? this : new StandardBaseEncoding(alphabet, null); } @Override public BaseEncoding withPadChar(char padChar) { if (8 % alphabet.bitsPerChar == 0 || (paddingChar != null && paddingChar.charValue() == padChar)) { return this; } else { return new StandardBaseEncoding(alphabet, padChar); } } @Override public BaseEncoding withSeparator(String separator, int afterEveryChars) { checkNotNull(separator); checkArgument(padding().or(alphabet).matchesNoneOf(separator), "Separator cannot contain alphabet or padding characters"); return new SeparatedBaseEncoding(this, separator, afterEveryChars); } private transient BaseEncoding upperCase; private transient BaseEncoding lowerCase; @Override public BaseEncoding upperCase() { BaseEncoding result = upperCase; if (result == null) { Alphabet upper = alphabet.upperCase(); result = upperCase = (upper == alphabet) ? this : new StandardBaseEncoding(upper, paddingChar); } return result; } @Override public BaseEncoding lowerCase() { BaseEncoding result = lowerCase; if (result == null) { Alphabet lower = alphabet.lowerCase(); result = lowerCase = (lower == alphabet) ? this : new StandardBaseEncoding(lower, paddingChar); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder("BaseEncoding."); builder.append(alphabet.toString()); if (8 % alphabet.bitsPerChar != 0) { if (paddingChar == null) { builder.append(".omitPadding()"); } else { builder.append(".withPadChar(").append(paddingChar).append(')'); } } return builder.toString(); } } static CharInput ignoringInput(final CharInput delegate, final CharMatcher toIgnore) { checkNotNull(delegate); checkNotNull(toIgnore); return new CharInput() { @Override public int read() throws IOException { int readChar; do { readChar = delegate.read(); } while (readChar != -1 && toIgnore.matches((char) readChar)); return readChar; } @Override public void close() throws IOException { delegate.close(); } }; } static CharOutput separatingOutput( final CharOutput delegate, final String separator, final int afterEveryChars) { checkNotNull(delegate); checkNotNull(separator); checkArgument(afterEveryChars > 0); return new CharOutput() { int charsUntilSeparator = afterEveryChars; @Override public void write(char c) throws IOException { if (charsUntilSeparator == 0) { for (int i = 0; i < separator.length(); i++) { delegate.write(separator.charAt(i)); } charsUntilSeparator = afterEveryChars; } delegate.write(c); charsUntilSeparator--; } @Override public void flush() throws IOException { delegate.flush(); } @Override public void close() throws IOException { delegate.close(); } }; } static final class SeparatedBaseEncoding extends BaseEncoding { private final BaseEncoding delegate; private final String separator; private final int afterEveryChars; private final CharMatcher separatorChars; SeparatedBaseEncoding(BaseEncoding delegate, String separator, int afterEveryChars) { this.delegate = checkNotNull(delegate); this.separator = checkNotNull(separator); this.afterEveryChars = afterEveryChars; checkArgument( afterEveryChars > 0, "Cannot add a separator after every %s chars", afterEveryChars); this.separatorChars = CharMatcher.anyOf(separator).precomputed(); } @Override CharMatcher padding() { return delegate.padding(); } @Override int maxEncodedSize(int bytes) { int unseparatedSize = delegate.maxEncodedSize(bytes); return unseparatedSize + separator.length() * divide(Math.max(0, unseparatedSize - 1), afterEveryChars, FLOOR); } @Override ByteOutput encodingStream(final CharOutput output) { return delegate.encodingStream(separatingOutput(output, separator, afterEveryChars)); } @Override int maxDecodedSize(int chars) { return delegate.maxDecodedSize(chars); } @Override ByteInput decodingStream(final CharInput input) { return delegate.decodingStream(ignoringInput(input, separatorChars)); } @Override public BaseEncoding omitPadding() { return delegate.omitPadding().withSeparator(separator, afterEveryChars); } @Override public BaseEncoding withPadChar(char padChar) { return delegate.withPadChar(padChar).withSeparator(separator, afterEveryChars); } @Override public BaseEncoding withSeparator(String separator, int afterEveryChars) { throw new UnsupportedOperationException("Already have a separator"); } @Override public BaseEncoding upperCase() { return delegate.upperCase().withSeparator(separator, afterEveryChars); } @Override public BaseEncoding lowerCase() { return delegate.lowerCase().withSeparator(separator, afterEveryChars); } @Override public String toString() { return delegate.toString() + ".withSeparator(\"" + separator + "\", " + afterEveryChars + ")"; } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.base.Charsets; import com.google.common.base.Objects; import com.google.common.collect.Lists; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URL; import java.nio.charset.Charset; import java.util.List; /** * Provides utility methods for working with resources in the classpath. * Note that even though these methods use {@link URL} parameters, they * are usually not appropriate for HTTP or other non-classpath resources. * * <p>All method parameters must be non-null unless documented otherwise. * * @author Chris Nokleberg * @author Ben Yu * @author Colin Decker * @since 1.0 */ @Beta public final class Resources { private Resources() {} /** * Returns a factory that will supply instances of {@link InputStream} that * read from the given URL. * * @param url the URL to read from * @return the factory */ public static InputSupplier<InputStream> newInputStreamSupplier(URL url) { return ByteStreams.asInputSupplier(asByteSource(url)); } /** * Returns a {@link ByteSource} that reads from the given URL. * * @since 14.0 */ public static ByteSource asByteSource(URL url) { return new UrlByteSource(url); } /** * A byte source that reads from a URL using {@link URL#openStream()}. */ private static final class UrlByteSource extends ByteSource { private final URL url; private UrlByteSource(URL url) { this.url = checkNotNull(url); } @Override public InputStream openStream() throws IOException { return url.openStream(); } @Override public String toString() { return "Resources.asByteSource(" + url + ")"; } } /** * Returns a factory that will supply instances of * {@link InputStreamReader} that read a URL using the given character set. * * @param url the URL to read from * @param charset the charset used to decode the input stream; see {@link * Charsets} for helpful predefined constants * @return the factory */ public static InputSupplier<InputStreamReader> newReaderSupplier( URL url, Charset charset) { return CharStreams.asInputSupplier(asCharSource(url, charset)); } /** * Returns a {@link CharSource} that reads from the given URL using the given character set. * * @since 14.0 */ public static CharSource asCharSource(URL url, Charset charset) { return asByteSource(url).asCharSource(charset); } /** * Reads all bytes from a URL into a byte array. * * @param url the URL to read from * @return a byte array containing all the bytes from the URL * @throws IOException if an I/O error occurs */ public static byte[] toByteArray(URL url) throws IOException { return asByteSource(url).read(); } /** * Reads all characters from a URL into a {@link String}, using the given * character set. * * @param url the URL to read from * @param charset the charset used to decode the input stream; see {@link * Charsets} for helpful predefined constants * @return a string containing all the characters from the URL * @throws IOException if an I/O error occurs. */ public static String toString(URL url, Charset charset) throws IOException { return asCharSource(url, charset).read(); } /** * Streams lines from a URL, stopping when our callback returns false, or we * have read all of the lines. * * @param url the URL to read from * @param charset the charset used to decode the input stream; see {@link * Charsets} for helpful predefined constants * @param callback the LineProcessor to use to handle the lines * @return the output of processing the lines * @throws IOException if an I/O error occurs */ public static <T> T readLines(URL url, Charset charset, LineProcessor<T> callback) throws IOException { return CharStreams.readLines(newReaderSupplier(url, charset), callback); } /** * Reads all of the lines from a URL. The lines do not include * line-termination characters, but do include other leading and trailing * whitespace. * * <p>This method returns a mutable {@code List}. For an * {@code ImmutableList}, use * {@code Resources.asCharSource(url, charset).readLines()}. * * @param url the URL to read from * @param charset the charset used to decode the input stream; see {@link * Charsets} for helpful predefined constants * @return a mutable {@link List} containing all the lines * @throws IOException if an I/O error occurs */ public static List<String> readLines(URL url, Charset charset) throws IOException { // don't use asCharSource(url, charset).readLines() because that returns // an immutable list, which would change the behavior of this method return readLines(url, charset, new LineProcessor<List<String>>() { final List<String> result = Lists.newArrayList(); @Override public boolean processLine(String line) { result.add(line); return true; } @Override public List<String> getResult() { return result; } }); } /** * Copies all bytes from a URL to an output stream. * * @param from the URL to read from * @param to the output stream * @throws IOException if an I/O error occurs */ public static void copy(URL from, OutputStream to) throws IOException { asByteSource(from).copyTo(to); } /** * Returns a {@code URL} pointing to {@code resourceName} if the resource is * found using the {@linkplain Thread#getContextClassLoader() context class * loader}. In simple environments, the context class loader will find * resources from the class path. In environments where different threads can * have different class loaders, for example app servers, the context class * loader will typically have been set to an appropriate loader for the * current thread. * * <p>In the unusual case where the context class loader is null, the class * loader that loaded this class ({@code Resources}) will be used instead. * * @throws IllegalArgumentException if the resource is not found */ public static URL getResource(String resourceName) { ClassLoader loader = Objects.firstNonNull( Thread.currentThread().getContextClassLoader(), Resources.class.getClassLoader()); URL url = loader.getResource(resourceName); checkArgument(url != null, "resource %s not found.", resourceName); return url; } /** * Given a {@code resourceName} that is relative to {@code contextClass}, * returns a {@code URL} pointing to the named resource. * * @throws IllegalArgumentException if the resource is not found */ public static URL getResource(Class<?> contextClass, String resourceName) { URL url = contextClass.getResource(resourceName); checkArgument(url != null, "resource %s relative to %s not found.", resourceName, contextClass.getName()); return url; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains utility methods and classes for working with Java I/O, * for example input streams, output streams, readers, writers, and files. * * <p>Many of the methods are based on the * {@link com.google.common.io.InputSupplier} and * {@link com.google.common.io.OutputSupplier} interfaces. They are used as * factories for I/O objects that might throw {@link java.io.IOException} when * being created. The advantage of using a factory is that the helper methods in * this package can take care of closing the resource properly, even if an * exception is thrown. The {@link com.google.common.io.ByteStreams}, * {@link com.google.common.io.CharStreams}, and * {@link com.google.common.io.Files} classes all have static helper methods to * create new factories and to work with them. * * <p>This package is a part of the open-source * <a href="http://guava-libraries.googlecode.com">Guava libraries</a>. * * @author Chris Nokleberg */ @ParametersAreNonnullByDefault package com.google.common.io; import javax.annotation.ParametersAreNonnullByDefault;
Java
/* * Copyright (C) 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.io; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Throwables; import java.io.Closeable; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayDeque; import java.util.Deque; import java.util.logging.Level; import javax.annotation.Nullable; /** * A {@link Closeable} that collects {@code Closeable} resources and closes them all when it is * {@linkplain #close closed}. This is intended to approximately emulate the behavior of Java 7's * <a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html"> * try-with-resources</a> statement in JDK6-compatible code. Running on Java 7, code using this * should be approximately equivalent in behavior to the same code written with try-with-resources. * Running on Java 6, exceptions that cannot be thrown must be logged rather than being added to the * thrown exception as a suppressed exception. * * <p>This class is intended to be used in the following pattern: * * <pre> {@code * Closer closer = Closer.create(); * try { * InputStream in = closer.register(openInputStream()); * OutputStream out = closer.register(openOutputStream()); * // do stuff * } catch (Throwable e) { * // ensure that any checked exception types other than IOException that could be thrown are * // provided here, e.g. throw closer.rethrow(e, CheckedException.class); * throw closer.rethrow(e); * } finally { * closer.close(); * }}</pre> * * <p>Note that this try-catch-finally block is not equivalent to a try-catch-finally block using * try-with-resources. To get the equivalent of that, you must wrap the above code in <i>another</i> * try block in order to catch any exception that may be thrown (including from the call to * {@code close()}). * * <p>This pattern ensures the following: * * <ul> * <li>Each {@code Closeable} resource that is successfully registered will be closed later.</li> * <li>If a {@code Throwable} is thrown in the try block, no exceptions that occur when attempting * to close resources will be thrown from the finally block. The throwable from the try block will * be thrown.</li> * <li>If no exceptions or errors were thrown in the try block, the <i>first</i> exception thrown * by an attempt to close a resource will be thrown.</li> * <li>Any exception caught when attempting to close a resource that is <i>not</i> thrown * (because another exception is already being thrown) is <i>suppressed</i>.</li> * </ul> * * <p>An exception that is suppressed is not thrown. The method of suppression used depends on the * version of Java the code is running on: * * <ul> * <li><b>Java 7+:</b> Exceptions are suppressed by adding them to the exception that <i>will</i> * be thrown using {@code Throwable.addSuppressed(Throwable)}.</li> * <li><b>Java 6:</b> Exceptions are suppressed by logging them instead.</li> * </ul> * * @author Colin Decker * @since 14.0 */ // Coffee's for {@link Closer closers} only. @Beta public final class Closer implements Closeable { /** * The suppressor implementation to use for the current Java version. */ private static final Suppressor SUPPRESSOR = SuppressingSuppressor.isAvailable() ? SuppressingSuppressor.INSTANCE : LoggingSuppressor.INSTANCE; /** * Creates a new {@link Closer}. */ public static Closer create() { return new Closer(SUPPRESSOR); } @VisibleForTesting final Suppressor suppressor; // only need space for 2 elements in most cases, so try to use the smallest array possible private final Deque<Closeable> stack = new ArrayDeque<Closeable>(4); private Throwable thrown; @VisibleForTesting Closer(Suppressor suppressor) { this.suppressor = checkNotNull(suppressor); // checkNotNull to satisfy null tests } /** * Registers the given {@code closeable} to be closed when this {@code Closer} is * {@linkplain #close closed}. * * @return the given {@code closeable} */ // close. this word no longer has any meaning to me. public <C extends Closeable> C register(@Nullable C closeable) { if (closeable != null) { stack.push(closeable); } return closeable; } /** * Stores the given throwable and rethrows it. It will be rethrown as is if it is an * {@code IOException}, {@code RuntimeException} or {@code Error}. Otherwise, it will be rethrown * wrapped in a {@code RuntimeException}. <b>Note:</b> Be sure to declare all of the checked * exception types your try block can throw when calling an overload of this method so as to avoid * losing the original exception type. * * <p>This method always throws, and as such should be called as * {@code throw closer.rethrow(e);} to ensure the compiler knows that it will throw. * * @return this method does not return; it always throws * @throws IOException when the given throwable is an IOException */ public RuntimeException rethrow(Throwable e) throws IOException { checkNotNull(e); thrown = e; Throwables.propagateIfPossible(e, IOException.class); throw new RuntimeException(e); } /** * Stores the given throwable and rethrows it. It will be rethrown as is if it is an * {@code IOException}, {@code RuntimeException}, {@code Error} or a checked exception of the * given type. Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b> * Be sure to declare all of the checked exception types your try block can throw when calling an * overload of this method so as to avoid losing the original exception type. * * <p>This method always throws, and as such should be called as * {@code throw closer.rethrow(e, ...);} to ensure the compiler knows that it will throw. * * @return this method does not return; it always throws * @throws IOException when the given throwable is an IOException * @throws X when the given throwable is of the declared type X */ public <X extends Exception> RuntimeException rethrow(Throwable e, Class<X> declaredType) throws IOException, X { checkNotNull(e); thrown = e; Throwables.propagateIfPossible(e, IOException.class); Throwables.propagateIfPossible(e, declaredType); throw new RuntimeException(e); } /** * Stores the given throwable and rethrows it. It will be rethrown as is if it is an * {@code IOException}, {@code RuntimeException}, {@code Error} or a checked exception of either * of the given types. Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. * <b>Note:</b> Be sure to declare all of the checked exception types your try block can throw * when calling an overload of this method so as to avoid losing the original exception type. * * <p>This method always throws, and as such should be called as * {@code throw closer.rethrow(e, ...);} to ensure the compiler knows that it will throw. * * @return this method does not return; it always throws * @throws IOException when the given throwable is an IOException * @throws X1 when the given throwable is of the declared type X1 * @throws X2 when the given throwable is of the declared type X2 */ public <X1 extends Exception, X2 extends Exception> RuntimeException rethrow( Throwable e, Class<X1> declaredType1, Class<X2> declaredType2) throws IOException, X1, X2 { checkNotNull(e); thrown = e; Throwables.propagateIfPossible(e, IOException.class); Throwables.propagateIfPossible(e, declaredType1, declaredType2); throw new RuntimeException(e); } /** * Closes all {@code Closeable} instances that have been added to this {@code Closer}. If an * exception was thrown in the try block and passed to one of the {@code exceptionThrown} methods, * any exceptions thrown when attempting to close a closeable will be suppressed. Otherwise, the * <i>first</i> exception to be thrown from an attempt to close a closeable will be thrown and any * additional exceptions that are thrown after that will be suppressed. */ @Override public void close() throws IOException { Throwable throwable = thrown; // close closeables in LIFO order while (!stack.isEmpty()) { Closeable closeable = stack.pop(); try { closeable.close(); } catch (Throwable e) { if (throwable == null) { throwable = e; } else { suppressor.suppress(closeable, throwable, e); } } } if (thrown == null && throwable != null) { Throwables.propagateIfPossible(throwable, IOException.class); throw new AssertionError(throwable); // not possible } } /** * Suppression strategy interface. */ @VisibleForTesting interface Suppressor { /** * Suppresses the given exception ({@code suppressed}) which was thrown when attempting to close * the given closeable. {@code thrown} is the exception that is actually being thrown from the * method. Implementations of this method should not throw under any circumstances. */ void suppress(Closeable closeable, Throwable thrown, Throwable suppressed); } /** * Suppresses exceptions by logging them. */ @VisibleForTesting static final class LoggingSuppressor implements Suppressor { static final LoggingSuppressor INSTANCE = new LoggingSuppressor(); @Override public void suppress(Closeable closeable, Throwable thrown, Throwable suppressed) { // log to the same place as Closeables Closeables.logger.log(Level.WARNING, "Suppressing exception thrown when closing " + closeable, suppressed); } } /** * Suppresses exceptions by adding them to the exception that will be thrown using JDK7's * addSuppressed(Throwable) mechanism. */ @VisibleForTesting static final class SuppressingSuppressor implements Suppressor { static final SuppressingSuppressor INSTANCE = new SuppressingSuppressor(); static boolean isAvailable() { return addSuppressed != null; } static final Method addSuppressed = getAddSuppressed(); private static Method getAddSuppressed() { try { return Throwable.class.getMethod("addSuppressed", Throwable.class); } catch (Throwable e) { return null; } } @Override public void suppress(Closeable closeable, Throwable thrown, Throwable suppressed) { // ensure no exceptions from addSuppressed if (thrown == suppressed) { return; } try { addSuppressed.invoke(thrown, suppressed); } catch (Throwable e) { // if, somehow, IllegalAccessException or another exception is thrown, fall back to logging LoggingSuppressor.INSTANCE.suppress(closeable, thrown, suppressed); } } } }
Java
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import static com.google.common.base.Preconditions.checkNotNull; import java.io.Closeable; import java.io.Flushable; import java.io.IOException; import java.io.Writer; import javax.annotation.Nullable; /** * Writer that places all output on an {@link Appendable} target. If the target * is {@link Flushable} or {@link Closeable}, flush()es and close()s will also * be delegated to the target. * * @author Alan Green * @author Sebastian Kanthak * @since 1.0 */ class AppendableWriter extends Writer { private final Appendable target; private boolean closed; /** * Creates a new writer that appends everything it writes to {@code target}. * * @param target target to which to append output */ AppendableWriter(Appendable target) { this.target = checkNotNull(target); } /* * Abstract methods from Writer */ @Override public void write(char cbuf[], int off, int len) throws IOException { checkNotClosed(); // It turns out that creating a new String is usually as fast, or faster // than wrapping cbuf in a light-weight CharSequence. target.append(new String(cbuf, off, len)); } @Override public void flush() throws IOException { checkNotClosed(); if (target instanceof Flushable) { ((Flushable) target).flush(); } } @Override public void close() throws IOException { this.closed = true; if (target instanceof Closeable) { ((Closeable) target).close(); } } /* * Override a few functions for performance reasons to avoid creating * unnecessary strings. */ @Override public void write(int c) throws IOException { checkNotClosed(); target.append((char) c); } @Override public void write(@Nullable String str) throws IOException { checkNotClosed(); target.append(str); } @Override public void write(@Nullable String str, int off, int len) throws IOException { checkNotClosed(); // tricky: append takes start, end pair... target.append(str, off, off + len); } @Override public Writer append(char c) throws IOException { checkNotClosed(); target.append(c); return this; } @Override public Writer append(@Nullable CharSequence charSeq) throws IOException { checkNotClosed(); target.append(charSeq); return this; } @Override public Writer append(@Nullable CharSequence charSeq, int start, int end) throws IOException { checkNotClosed(); target.append(charSeq, start, end); return this; } private void checkNotClosed() throws IOException { if (closed) { throw new IOException("Cannot write to a closed writer."); } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import com.google.common.annotations.Beta; import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.annotation.Nullable; /** * An OutputStream that counts the number of bytes written. * * @author Chris Nokleberg * @since 1.0 */ @Beta public final class CountingOutputStream extends FilterOutputStream { private long count; /** * Wraps another output stream, counting the number of bytes written. * * @param out the output stream to be wrapped */ public CountingOutputStream(@Nullable OutputStream out) { super(out); } /** Returns the number of bytes written. */ public long getCount() { return count; } @Override public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); count += len; } @Override public void write(int b) throws IOException { out.write(b); count++; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import java.io.IOException; /** * Package-protected abstract class that implements the line reading * algorithm used by {@link LineReader}. Line separators are per {@link * java.io.BufferedReader}: line feed, carriage return, or carriage * return followed immediately by a linefeed. * * <p>Subclasses must implement {@link #handleLine}, call {@link #add} * to pass character data, and call {@link #finish} at the end of stream. * * @author Chris Nokleberg * @since 1.0 */ abstract class LineBuffer { /** Holds partial line contents. */ private StringBuilder line = new StringBuilder(); /** Whether a line ending with a CR is pending processing. */ private boolean sawReturn; /** * Process additional characters from the stream. When a line separator * is found the contents of the line and the line separator itself * are passed to the abstract {@link #handleLine} method. * * @param cbuf the character buffer to process * @param off the offset into the buffer * @param len the number of characters to process * @throws IOException if an I/O error occurs * @see #finish */ protected void add(char[] cbuf, int off, int len) throws IOException { int pos = off; if (sawReturn && len > 0) { // Last call to add ended with a CR; we can handle the line now. if (finishLine(cbuf[pos] == '\n')) { pos++; } } int start = pos; for (int end = off + len; pos < end; pos++) { switch (cbuf[pos]) { case '\r': line.append(cbuf, start, pos - start); sawReturn = true; if (pos + 1 < end) { if (finishLine(cbuf[pos + 1] == '\n')) { pos++; } } start = pos + 1; break; case '\n': line.append(cbuf, start, pos - start); finishLine(true); start = pos + 1; break; default: // do nothing } } line.append(cbuf, start, off + len - start); } /** Called when a line is complete. */ private boolean finishLine(boolean sawNewline) throws IOException { handleLine(line.toString(), sawReturn ? (sawNewline ? "\r\n" : "\r") : (sawNewline ? "\n" : "")); line = new StringBuilder(); sawReturn = false; return sawNewline; } /** * Subclasses must call this method after finishing character processing, * in order to ensure that any unterminated line in the buffer is * passed to {@link #handleLine}. * * @throws IOException if an I/O error occurs */ protected void finish() throws IOException { if (sawReturn || line.length() > 0) { finishLine(false); } } /** * Called for each line found in the character data passed to * {@link #add}. * * @param line a line of text (possibly empty), without any line separators * @param end the line separator; one of {@code "\r"}, {@code "\n"}, * {@code "\r\n"}, or {@code ""} * @throws IOException if an I/O error occurs */ protected abstract void handleLine(String line, String end) throws IOException; }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import com.google.common.annotations.Beta; import java.io.IOException; /** * A callback interface to process bytes from a stream. * * <p>{@link #processBytes} will be called for each line that is read, and * should return {@code false} when you want to stop processing. * * @author Chris Nokleberg * @since 1.0 */ @Beta public interface ByteProcessor<T> { /** * This method will be called for each chunk of bytes in an * input stream. The implementation should process the bytes * from {@code buf[off]} through {@code buf[off + len - 1]} * (inclusive). * * @param buf the byte array containing the data to process * @param off the initial offset into the array * @param len the length of data to be processed * @return true to continue processing, false to stop */ boolean processBytes(byte[] buf, int off, int len) throws IOException; /** Return the result of processing all the bytes. */ T getResult(); }
Java
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import java.io.IOException; import java.io.Reader; import java.nio.CharBuffer; /** * A {@link Reader} that reads the characters in a {@link CharSequence}. Like {@code StringReader}, * but works with any {@link CharSequence}. * * @author Colin Decker */ // TODO(user): make this public? as a type, or a method in CharStreams? final class CharSequenceReader extends Reader { private CharSequence seq; private int pos; private int mark; /** * Creates a new reader wrapping the given character sequence. */ public CharSequenceReader(CharSequence seq) { this.seq = checkNotNull(seq); } private void checkOpen() throws IOException { if (seq == null) { throw new IOException("reader closed"); } } private boolean hasRemaining() { return remaining() > 0; } private int remaining() { return seq.length() - pos; } @Override public synchronized int read(CharBuffer target) throws IOException { checkNotNull(target); checkOpen(); if (!hasRemaining()) { return -1; } int charsToRead = Math.min(target.remaining(), remaining()); for (int i = 0; i < charsToRead; i++) { target.put(seq.charAt(pos++)); } return charsToRead; } @Override public synchronized int read() throws IOException { checkOpen(); return hasRemaining() ? seq.charAt(pos++) : -1; } @Override public synchronized int read(char[] cbuf, int off, int len) throws IOException { checkPositionIndexes(off, off + len, cbuf.length); checkOpen(); if (!hasRemaining()) { return -1; } int charsToRead = Math.min(len, remaining()); for (int i = 0; i < charsToRead; i++) { cbuf[off + i] = seq.charAt(pos++); } return charsToRead; } @Override public synchronized long skip(long n) throws IOException { checkArgument(n >= 0, "n (%s) may not be negative", n); checkOpen(); int charsToSkip = (int) Math.min(remaining(), n); // safe because remaining is an int pos += charsToSkip; return charsToSkip; } @Override public synchronized boolean ready() throws IOException { checkOpen(); return true; } @Override public boolean markSupported() { return true; } @Override public synchronized void mark(int readAheadLimit) throws IOException { checkArgument(readAheadLimit >= 0, "readAheadLimit (%s) may not be negative", readAheadLimit); checkOpen(); mark = pos; } @Override public synchronized void reset() throws IOException { checkOpen(); pos = mark; } @Override public synchronized void close() throws IOException { seq = null; } }
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.io; 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.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; /** * Provides simple GWT-compatible substitutes for {@code InputStream}, {@code OutputStream}, * {@code Reader}, and {@code Writer} so that {@code BaseEncoding} can use streaming implementations * while remaining GWT-compatible. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) final class GwtWorkarounds { private GwtWorkarounds() {} /** * A GWT-compatible substitute for a {@code Reader}. */ interface CharInput { int read() throws IOException; void close() throws IOException; } /** * Views a {@code Reader} as a {@code CharInput}. */ @GwtIncompatible("Reader") static CharInput asCharInput(final Reader reader) { checkNotNull(reader); return new CharInput() { @Override public int read() throws IOException { return reader.read(); } @Override public void close() throws IOException { reader.close(); } }; } /** * Views a {@code CharSequence} as a {@code CharInput}. */ static CharInput asCharInput(final CharSequence chars) { checkNotNull(chars); return new CharInput() { int index = 0; @Override public int read() { if (index < chars.length()) { return chars.charAt(index++); } else { return -1; } } @Override public void close() { index = chars.length(); } }; } /** * A GWT-compatible substitute for an {@code InputStream}. */ interface ByteInput { int read() throws IOException; void close() throws IOException; } /** * Views a {@code ByteInput} as an {@code InputStream}. */ @GwtIncompatible("InputStream") static InputStream asInputStream(final ByteInput input) { checkNotNull(input); return new InputStream() { @Override public int read() throws IOException { return input.read(); } @Override public int read(byte[] b, int off, int len) throws IOException { checkNotNull(b); checkPositionIndexes(off, off + len, b.length); if (len == 0) { return 0; } int firstByte = read(); if (firstByte == -1) { return -1; } b[off] = (byte) firstByte; for (int dst = 1; dst < len; dst++) { int readByte = read(); if (readByte == -1) { return dst; } b[off + dst] = (byte) readByte; } return len; } @Override public void close() throws IOException { input.close(); } }; } /** * A GWT-compatible substitute for an {@code OutputStream}. */ interface ByteOutput { void write(byte b) throws IOException; void flush() throws IOException; void close() throws IOException; } /** * Views a {@code ByteOutput} as an {@code OutputStream}. */ @GwtIncompatible("OutputStream") static OutputStream asOutputStream(final ByteOutput output) { checkNotNull(output); return new OutputStream() { @Override public void write(int b) throws IOException { output.write((byte) b); } @Override public void flush() throws IOException { output.flush(); } @Override public void close() throws IOException { output.close(); } }; } /** * A GWT-compatible substitute for a {@code Writer}. */ interface CharOutput { void write(char c) throws IOException; void flush() throws IOException; void close() throws IOException; } /** * Views a {@code Writer} as a {@code CharOutput}. */ @GwtIncompatible("Writer") static CharOutput asCharOutput(final Writer writer) { checkNotNull(writer); return new CharOutput() { @Override public void write(char c) throws IOException { writer.append(c); } @Override public void flush() throws IOException { writer.flush(); } @Override public void close() throws IOException { writer.close(); } }; } /** * Returns a {@code CharOutput} whose {@code toString()} method can be used * to get the combined output. */ static CharOutput stringBuilderOutput(int initialSize) { final StringBuilder builder = new StringBuilder(initialSize); return new CharOutput() { @Override public void write(char c) { builder.append(c); } @Override public void flush() {} @Override public void close() {} @Override public String toString() { return builder.toString(); } }; } }
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.io; /** * Modes for opening a file for writing. The default when mode when none is specified is to * truncate the file before writing. * * @author Colin Decker */ public enum FileWriteMode { /** Specifies that writes to the opened file should append to the end of the file. */ APPEND }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * An {@link OutputStream} that starts buffering to a byte array, but * switches to file buffering once the data reaches a configurable size. * * <p>This class is thread-safe. * * @author Chris Nokleberg * @since 1.0 */ @Beta public final class FileBackedOutputStream extends OutputStream { private final int fileThreshold; private final boolean resetOnFinalize; private final ByteSource source; private OutputStream out; private MemoryOutput memory; private File file; /** ByteArrayOutputStream that exposes its internals. */ private static class MemoryOutput extends ByteArrayOutputStream { byte[] getBuffer() { return buf; } int getCount() { return count; } } /** Returns the file holding the data (possibly null). */ @VisibleForTesting synchronized File getFile() { return file; } /** * Creates a new instance that uses the given file threshold, and does * not reset the data when the {@link ByteSource} returned by * {@link #asByteSource} is finalized. * * @param fileThreshold the number of bytes before the stream should * switch to buffering to a file */ public FileBackedOutputStream(int fileThreshold) { this(fileThreshold, false); } /** * Creates a new instance that uses the given file threshold, and * optionally resets the data when the {@link ByteSource} returned * by {@link #asByteSource} is finalized. * * @param fileThreshold the number of bytes before the stream should * switch to buffering to a file * @param resetOnFinalize if true, the {@link #reset} method will * be called when the {@link ByteSource} returned by {@link * #asByteSource} is finalized */ public FileBackedOutputStream(int fileThreshold, boolean resetOnFinalize) { this.fileThreshold = fileThreshold; this.resetOnFinalize = resetOnFinalize; memory = new MemoryOutput(); out = memory; if (resetOnFinalize) { source = new ByteSource() { @Override public InputStream openStream() throws IOException { return openInputStream(); } @Override protected void finalize() { try { reset(); } catch (Throwable t) { t.printStackTrace(System.err); } } }; } else { source = new ByteSource() { @Override public InputStream openStream() throws IOException { return openInputStream(); } }; } } /** * Returns a supplier that may be used to retrieve the data buffered * by this stream. This method returns the same object as * {@link #asByteSource()}. * * @deprecated Use {@link #asByteSource()} instead. This method is scheduled * to be removed in Guava 16.0. */ @Deprecated public InputSupplier<InputStream> getSupplier() { return asByteSource(); } /** * Returns a readable {@link ByteSource} view of the data that has been * written to this stream. * * @since 15.0 */ public ByteSource asByteSource() { return source; } private synchronized InputStream openInputStream() throws IOException { if (file != null) { return new FileInputStream(file); } else { return new ByteArrayInputStream( memory.getBuffer(), 0, memory.getCount()); } } /** * Calls {@link #close} if not already closed, and then resets this * object back to its initial state, for reuse. If data was buffered * to a file, it will be deleted. * * @throws IOException if an I/O error occurred while deleting the file buffer */ public synchronized void reset() throws IOException { try { close(); } finally { if (memory == null) { memory = new MemoryOutput(); } else { memory.reset(); } out = memory; if (file != null) { File deleteMe = file; file = null; if (!deleteMe.delete()) { throw new IOException("Could not delete: " + deleteMe); } } } } @Override public synchronized void write(int b) throws IOException { update(1); out.write(b); } @Override public synchronized void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public synchronized void write(byte[] b, int off, int len) throws IOException { update(len); out.write(b, off, len); } @Override public synchronized void close() throws IOException { out.close(); } @Override public synchronized void flush() throws IOException { out.flush(); } /** * Checks if writing {@code len} bytes would go over threshold, and * switches to file buffering if so. */ private void update(int len) throws IOException { if (file == null && (memory.getCount() + len > fileThreshold)) { File temp = File.createTempFile("FileBackedOutputStream", null); if (resetOnFinalize) { // Finalizers are not guaranteed to be called on system shutdown; // this is insurance. temp.deleteOnExit(); } FileOutputStream transfer = new FileOutputStream(temp); transfer.write(memory.getBuffer(), 0, memory.getCount()); transfer.flush(); // We've successfully transferred the data; switch to writing to file out = transfer; file = temp; memory = null; } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import java.io.IOException; /** * A factory for writable streams of bytes or characters. * * @author Chris Nokleberg * @since 1.0 */ public interface OutputSupplier<T> { /** * Returns an object that encapsulates a writable resource. * <p> * Like {@link Iterable#iterator}, this method may be called repeatedly to * get independent channels to the same underlying resource. * <p> * Where the channel maintains a position within the resource, moving that * cursor within one channel should not affect the starting position of * channels returned by other calls. */ T getOutput() throws IOException; }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import com.google.common.base.Preconditions; import java.io.IOException; import java.io.Reader; import java.util.Iterator; import javax.annotation.Nullable; /** * A {@link Reader} that concatenates multiple readers. * * @author Bin Zhu * @since 1.0 */ class MultiReader extends Reader { private final Iterator<? extends CharSource> it; private Reader current; MultiReader(Iterator<? extends CharSource> readers) throws IOException { this.it = readers; advance(); } /** * Closes the current reader and opens the next one, if any. */ private void advance() throws IOException { close(); if (it.hasNext()) { current = it.next().openStream(); } } @Override public int read(@Nullable char cbuf[], int off, int len) throws IOException { if (current == null) { return -1; } int result = current.read(cbuf, off, len); if (result == -1) { advance(); return read(cbuf, off, len); } return result; } @Override public long skip(long n) throws IOException { Preconditions.checkArgument(n >= 0, "n is negative"); if (n > 0) { while (current != null) { long result = current.skip(n); if (result > 0) { return result; } advance(); } } return 0; } @Override public boolean ready() throws IOException { return (current != null) && current.ready(); } @Override public void close() throws IOException { if (current != null) { try { current.close(); } finally { current = null; } } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import com.google.common.annotations.Beta; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import javax.annotation.Nullable; /** * An {@link InputStream} that counts the number of bytes read. * * @author Chris Nokleberg * @since 1.0 */ @Beta public final class CountingInputStream extends FilterInputStream { private long count; private long mark = -1; /** * Wraps another input stream, counting the number of bytes read. * * @param in the input stream to be wrapped */ public CountingInputStream(@Nullable InputStream in) { super(in); } /** Returns the number of bytes read. */ public long getCount() { return count; } @Override public int read() throws IOException { int result = in.read(); if (result != -1) { count++; } return result; } @Override public int read(byte[] b, int off, int len) throws IOException { int result = in.read(b, off, len); if (result != -1) { count += result; } return result; } @Override public long skip(long n) throws IOException { long result = in.skip(n); count += result; return result; } @Override public synchronized void mark(int readlimit) { in.mark(readlimit); mark = count; // it's okay to mark even if mark isn't supported, as reset won't work } @Override public synchronized void reset() throws IOException { if (!in.markSupported()) { throw new IOException("Mark not supported"); } if (mark == -1) { throw new IOException("Mark not set"); } in.reset(); count = mark; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import java.io.DataInput; import java.io.DataInputStream; import java.io.EOFException; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * An implementation of {@link DataInput} that uses little-endian byte ordering * for reading {@code short}, {@code int}, {@code float}, {@code double}, and * {@code long} values. * <p> * <b>Note:</b> This class intentionally violates the specification of its * supertype {@code DataInput}, which explicitly requires big-endian byte order. * * @author Chris Nokleberg * @author Keith Bottner * @since 8.0 */ @Beta public final class LittleEndianDataInputStream extends FilterInputStream implements DataInput { /** * Creates a {@code LittleEndianDataInputStream} that wraps the given stream. * * @param in the stream to delegate to */ public LittleEndianDataInputStream(InputStream in) { super(Preconditions.checkNotNull(in)); } /** * This method will throw an {@link UnsupportedOperationException}. */ @Override public String readLine() { throw new UnsupportedOperationException("readLine is not supported"); } @Override public void readFully(byte[] b) throws IOException { ByteStreams.readFully(this, b); } @Override public void readFully(byte[] b, int off, int len) throws IOException { ByteStreams.readFully(this, b, off, len); } @Override public int skipBytes(int n) throws IOException { return (int) in.skip(n); } @Override public int readUnsignedByte() throws IOException { int b1 = in.read(); if (0 > b1) { throw new EOFException(); } return b1; } /** * Reads an unsigned {@code short} as specified by * {@link DataInputStream#readUnsignedShort()}, except using little-endian * byte order. * * @return the next two bytes of the input stream, interpreted as an * unsigned 16-bit integer in little-endian byte order * @throws IOException if an I/O error occurs */ @Override public int readUnsignedShort() throws IOException { byte b1 = readAndCheckByte(); byte b2 = readAndCheckByte(); return Ints.fromBytes((byte) 0, (byte) 0, b2, b1); } /** * Reads an integer as specified by {@link DataInputStream#readInt()}, except * using little-endian byte order. * * @return the next four bytes of the input stream, interpreted as an * {@code int} in little-endian byte order * @throws IOException if an I/O error occurs */ @Override public int readInt() throws IOException { byte b1 = readAndCheckByte(); byte b2 = readAndCheckByte(); byte b3 = readAndCheckByte(); byte b4 = readAndCheckByte(); return Ints.fromBytes( b4, b3, b2, b1); } /** * Reads a {@code long} as specified by {@link DataInputStream#readLong()}, * except using little-endian byte order. * * @return the next eight bytes of the input stream, interpreted as a * {@code long} in little-endian byte order * @throws IOException if an I/O error occurs */ @Override public long readLong() throws IOException { byte b1 = readAndCheckByte(); byte b2 = readAndCheckByte(); byte b3 = readAndCheckByte(); byte b4 = readAndCheckByte(); byte b5 = readAndCheckByte(); byte b6 = readAndCheckByte(); byte b7 = readAndCheckByte(); byte b8 = readAndCheckByte(); return Longs.fromBytes(b8, b7, b6, b5, b4, b3, b2, b1); } /** * Reads a {@code float} as specified by {@link DataInputStream#readFloat()}, * except using little-endian byte order. * * @return the next four bytes of the input stream, interpreted as a * {@code float} in little-endian byte order * @throws IOException if an I/O error occurs */ @Override public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } /** * Reads a {@code double} as specified by * {@link DataInputStream#readDouble()}, except using little-endian byte * order. * * @return the next eight bytes of the input stream, interpreted as a * {@code double} in little-endian byte order * @throws IOException if an I/O error occurs */ @Override public double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } @Override public String readUTF() throws IOException { return new DataInputStream(in).readUTF(); } /** * Reads a {@code short} as specified by {@link DataInputStream#readShort()}, * except using little-endian byte order. * * @return the next two bytes of the input stream, interpreted as a * {@code short} in little-endian byte order. * @throws IOException if an I/O error occurs. */ @Override public short readShort() throws IOException { return (short) readUnsignedShort(); } /** * Reads a char as specified by {@link DataInputStream#readChar()}, except * using little-endian byte order. * * @return the next two bytes of the input stream, interpreted as a * {@code char} in little-endian byte order * @throws IOException if an I/O error occurs */ @Override public char readChar() throws IOException { return (char) readUnsignedShort(); } @Override public byte readByte() throws IOException { return (byte) readUnsignedByte(); } @Override public boolean readBoolean() throws IOException { return readUnsignedByte() != 0; } /** * Reads a byte from the input stream checking that the end of file (EOF) * has not been encountered. * * @return byte read from input * @throws IOException if an error is encountered while reading * @throws EOFException if the end of file (EOF) is encountered. */ private byte readAndCheckByte() throws IOException, EOFException { int b1 = in.read(); if (-1 == b1) { throw new EOFException(); } return (byte) b1; } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import java.io.DataOutput; import java.io.IOException; /** * An extension of {@code DataOutput} for writing to in-memory byte arrays; its * methods offer identical functionality but do not throw {@link IOException}. * * @author Jayaprabhakar Kadarkarai * @since 1.0 */ public interface ByteArrayDataOutput extends DataOutput { @Override void write(int b); @Override void write(byte b[]); @Override void write(byte b[], int off, int len); @Override void writeBoolean(boolean v); @Override void writeByte(int v); @Override void writeShort(int v); @Override void writeChar(int v); @Override void writeInt(int v); @Override void writeLong(long v); @Override void writeFloat(float v); @Override void writeDouble(double v); @Override void writeChars(String s); @Override void writeUTF(String s); /** * @deprecated This method is dangerous as it discards the high byte of * every character. For UTF-8, use {@code write(s.getBytes(Charsets.UTF_8))}. */ @Deprecated @Override void writeBytes(String s); /** * Returns the contents that have been written to this instance, * as a byte array. */ byte[] toByteArray(); }
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.io; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableList; import com.google.common.hash.Funnels; import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; import com.google.common.hash.Hasher; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Iterator; /** * A readable source of bytes, such as a file. Unlike an {@link InputStream}, a * {@code ByteSource} is not an open, stateful stream for input that can be read and closed. * Instead, it is an immutable <i>supplier</i> of {@code InputStream} instances. * * <p>{@code ByteSource} provides two kinds of methods: * <ul> * <li><b>Methods that return a stream:</b> These methods should return a <i>new</i>, independent * instance each time they are called. The caller is responsible for ensuring that the returned * stream is closed. * <li><b>Convenience methods:</b> These are implementations of common operations that are * typically implemented by opening a stream using one of the methods in the first category, doing * something and finally closing the stream that was opened. * </ul> * * @since 14.0 * @author Colin Decker */ public abstract class ByteSource implements InputSupplier<InputStream> { private static final int BUF_SIZE = 0x1000; // 4K /** * Returns a {@link CharSource} view of this byte source that decodes bytes read from this source * as characters using the given {@link Charset}. */ public CharSource asCharSource(Charset charset) { return new AsCharSource(charset); } /** * Opens a new {@link InputStream} for reading from this source. This method should return a new, * independent stream each time it is called. * * <p>The caller is responsible for ensuring that the returned stream is closed. * * @throws IOException if an I/O error occurs in the process of opening the stream */ public abstract InputStream openStream() throws IOException; /** * This method is a temporary method provided for easing migration from suppliers to sources and * sinks. * * @since 15.0 * @deprecated This method is only provided for temporary compatibility with the * {@link InputSupplier} interface and should not be called directly. Use {@link #openStream} * instead. */ @Override @Deprecated public final InputStream getInput() throws IOException { return openStream(); } /** * Opens a new buffered {@link InputStream} for reading from this source. The returned stream is * not required to be a {@link BufferedInputStream} in order to allow implementations to simply * delegate to {@link #openStream()} when the stream returned by that method does not benefit * from additional buffering (for example, a {@code ByteArrayInputStream}). This method should * return a new, independent stream each time it is called. * * <p>The caller is responsible for ensuring that the returned stream is closed. * * @throws IOException if an I/O error occurs in the process of opening the stream * @since 15.0 (in 14.0 with return type {@link BufferedInputStream}) */ public InputStream openBufferedStream() throws IOException { InputStream in = openStream(); return (in instanceof BufferedInputStream) ? (BufferedInputStream) in : new BufferedInputStream(in); } /** * Returns a view of a slice of this byte source that is at most {@code length} bytes long * starting at the given {@code offset}. * * @throws IllegalArgumentException if {@code offset} or {@code length} is negative */ public ByteSource slice(long offset, long length) { return new SlicedByteSource(offset, length); } /** * Returns whether the source has zero bytes. The default implementation is to open a stream and * check for EOF. * * @throws IOException if an I/O error occurs * @since 15.0 */ public boolean isEmpty() throws IOException { Closer closer = Closer.create(); try { InputStream in = closer.register(openStream()); return in.read() == -1; } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Returns the size of this source in bytes. For most implementations, this is a heavyweight * operation that will open a stream, read (or {@link InputStream#skip(long) skip}, if possible) * to the end of the stream and return the total number of bytes that were read. * * <p>For some sources, such as a file, this method may use a more efficient implementation. Note * that in such cases, it is <i>possible</i> that this method will return a different number of * bytes than would be returned by reading all of the bytes (for example, some special files may * return a size of 0 despite actually having content when read). * * <p>In either case, if this is a mutable source such as a file, the size it returns may not be * the same number of bytes a subsequent read would return. * * @throws IOException if an I/O error occurs in the process of reading the size of this source */ public long size() throws IOException { Closer closer = Closer.create(); try { InputStream in = closer.register(openStream()); return countBySkipping(in); } catch (IOException e) { // skip may not be supported... at any rate, try reading } finally { closer.close(); } closer = Closer.create(); try { InputStream in = closer.register(openStream()); return countByReading(in); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Counts the bytes in the given input stream using skip if possible. Returns SKIP_FAILED if the * first call to skip threw, in which case skip may just not be supported. */ private long countBySkipping(InputStream in) throws IOException { long count = 0; while (true) { // don't try to skip more than available() // things may work really wrong with FileInputStream otherwise long skipped = in.skip(Math.min(in.available(), Integer.MAX_VALUE)); if (skipped <= 0) { if (in.read() == -1) { return count; } else if (count == 0 && in.available() == 0) { // if available is still zero after reading a single byte, it // will probably always be zero, so we should countByReading throw new IOException(); } count++; } else { count += skipped; } } } private static final byte[] countBuffer = new byte[BUF_SIZE]; private long countByReading(InputStream in) throws IOException { long count = 0; long read; while ((read = in.read(countBuffer)) != -1) { count += read; } return count; } /** * Copies the contents of this byte source to the given {@code OutputStream}. Does not close * {@code output}. * * @throws IOException if an I/O error occurs in the process of reading from this source or * writing to {@code output} */ public long copyTo(OutputStream output) throws IOException { checkNotNull(output); Closer closer = Closer.create(); try { InputStream in = closer.register(openStream()); return ByteStreams.copy(in, output); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Copies the contents of this byte source to the given {@code ByteSink}. * * @throws IOException if an I/O error occurs in the process of reading from this source or * writing to {@code sink} */ public long copyTo(ByteSink sink) throws IOException { checkNotNull(sink); Closer closer = Closer.create(); try { InputStream in = closer.register(openStream()); OutputStream out = closer.register(sink.openStream()); return ByteStreams.copy(in, out); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Reads the full contents of this byte source as a byte array. * * @throws IOException if an I/O error occurs in the process of reading from this source */ public byte[] read() throws IOException { Closer closer = Closer.create(); try { InputStream in = closer.register(openStream()); return ByteStreams.toByteArray(in); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Hashes the contents of this byte source using the given hash function. * * @throws IOException if an I/O error occurs in the process of reading from this source */ public HashCode hash(HashFunction hashFunction) throws IOException { Hasher hasher = hashFunction.newHasher(); copyTo(Funnels.asOutputStream(hasher)); return hasher.hash(); } /** * Checks that the contents of this byte source are equal to the contents of the given byte * source. * * @throws IOException if an I/O error occurs in the process of reading from this source or * {@code other} */ public boolean contentEquals(ByteSource other) throws IOException { checkNotNull(other); byte[] buf1 = new byte[BUF_SIZE]; byte[] buf2 = new byte[BUF_SIZE]; Closer closer = Closer.create(); try { InputStream in1 = closer.register(openStream()); InputStream in2 = closer.register(other.openStream()); while (true) { int read1 = ByteStreams.read(in1, buf1, 0, BUF_SIZE); int read2 = ByteStreams.read(in2, buf2, 0, BUF_SIZE); if (read1 != read2 || !Arrays.equals(buf1, buf2)) { return false; } else if (read1 != BUF_SIZE) { return true; } } } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Concatenates multiple {@link ByteSource} instances into a single source. * Streams returned from the source will contain the concatenated data from * the streams of the underlying sources. * * <p>Only one underlying stream will be open at a time. Closing the * concatenated stream will close the open underlying stream. * * @param sources the sources to concatenate * @return a {@code ByteSource} containing the concatenated data * @throws NullPointerException if any of {@code sources} is {@code null} * @since 15.0 */ public static ByteSource concat(Iterable<? extends ByteSource> sources) { return new ConcatenatedByteSource(sources); } /** * Concatenates multiple {@link ByteSource} instances into a single source. * Streams returned from the source will contain the concatenated data from * the streams of the underlying sources. * * <p>Only one underlying stream will be open at a time. Closing the * concatenated stream will close the open underlying stream. * * @param sources the sources to concatenate * @return a {@code ByteSource} containing the concatenated data * @throws NullPointerException if any of {@code sources} is {@code null} * @since 15.0 */ public static ByteSource concat(Iterator<? extends ByteSource> sources) { return concat(ImmutableList.copyOf(sources)); } /** * Concatenates multiple {@link ByteSource} instances into a single source. * Streams returned from the source will contain the concatenated data from * the streams of the underlying sources. * * <p>Only one underlying stream will be open at a time. Closing the * concatenated stream will close the open underlying stream. * * @param sources the sources to concatenate * @return a {@code ByteSource} containing the concatenated data * @throws NullPointerException if any of {@code sources} is {@code null} * @since 15.0 */ public static ByteSource concat(ByteSource... sources) { return concat(ImmutableList.copyOf(sources)); } /** * Returns a view of the given byte array as a {@link ByteSource}. To view only a specific range * in the array, use {@code ByteSource.wrap(b).slice(offset, length)}. * * @since 15.0 (since 14.0 as {@code ByteStreams.asByteSource(byte[])}). */ public static ByteSource wrap(byte[] b) { return new ByteArrayByteSource(b); } /** * Returns an immutable {@link ByteSource} that contains no bytes. * * @since 15.0 */ public static ByteSource empty() { return EmptyByteSource.INSTANCE; } /** * A char source that reads bytes from this source and decodes them as characters using a * charset. */ private final class AsCharSource extends CharSource { private final Charset charset; private AsCharSource(Charset charset) { this.charset = checkNotNull(charset); } @Override public Reader openStream() throws IOException { return new InputStreamReader(ByteSource.this.openStream(), charset); } @Override public String toString() { return ByteSource.this.toString() + ".asCharSource(" + charset + ")"; } } /** * A view of a subsection of the containing byte source. */ private final class SlicedByteSource extends ByteSource { private final long offset; private final long length; private SlicedByteSource(long offset, long length) { checkArgument(offset >= 0, "offset (%s) may not be negative", offset); checkArgument(length >= 0, "length (%s) may not be negative", length); this.offset = offset; this.length = length; } @Override public InputStream openStream() throws IOException { return sliceStream(ByteSource.this.openStream()); } @Override public InputStream openBufferedStream() throws IOException { return sliceStream(ByteSource.this.openBufferedStream()); } private InputStream sliceStream(InputStream in) throws IOException { if (offset > 0) { try { ByteStreams.skipFully(in, offset); } catch (Throwable e) { Closer closer = Closer.create(); closer.register(in); try { throw closer.rethrow(e); } finally { closer.close(); } } } return ByteStreams.limit(in, length); } @Override public ByteSource slice(long offset, long length) { checkArgument(offset >= 0, "offset (%s) may not be negative", offset); checkArgument(length >= 0, "length (%s) may not be negative", length); long maxLength = this.length - offset; return ByteSource.this.slice(this.offset + offset, Math.min(length, maxLength)); } @Override public boolean isEmpty() throws IOException { return length == 0 || super.isEmpty(); } @Override public String toString() { return ByteSource.this.toString() + ".slice(" + offset + ", " + length + ")"; } } private static class ByteArrayByteSource extends ByteSource { protected final byte[] bytes; protected ByteArrayByteSource(byte[] bytes) { this.bytes = checkNotNull(bytes); } @Override public InputStream openStream() { return new ByteArrayInputStream(bytes); } @Override public InputStream openBufferedStream() throws IOException { return openStream(); } @Override public boolean isEmpty() { return bytes.length == 0; } @Override public long size() { return bytes.length; } @Override public byte[] read() { return bytes.clone(); } @Override public long copyTo(OutputStream output) throws IOException { output.write(bytes); return bytes.length; } @Override public HashCode hash(HashFunction hashFunction) throws IOException { return hashFunction.hashBytes(bytes); } // TODO(user): Possibly override slice() @Override public String toString() { return "ByteSource.wrap(" + BaseEncoding.base16().encode(bytes) + ")"; } } private static final class EmptyByteSource extends ByteArrayByteSource { private static final EmptyByteSource INSTANCE = new EmptyByteSource(); private EmptyByteSource() { super(new byte[0]); } @Override public CharSource asCharSource(Charset charset) { checkNotNull(charset); return CharSource.empty(); } @Override public byte[] read() { return bytes; // length is 0, no need to clone } @Override public String toString() { return "ByteSource.empty()"; } } private static final class ConcatenatedByteSource extends ByteSource { private final ImmutableList<ByteSource> sources; ConcatenatedByteSource(Iterable<? extends ByteSource> sources) { this.sources = ImmutableList.copyOf(sources); } @Override public InputStream openStream() throws IOException { return new MultiInputStream(sources.iterator()); } @Override public boolean isEmpty() throws IOException { for (ByteSource source : sources) { if (!source.isEmpty()) { return false; } } return true; } @Override public long size() throws IOException { long result = 0L; for (ByteSource source : sources) { result += source.size(); } return result; } @Override public String toString() { return "ByteSource.concat(" + sources + ")"; } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import com.google.common.annotations.Beta; import java.io.Flushable; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Utility methods for working with {@link Flushable} objects. * * @author Michael Lancaster * @since 1.0 */ @Beta public final class Flushables { private static final Logger logger = Logger.getLogger(Flushables.class.getName()); private Flushables() {} /** * Flush a {@link Flushable}, with control over whether an * {@code IOException} may be thrown. * * <p>If {@code swallowIOException} is true, then we don't rethrow * {@code IOException}, but merely log it. * * @param flushable the {@code Flushable} object to be flushed. * @param swallowIOException if true, don't propagate IO exceptions * thrown by the {@code flush} method * @throws IOException if {@code swallowIOException} is false and * {@link Flushable#flush} throws an {@code IOException}. * @see Closeables#close */ public static void flush(Flushable flushable, boolean swallowIOException) throws IOException { try { flushable.flush(); } catch (IOException e) { if (swallowIOException) { logger.log(Level.WARNING, "IOException thrown while flushing Flushable.", e); } else { throw e; } } } /** * Equivalent to calling {@code flush(flushable, true)}, but with no * {@code IOException} in the signature. * * @param flushable the {@code Flushable} object to be flushed. */ public static void flushQuietly(Flushable flushable) { try { flush(flushable, true); } catch (IOException e) { logger.log(Level.SEVERE, "IOException should not have been thrown.", e); } } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import com.google.common.annotations.Beta; import java.io.IOException; /** * A callback to be used with the streaming {@code readLines} methods. * * <p>{@link #processLine} will be called for each line that is read, and * should return {@code false} when you want to stop processing. * * @author Miles Barr * @since 1.0 */ @Beta public interface LineProcessor<T> { /** * This method will be called once for each line. * * @param line the line read from the input, without delimiter * @return true to continue processing, false to stop */ boolean processLine(String line) throws IOException; /** Return the result of processing all the lines. */ T getResult(); }
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.escape.testing; import static com.google.common.escape.Escapers.computeReplacement; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.escape.CharEscaper; import com.google.common.escape.Escaper; import com.google.common.escape.UnicodeEscaper; import junit.framework.Assert; import java.io.IOException; /** * Extra assert methods for testing Escaper implementations. * * @author David Beaumont * @since 15.0 */ @Beta @GwtCompatible public final class EscaperAsserts { private EscaperAsserts() {} /** * Asserts that an escaper behaves correctly with respect to null inputs. * * @param escaper the non-null escaper to test * @throws IOException */ public static void assertBasic(Escaper escaper) throws IOException { // Escapers operate on characters: no characters, no escaping. Assert.assertEquals("", escaper.escape("")); // Assert that escapers throw null pointer exceptions. try { escaper.escape((String) null); Assert.fail("exception not thrown when escaping a null string"); } catch (NullPointerException e) { // pass } } /** * Asserts that an escaper escapes the given character into the expected * string. * * @param escaper the non-null escaper to test * @param expected the expected output string * @param c the character to escape */ public static void assertEscaping(CharEscaper escaper, String expected, char c) { String escaped = computeReplacement(escaper, c); Assert.assertNotNull(escaped); Assert.assertEquals(expected, escaped); } /** * Asserts that an escaper does not escape the given character. * * @param escaper the non-null escaper to test * @param c the character to test */ public static void assertUnescaped(CharEscaper escaper, char c) { Assert.assertNull(computeReplacement(escaper, c)); } /** * Asserts that a Unicode escaper escapes the given code point into the * expected string. * * @param escaper the non-null escaper to test * @param expected the expected output string * @param cp the Unicode code point to escape */ public static void assertEscaping(UnicodeEscaper escaper, String expected, int cp) { String escaped = computeReplacement(escaper, cp); Assert.assertNotNull(escaped); Assert.assertEquals(expected, escaped); } /** * Asserts that a Unicode escaper does not escape the given character. * * @param escaper the non-null escaper to test * @param cp the Unicode code point to test */ public static void assertUnescaped(UnicodeEscaper escaper, int cp) { Assert.assertNull(computeReplacement(escaper, cp)); } /** * Asserts that a Unicode escaper escapes the given hi/lo surrogate pair into * the expected string. * * @param escaper the non-null escaper to test * @param expected the expected output string * @param hi the high surrogate pair character * @param lo the low surrogate pair character */ public static void assertUnicodeEscaping(UnicodeEscaper escaper, String expected, char hi, char lo) { int cp = Character.toCodePoint(hi, lo); String escaped = computeReplacement(escaper, cp); Assert.assertNotNull(escaped); Assert.assertEquals(expected, escaped); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import static com.google.common.collect.testing.Helpers.orderEntriesByKey; import com.google.common.annotations.GwtCompatible; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * Implementation helper for {@link TestMapGenerator} for use with enum maps. * * @author Kevin Bourrillion */ @GwtCompatible public abstract class TestEnumMapGenerator implements TestMapGenerator<AnEnum, String> { @Override public SampleElements<Entry<AnEnum, String>> samples() { return new SampleElements<Entry<AnEnum, String>>( Helpers.mapEntry(AnEnum.A, "January"), Helpers.mapEntry(AnEnum.B, "February"), Helpers.mapEntry(AnEnum.C, "March"), Helpers.mapEntry(AnEnum.D, "April"), Helpers.mapEntry(AnEnum.E, "May") ); } @Override public final Map<AnEnum, String> create(Object... entries) { @SuppressWarnings("unchecked") Entry<AnEnum, String>[] array = new Entry[entries.length]; int i = 0; for (Object o : entries) { @SuppressWarnings("unchecked") Entry<AnEnum, String> e = (Entry<AnEnum, String>) o; array[i++] = e; } return create(array); } protected abstract Map<AnEnum, String> create( Entry<AnEnum, String>[] entries); @Override @SuppressWarnings("unchecked") public final Entry<AnEnum, String>[] createArray(int length) { return new Entry[length]; } @Override public final AnEnum[] createKeyArray(int length) { return new AnEnum[length]; } @Override public final String[] createValueArray(int length) { return new String[length]; } /** Returns the elements sorted in natural order. */ @Override public Iterable<Entry<AnEnum, String>> order( List<Entry<AnEnum, String>> insertionOrder) { return orderEntriesByKey(insertionOrder); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.Iterator; /** * Creates iterators to be tested. * * @param <E> the element type of the iterator. * * @author George van den Driessche */ @GwtCompatible public interface TestIteratorGenerator<E> { Iterator<E> get(); }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.Collections; import java.util.Iterator; /** * A utility for testing an Iterator implementation by comparing its behavior to * that of a "known good" reference implementation. In order to accomplish this, * it's important to test a great variety of sequences of the * {@link Iterator#next}, {@link Iterator#hasNext} and {@link Iterator#remove} * operations. This utility takes the brute-force approach of trying <i>all</i> * possible sequences of these operations, up to a given number of steps. So, if * the caller specifies to use <i>n</i> steps, a total of <i>3^n</i> tests are * actually performed. * * <p>For instance, if <i>steps</i> is 5, one example sequence that will be * tested is: * * <ol> * <li>remove(); * <li>hasNext() * <li>hasNext(); * <li>remove(); * <li>next(); * </ol> * * <p>This particular order of operations may be unrealistic, and testing all 3^5 * of them may be thought of as overkill; however, it's difficult to determine * which proper subset of this massive set would be sufficient to expose any * possible bug. Brute force is simpler. * * <p>To use this class the concrete subclass must implement the * {@link IteratorTester#newTargetIterator()} method. This is because it's * impossible to test an Iterator without changing its state, so the tester * needs a steady supply of fresh Iterators. * * <p>If your iterator supports modification through {@code remove()}, you may * wish to override the verify() method, which is called <em>after</em> * each sequence and is guaranteed to be called using the latest values * obtained from {@link IteratorTester#newTargetIterator()}. * * @author Kevin Bourrillion * @author Chris Povirk */ @GwtCompatible public abstract class IteratorTester<E> extends AbstractIteratorTester<E, Iterator<E>> { /** * Creates an IteratorTester. * * @param steps how many operations to test for each tested pair of iterators * @param features the features supported by the iterator */ protected IteratorTester(int steps, Iterable<? extends IteratorFeature> features, Iterable<E> expectedElements, KnownOrder knownOrder) { super(steps, Collections.<E>singleton(null), features, expectedElements, knownOrder, 0); } @Override protected final Iterable<Stimulus<E, Iterator<E>>> getStimulusValues() { return iteratorStimuli(); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.Feature; import com.google.common.testing.SerializableTester; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Concrete instantiation of {@link AbstractCollectionTestSuiteBuilder} for * testing collections that do not have a more specific tester like * {@link ListTestSuiteBuilder} or {@link SetTestSuiteBuilder}. * * @author Chris Povirk * @author Louis Wasserman */ public class CollectionTestSuiteBuilder<E> extends AbstractCollectionTestSuiteBuilder< CollectionTestSuiteBuilder<E>, E> { public static <E> CollectionTestSuiteBuilder<E> using( TestCollectionGenerator<E> generator) { return new CollectionTestSuiteBuilder<E>().usingGenerator(generator); } @Override protected List<TestSuite> createDerivedSuites( FeatureSpecificTestSuiteBuilder< ?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) { List<TestSuite> derivedSuites = new ArrayList<TestSuite>( super.createDerivedSuites(parentBuilder)); if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) { derivedSuites.add(CollectionTestSuiteBuilder .using(new ReserializedCollectionGenerator<E>(parentBuilder.getSubjectGenerator())) .named(getName() + " reserialized") .withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures())) .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite()); } return derivedSuites; } static class ReserializedCollectionGenerator<E> implements TestCollectionGenerator<E> { final OneSizeTestContainerGenerator<Collection<E>, E> gen; private ReserializedCollectionGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) { this.gen = gen; } @Override public SampleElements<E> samples() { return gen.samples(); } @Override public Collection<E> create(Object... elements) { return SerializableTester.reserialize(gen.create(elements)); } @Override public E[] createArray(int length) { return gen.createArray(length); } @Override public Iterable<E> order(List<E> insertionOrder) { return gen.order(insertionOrder); } } private static Set<Feature<?>> computeReserializedCollectionFeatures(Set<Feature<?>> features) { Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>(); derivedFeatures.addAll(features); derivedFeatures.remove(CollectionFeature.SERIALIZABLE); derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS); return derivedFeatures; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import static java.util.Collections.disjoint; import static java.util.logging.Level.FINER; import com.google.common.collect.testing.features.ConflictingRequirementsException; import com.google.common.collect.testing.features.Feature; import com.google.common.collect.testing.features.FeatureUtil; import com.google.common.collect.testing.features.TesterRequirements; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.logging.Logger; /** * Creates, based on your criteria, a JUnit test suite that exhaustively tests * the object generated by a G, selecting appropriate tests by matching them * against specified features. * * @param <B> The concrete type of this builder (the 'self-type'). All the * Builder methods of this class (such as {@link #named}) return this type, so * that Builder methods of more derived classes can be chained onto them without * casting. * @param <G> The type of the generator to be passed to testers in the * generated test suite. An instance of G should somehow provide an * instance of the class under test, plus any other information required * to parameterize the test. * * @author George van den Driessche */ public abstract class FeatureSpecificTestSuiteBuilder< B extends FeatureSpecificTestSuiteBuilder<B, G>, G> { @SuppressWarnings("unchecked") protected B self() { return (B) this; } // Test Data private G subjectGenerator; // Gets run before every test. private Runnable setUp; // Gets run at the conclusion of every test. private Runnable tearDown; protected B usingGenerator(G subjectGenerator) { this.subjectGenerator = subjectGenerator; return self(); } public G getSubjectGenerator() { return subjectGenerator; } public B withSetUp(Runnable setUp) { this.setUp = setUp; return self(); } protected Runnable getSetUp() { return setUp; } public B withTearDown(Runnable tearDown) { this.tearDown = tearDown; return self(); } protected Runnable getTearDown() { return tearDown; } // Features private Set<Feature<?>> features = new LinkedHashSet<Feature<?>>(); /** * Configures this builder to produce tests appropriate for the given * features. This method may be called more than once to add features * in multiple groups. */ public B withFeatures(Feature<?>... features) { return withFeatures(Arrays.asList(features)); } public B withFeatures(Iterable<? extends Feature<?>> features) { for (Feature<?> feature : features) { this.features.add(feature); } return self(); } public Set<Feature<?>> getFeatures() { return Collections.unmodifiableSet(features); } // Name private String name; /** Configures this builder produce a TestSuite with the given name. */ public B named(String name) { if (name.contains("(")) { throw new IllegalArgumentException("Eclipse hides all characters after " + "'('; please use '[]' or other characters instead of parentheses"); } this.name = name; return self(); } public String getName() { return name; } // Test suppression private Set<Method> suppressedTests = new HashSet<Method>(); /** * Prevents the given methods from being run as part of the test suite. * * <em>Note:</em> in principle this should never need to be used, but it * might be useful if the semantics of an implementation disagree in * unforeseen ways with the semantics expected by a test, or to keep dependent * builds clean in spite of an erroneous test. */ public B suppressing(Method... methods) { return suppressing(Arrays.asList(methods)); } public B suppressing(Collection<Method> methods) { suppressedTests.addAll(methods); return self(); } public Set<Method> getSuppressedTests() { return suppressedTests; } private static final Logger logger = Logger.getLogger( FeatureSpecificTestSuiteBuilder.class.getName()); /** * Creates a runnable JUnit test suite based on the criteria already given. */ /* * Class parameters must be raw. This annotation should go on testerClass in * the for loop, but the 1.5 javac crashes on annotations in for loops: * <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6294589> */ @SuppressWarnings("unchecked") public TestSuite createTestSuite() { checkCanCreate(); logger.fine(" Testing: " + name); logger.fine("Features: " + formatFeatureSet(features)); FeatureUtil.addImpliedFeatures(features); logger.fine("Expanded: " + formatFeatureSet(features)); // Class parameters must be raw. List<Class<? extends AbstractTester>> testers = getTesters(); TestSuite suite = new TestSuite(name); for (Class<? extends AbstractTester> testerClass : testers) { final TestSuite testerSuite = makeSuiteForTesterClass( (Class<? extends AbstractTester<?>>) testerClass); if (testerSuite.countTestCases() > 0) { suite.addTest(testerSuite); } } return suite; } /** * Throw {@link IllegalStateException} if {@link #createTestSuite()} can't * be called yet. */ protected void checkCanCreate() { if (subjectGenerator == null) { throw new IllegalStateException("Call using() before createTestSuite()."); } if (name == null) { throw new IllegalStateException("Call named() before createTestSuite()."); } if (features == null) { throw new IllegalStateException( "Call withFeatures() before createTestSuite()."); } } // Class parameters must be raw. protected abstract List<Class<? extends AbstractTester>> getTesters(); private boolean matches(Test test) { final Method method; try { method = extractMethod(test); } catch (IllegalArgumentException e) { logger.finer(Platform.format( "%s: including by default: %s", test, e.getMessage())); return true; } if (suppressedTests.contains(method)) { logger.finer(Platform.format( "%s: excluding because it was explicitly suppressed.", test)); return false; } final TesterRequirements requirements; try { requirements = FeatureUtil.getTesterRequirements(method); } catch (ConflictingRequirementsException e) { throw new RuntimeException(e); } if (!features.containsAll(requirements.getPresentFeatures())) { if (logger.isLoggable(FINER)) { Set<Feature<?>> missingFeatures = Helpers.copyToSet(requirements.getPresentFeatures()); missingFeatures.removeAll(features); logger.finer(Platform.format( "%s: skipping because these features are absent: %s", method, missingFeatures)); } return false; } if (intersect(features, requirements.getAbsentFeatures())) { if (logger.isLoggable(FINER)) { Set<Feature<?>> unwantedFeatures = Helpers.copyToSet(requirements.getAbsentFeatures()); unwantedFeatures.retainAll(features); logger.finer(Platform.format( "%s: skipping because these features are present: %s", method, unwantedFeatures)); } return false; } return true; } private static boolean intersect(Set<?> a, Set<?> b) { return !disjoint(a, b); } private static Method extractMethod(Test test) { if (test instanceof AbstractTester) { AbstractTester<?> tester = (AbstractTester<?>) test; return Helpers.getMethod(tester.getClass(), tester.getTestMethodName()); } else if (test instanceof TestCase) { TestCase testCase = (TestCase) test; return Helpers.getMethod(testCase.getClass(), testCase.getName()); } else { throw new IllegalArgumentException( "unable to extract method from test: not a TestCase."); } } protected TestSuite makeSuiteForTesterClass( Class<? extends AbstractTester<?>> testerClass) { final TestSuite candidateTests = new TestSuite(testerClass); final TestSuite suite = filterSuite(candidateTests); Enumeration<?> allTests = suite.tests(); while (allTests.hasMoreElements()) { Object test = allTests.nextElement(); if (test instanceof AbstractTester) { @SuppressWarnings("unchecked") AbstractTester<? super G> tester = (AbstractTester<? super G>) test; tester.init(subjectGenerator, name, setUp, tearDown); } } return suite; } private TestSuite filterSuite(TestSuite suite) { TestSuite filtered = new TestSuite(suite.getName()); final Enumeration<?> tests = suite.tests(); while (tests.hasMoreElements()) { Test test = (Test) tests.nextElement(); if (matches(test)) { filtered.addTest(test); } } return filtered; } protected static String formatFeatureSet(Set<? extends Feature<?>> features) { List<String> temp = new ArrayList<String>(); for (Feature<?> feature : features) { Object featureAsObject = feature; // to work around bogus JDK warning if (featureAsObject instanceof Enum) { Enum<?> f = (Enum<?>) featureAsObject; temp.add(Platform.classGetSimpleName( f.getDeclaringClass()) + "." + feature); } else { temp.add(feature.toString()); } } return temp.toString(); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.Feature; import com.google.common.collect.testing.testers.CollectionSerializationEqualTester; import com.google.common.collect.testing.testers.ListAddAllAtIndexTester; import com.google.common.collect.testing.testers.ListAddAllTester; import com.google.common.collect.testing.testers.ListAddAtIndexTester; import com.google.common.collect.testing.testers.ListAddTester; import com.google.common.collect.testing.testers.ListCreationTester; import com.google.common.collect.testing.testers.ListEqualsTester; import com.google.common.collect.testing.testers.ListGetTester; import com.google.common.collect.testing.testers.ListHashCodeTester; import com.google.common.collect.testing.testers.ListIndexOfTester; import com.google.common.collect.testing.testers.ListLastIndexOfTester; import com.google.common.collect.testing.testers.ListListIteratorTester; import com.google.common.collect.testing.testers.ListRemoveAllTester; import com.google.common.collect.testing.testers.ListRemoveAtIndexTester; import com.google.common.collect.testing.testers.ListRemoveTester; import com.google.common.collect.testing.testers.ListRetainAllTester; import com.google.common.collect.testing.testers.ListSetTester; import com.google.common.collect.testing.testers.ListSubListTester; import com.google.common.collect.testing.testers.ListToArrayTester; import com.google.common.testing.SerializableTester; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Creates, based on your criteria, a JUnit test suite that exhaustively tests * a List implementation. * * @author George van den Driessche */ public final class ListTestSuiteBuilder<E> extends AbstractCollectionTestSuiteBuilder<ListTestSuiteBuilder<E>, E> { public static <E> ListTestSuiteBuilder<E> using( TestListGenerator<E> generator) { return new ListTestSuiteBuilder<E>().usingGenerator(generator); } @Override protected List<Class<? extends AbstractTester>> getTesters() { List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters()); testers.add(CollectionSerializationEqualTester.class); testers.add(ListAddAllAtIndexTester.class); testers.add(ListAddAllTester.class); testers.add(ListAddAtIndexTester.class); testers.add(ListAddTester.class); testers.add(ListCreationTester.class); testers.add(ListEqualsTester.class); testers.add(ListGetTester.class); testers.add(ListHashCodeTester.class); testers.add(ListIndexOfTester.class); testers.add(ListLastIndexOfTester.class); testers.add(ListListIteratorTester.class); testers.add(ListRemoveAllTester.class); testers.add(ListRemoveAtIndexTester.class); testers.add(ListRemoveTester.class); testers.add(ListRetainAllTester.class); testers.add(ListSetTester.class); testers.add(ListSubListTester.class); testers.add(ListToArrayTester.class); return testers; } /** * Specifies {@link CollectionFeature#KNOWN_ORDER} for all list tests, since * lists have an iteration ordering corresponding to the insertion order. */ @Override public TestSuite createTestSuite() { withFeatures(CollectionFeature.KNOWN_ORDER); return super.createTestSuite(); } @Override protected List<TestSuite> createDerivedSuites( FeatureSpecificTestSuiteBuilder< ?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) { List<TestSuite> derivedSuites = new ArrayList<TestSuite>( super.createDerivedSuites(parentBuilder)); if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) { derivedSuites.add(ListTestSuiteBuilder .using(new ReserializedListGenerator<E>(parentBuilder.getSubjectGenerator())) .named(getName() + " reserialized") .withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures())) .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite()); } return derivedSuites; } static class ReserializedListGenerator<E> implements TestListGenerator<E>{ final OneSizeTestContainerGenerator<Collection<E>, E> gen; private ReserializedListGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) { this.gen = gen; } @Override public SampleElements<E> samples() { return gen.samples(); } @Override public List<E> create(Object... elements) { return (List<E>) SerializableTester.reserialize(gen.create(elements)); } @Override public E[] createArray(int length) { return gen.createArray(length); } @Override public Iterable<E> order(List<E> insertionOrder) { return gen.order(insertionOrder); } } private static Set<Feature<?>> computeReserializedCollectionFeatures( Set<Feature<?>> features) { Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>(); derivedFeatures.addAll(features); derivedFeatures.remove(CollectionFeature.SERIALIZABLE); derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS); return derivedFeatures; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; /** * To be implemented by test generators that can produce test subjects without * requiring any parameters. * * @param <T> the type created by this generator. * * @author George van den Driessche */ @GwtCompatible public interface TestSubjectGenerator<T> { T createTestSubject(); }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import static java.util.Collections.sort; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import junit.framework.Assert; import junit.framework.AssertionFailedError; import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; @GwtCompatible(emulated = true) public class Helpers { // Clone of Objects.equal static boolean equal(Object a, Object b) { return a == b || (a != null && a.equals(b)); } // Clone of Lists.newArrayList public static <E> List<E> copyToList(Iterable<? extends E> elements) { List<E> list = new ArrayList<E>(); addAll(list, elements); return list; } public static <E> List<E> copyToList(E[] elements) { return copyToList(Arrays.asList(elements)); } // Clone of Sets.newLinkedHashSet public static <E> Set<E> copyToSet(Iterable<? extends E> elements) { Set<E> set = new LinkedHashSet<E>(); addAll(set, elements); return set; } public static <E> Set<E> copyToSet(E[] elements) { return copyToSet(Arrays.asList(elements)); } // Would use Maps.immutableEntry public static <K, V> Entry<K, V> mapEntry(K key, V value) { return Collections.singletonMap(key, value).entrySet().iterator().next(); } public static void assertEqualIgnoringOrder( Iterable<?> expected, Iterable<?> actual) { List<?> exp = copyToList(expected); List<?> act = copyToList(actual); String actString = act.toString(); // Of course we could take pains to give the complete description of the // problem on any failure. // Yeah it's n^2. for (Object object : exp) { if (!act.remove(object)) { Assert.fail("did not contain expected element " + object + ", " + "expected = " + exp + ", actual = " + actString); } } assertTrue("unexpected elements: " + act, act.isEmpty()); } public static void assertContentsAnyOrder( Iterable<?> actual, Object... expected) { assertEqualIgnoringOrder(Arrays.asList(expected), actual); } public static <E> boolean addAll( Collection<E> addTo, Iterable<? extends E> elementsToAdd) { boolean modified = false; for (E e : elementsToAdd) { modified |= addTo.add(e); } return modified; } static <T> Iterable<T> reverse(final List<T> list) { return new Iterable<T>() { @Override public Iterator<T> iterator() { final ListIterator<T> listIter = list.listIterator(list.size()); return new Iterator<T>() { @Override public boolean hasNext() { return listIter.hasPrevious(); } @Override public T next() { return listIter.previous(); } @Override public void remove() { listIter.remove(); } }; } }; } static <T> Iterator<T> cycle(final Iterable<T> iterable) { return new Iterator<T>() { Iterator<T> iterator = Collections.<T>emptySet().iterator(); @Override public boolean hasNext() { return true; } @Override public T next() { if (!iterator.hasNext()) { iterator = iterable.iterator(); } return iterator.next(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } static <T> T get(Iterator<T> iterator, int position) { for (int i = 0; i < position; i++) { iterator.next(); } return iterator.next(); } static void fail(Throwable cause, Object message) { AssertionFailedError assertionFailedError = new AssertionFailedError(String.valueOf(message)); assertionFailedError.initCause(cause); throw assertionFailedError; } public static <K, V> Comparator<Entry<K, V>> entryComparator( final Comparator<? super K> keyComparator) { return new Comparator<Entry<K, V>>() { @Override @SuppressWarnings("unchecked") // no less safe than putting it in the map! public int compare(Entry<K, V> a, Entry<K, V> b) { return (keyComparator == null) ? ((Comparable) a.getKey()).compareTo(b.getKey()) : keyComparator.compare(a.getKey(), b.getKey()); } }; } public static <T> void testComparator( Comparator<? super T> comparator, T... valuesInExpectedOrder) { testComparator(comparator, Arrays.asList(valuesInExpectedOrder)); } public static <T> void testComparator( Comparator<? super T> comparator, List<T> valuesInExpectedOrder) { // This does an O(n^2) test of all pairs of values in both orders for (int i = 0; i < valuesInExpectedOrder.size(); i++) { T t = valuesInExpectedOrder.get(i); for (int j = 0; j < i; j++) { T lesser = valuesInExpectedOrder.get(j); assertTrue(comparator + ".compare(" + lesser + ", " + t + ")", comparator.compare(lesser, t) < 0); } assertEquals(comparator + ".compare(" + t + ", " + t + ")", 0, comparator.compare(t, t)); for (int j = i + 1; j < valuesInExpectedOrder.size(); j++) { T greater = valuesInExpectedOrder.get(j); assertTrue(comparator + ".compare(" + greater + ", " + t + ")", comparator.compare(greater, t) > 0); } } } public static <T extends Comparable<? super T>> void testCompareToAndEquals( List<T> valuesInExpectedOrder) { // This does an O(n^2) test of all pairs of values in both orders for (int i = 0; i < valuesInExpectedOrder.size(); i++) { T t = valuesInExpectedOrder.get(i); for (int j = 0; j < i; j++) { T lesser = valuesInExpectedOrder.get(j); assertTrue(lesser + ".compareTo(" + t + ')', lesser.compareTo(t) < 0); assertFalse(lesser.equals(t)); } assertEquals(t + ".compareTo(" + t + ')', 0, t.compareTo(t)); assertTrue(t.equals(t)); for (int j = i + 1; j < valuesInExpectedOrder.size(); j++) { T greater = valuesInExpectedOrder.get(j); assertTrue(greater + ".compareTo(" + t + ')', greater.compareTo(t) > 0); assertFalse(greater.equals(t)); } } } /** * Returns a collection that simulates concurrent modification by * having its size method return incorrect values. This is useful * for testing methods that must treat the return value from size() * as a hint only. * * @param delta the difference between the true size of the * collection and the values returned by the size method */ public static <T> Collection<T> misleadingSizeCollection(final int delta) { // It would be nice to be able to return a real concurrent // collection like ConcurrentLinkedQueue, so that e.g. concurrent // iteration would work, but that would not be GWT-compatible. return new ArrayList<T>() { @Override public int size() { return Math.max(0, super.size() + delta); } }; } /** * Returns a "nefarious" map entry with the specified key and value, * meaning an entry that is suitable for testing that map entries cannot be * modified via a nefarious implementation of equals. This is used for testing * unmodifiable collections of map entries; for example, it should not be * possible to access the raw (modifiable) map entry via a nefarious equals * method. */ public static <K, V> Map.Entry<K, V> nefariousMapEntry(final K key, final V value) { return new Map.Entry<K, V>() { @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public V setValue(V value) { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (o instanceof Map.Entry) { Map.Entry<K, V> e = (Map.Entry<K, V>) o; e.setValue(value); // muhahaha! return equal(this.getKey(), e.getKey()) && equal(this.getValue(), e.getValue()); } return false; } @Override public int hashCode() { K k = getKey(); V v = getValue(); return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode()); } /** * Returns a string representation of the form <code>{key}={value}</code>. */ @Override public String toString() { return getKey() + "=" + getValue(); } }; } static <E> List<E> castOrCopyToList(Iterable<E> iterable) { if (iterable instanceof List) { return (List<E>) iterable; } List<E> list = new ArrayList<E>(); for (E e : iterable) { list.add(e); } return list; } private static final Comparator<Comparable> NATURAL_ORDER = new Comparator<Comparable>() { @SuppressWarnings("unchecked") // assume any Comparable is Comparable<Self> @Override public int compare(Comparable left, Comparable right) { return left.compareTo(right); } }; public static <K extends Comparable, V> Iterable<Entry<K, V>> orderEntriesByKey( List<Entry<K, V>> insertionOrder) { sort(insertionOrder, Helpers.<K, V>entryComparator(NATURAL_ORDER)); return insertionOrder; } /** * Private replacement for {@link com.google.gwt.user.client.rpc.GwtTransient} to work around * build-system quirks. */ private @interface GwtTransient {} /** * Compares strings in natural order except that null comes immediately before a given value. This * works better than Ordering.natural().nullsFirst() because, if null comes before all other * values, it lies outside the submap/submultiset ranges we test, and the variety of tests that * exercise null handling fail on those subcollections. */ public abstract static class NullsBefore implements Comparator<String>, Serializable { /* * We don't serialize this class in GWT, so we don't care about whether GWT will serialize this * field. */ @GwtTransient private final String justAfterNull; protected NullsBefore(String justAfterNull) { if (justAfterNull == null) { throw new NullPointerException(); } this.justAfterNull = justAfterNull; } @Override public int compare(String lhs, String rhs) { if (lhs == rhs) { return 0; } if (lhs == null) { // lhs (null) comes just before justAfterNull. // If rhs is b, lhs comes first. if (rhs.equals(justAfterNull)) { return -1; } return justAfterNull.compareTo(rhs); } if (rhs == null) { // rhs (null) comes just before justAfterNull. // If lhs is b, rhs comes first. if (lhs.equals(justAfterNull)) { return 1; } return lhs.compareTo(justAfterNull); } return lhs.compareTo(rhs); } @Override public boolean equals(Object obj) { if (obj instanceof NullsBefore) { NullsBefore other = (NullsBefore) obj; return justAfterNull.equals(other.justAfterNull); } return false; } @Override public int hashCode() { return justAfterNull.hashCode(); } } public static final class NullsBeforeB extends NullsBefore { public static final NullsBeforeB INSTANCE = new NullsBeforeB(); private NullsBeforeB() { super("b"); } } public static final class NullsBeforeTwo extends NullsBefore { public static final NullsBeforeTwo INSTANCE = new NullsBeforeTwo(); private NullsBeforeTwo() { super("two"); // from TestStringSortedMapGenerator's sample keys } } @GwtIncompatible("reflection") public static Method getMethod(Class<?> clazz, String name) { try { return clazz.getMethod(name); } catch (Exception e) { throw new IllegalArgumentException(e); } } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; import com.google.common.annotations.GwtCompatible; import junit.framework.AssertionFailedError; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.Stack; /** * Most of the logic for {@link IteratorTester} and {@link ListIteratorTester}. * * @param <E> the type of element returned by the iterator * @param <I> the type of the iterator ({@link Iterator} or * {@link ListIterator}) * * @author Kevin Bourrillion * @author Chris Povirk */ @GwtCompatible abstract class AbstractIteratorTester<E, I extends Iterator<E>> { private boolean whenNextThrowsExceptionStopTestingCallsToRemove; private boolean whenAddThrowsExceptionStopTesting; /** * Don't verify iterator behavior on remove() after a call to next() * throws an exception. * * <p>JDK 6 currently has a bug where some iterators get into a undefined * state when next() throws a NoSuchElementException. The correct * behavior is for remove() to remove the last element returned by * next, even if a subsequent next() call threw an exception; however * JDK 6's HashMap and related classes throw an IllegalStateException * in this case. * * <p>Calling this method causes the iterator tester to skip testing * any remove() in a stimulus sequence after the reference iterator * throws an exception in next(). * * <p>TODO: remove this once we're on 6u5, which has the fix. * * @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6529795"> * Sun Java Bug 6529795</a> */ public void ignoreSunJavaBug6529795() { whenNextThrowsExceptionStopTestingCallsToRemove = true; } /** * Don't verify iterator behavior after a call to add() throws an exception. * * <p>AbstractList's ListIterator implementation gets into a undefined state * when add() throws an UnsupportedOperationException. Instead of leaving the * iterator's position unmodified, it increments it, skipping an element or * even moving past the end of the list. * * <p>Calling this method causes the iterator tester to skip testing in a * stimulus sequence after the iterator under test throws an exception in * add(). * * <p>TODO: remove this once the behavior is fixed. * * @see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6533203"> * Sun Java Bug 6533203</a> */ public void stopTestingWhenAddThrowsException() { whenAddThrowsExceptionStopTesting = true; } private Stimulus<E, ? super I>[] stimuli; private final Iterator<E> elementsToInsert; private final Set<IteratorFeature> features; private final List<E> expectedElements; private final int startIndex; private final KnownOrder knownOrder; /** * Meta-exception thrown by * {@link AbstractIteratorTester.MultiExceptionListIterator} instead of * throwing any particular exception type. */ // This class is accessible but not supported in GWT. private static final class PermittedMetaException extends RuntimeException { final Set<? extends Class<? extends RuntimeException>> exceptionClasses; PermittedMetaException( Set<? extends Class<? extends RuntimeException>> exceptionClasses) { super("one of " + exceptionClasses); this.exceptionClasses = exceptionClasses; } PermittedMetaException(Class<? extends RuntimeException> exceptionClass) { this(Collections.singleton(exceptionClass)); } // It's not supported In GWT, it always returns true. boolean isPermitted(RuntimeException exception) { for (Class<? extends RuntimeException> clazz : exceptionClasses) { if (Platform.checkIsInstance(clazz, exception)) { return true; } } return false; } // It's not supported in GWT, it always passes. void assertPermitted(RuntimeException exception) { if (!isPermitted(exception)) { // TODO: use simple class names String message = "Exception " + exception.getClass() + " was thrown; expected " + this; Helpers.fail(exception, message); } } @Override public String toString() { return getMessage(); } private static final long serialVersionUID = 0; } private static final class UnknownElementException extends RuntimeException { private UnknownElementException(Collection<?> expected, Object actual) { super("Returned value '" + actual + "' not found. Remaining elements: " + expected); } private static final long serialVersionUID = 0; } /** * Quasi-implementation of {@link ListIterator} that works from a list of * elements and a set of features to support (from the enclosing * {@link AbstractIteratorTester} instance). Instead of throwing exceptions * like {@link NoSuchElementException} at the appropriate times, it throws * {@link PermittedMetaException} instances, which wrap a set of all * exceptions that the iterator could throw during the invocation of that * method. This is necessary because, e.g., a call to * {@code iterator().remove()} of an unmodifiable list could throw either * {@link IllegalStateException} or {@link UnsupportedOperationException}. * Note that iterator implementations should always throw one of the * exceptions in a {@code PermittedExceptions} instance, since * {@code PermittedExceptions} is thrown only when a method call is invalid. * * <p>This class is accessible but not supported in GWT as it references * {@link PermittedMetaException}. */ protected final class MultiExceptionListIterator implements ListIterator<E> { // TODO: track seen elements when order isn't guaranteed // TODO: verify contents afterward // TODO: something shiny and new instead of Stack // TODO: test whether null is supported (create a Feature) /** * The elements to be returned by future calls to {@code next()}, with the * first at the top of the stack. */ final Stack<E> nextElements = new Stack<E>(); /** * The elements to be returned by future calls to {@code previous()}, with * the first at the top of the stack. */ final Stack<E> previousElements = new Stack<E>(); /** * {@link #nextElements} if {@code next()} was called more recently then * {@code previous}, {@link #previousElements} if the reverse is true, or -- * overriding both of these -- {@code null} if {@code remove()} or * {@code add()} has been called more recently than either. We use this to * determine which stack to pop from on a call to {@code remove()} (or to * pop from and push to on a call to {@code set()}. */ Stack<E> stackWithLastReturnedElementAtTop = null; MultiExceptionListIterator(List<E> expectedElements) { Helpers.addAll(nextElements, Helpers.reverse(expectedElements)); for (int i = 0; i < startIndex; i++) { previousElements.push(nextElements.pop()); } } @Override public void add(E e) { if (!features.contains(IteratorFeature.SUPPORTS_ADD)) { throw new PermittedMetaException(UnsupportedOperationException.class); } previousElements.push(e); stackWithLastReturnedElementAtTop = null; } @Override public boolean hasNext() { return !nextElements.isEmpty(); } @Override public boolean hasPrevious() { return !previousElements.isEmpty(); } @Override public E next() { return transferElement(nextElements, previousElements); } @Override public int nextIndex() { return previousElements.size(); } @Override public E previous() { return transferElement(previousElements, nextElements); } @Override public int previousIndex() { return nextIndex() - 1; } @Override public void remove() { throwIfInvalid(IteratorFeature.SUPPORTS_REMOVE); stackWithLastReturnedElementAtTop.pop(); stackWithLastReturnedElementAtTop = null; } @Override public void set(E e) { throwIfInvalid(IteratorFeature.SUPPORTS_SET); stackWithLastReturnedElementAtTop.pop(); stackWithLastReturnedElementAtTop.push(e); } /** * Moves the given element from its current position in * {@link #nextElements} to the top of the stack so that it is returned by * the next call to {@link Iterator#next()}. If the element is not in * {@link #nextElements}, this method throws an * {@link UnknownElementException}. * * <p>This method is used when testing iterators without a known ordering. * We poll the target iterator's next element and pass it to the reference * iterator through this method so it can return the same element. This * enables the assertion to pass and the reference iterator to properly * update its state. */ void promoteToNext(E e) { if (nextElements.remove(e)) { nextElements.push(e); } else { throw new UnknownElementException(nextElements, e); } } private E transferElement(Stack<E> source, Stack<E> destination) { if (source.isEmpty()) { throw new PermittedMetaException(NoSuchElementException.class); } destination.push(source.pop()); stackWithLastReturnedElementAtTop = destination; return destination.peek(); } private void throwIfInvalid(IteratorFeature methodFeature) { Set<Class<? extends RuntimeException>> exceptions = new HashSet<Class<? extends RuntimeException>>(); if (!features.contains(methodFeature)) { exceptions.add(UnsupportedOperationException.class); } if (stackWithLastReturnedElementAtTop == null) { exceptions.add(IllegalStateException.class); } if (!exceptions.isEmpty()) { throw new PermittedMetaException(exceptions); } } private List<E> getElements() { List<E> elements = new ArrayList<E>(); Helpers.addAll(elements, previousElements); Helpers.addAll(elements, Helpers.reverse(nextElements)); return elements; } } public enum KnownOrder { KNOWN_ORDER, UNKNOWN_ORDER } @SuppressWarnings("unchecked") // creating array of generic class Stimulus AbstractIteratorTester(int steps, Iterable<E> elementsToInsertIterable, Iterable<? extends IteratorFeature> features, Iterable<E> expectedElements, KnownOrder knownOrder, int startIndex) { // periodically we should manually try (steps * 3 / 2) here; all tests but // one should still pass (testVerifyGetsCalled()). stimuli = new Stimulus[steps]; if (!elementsToInsertIterable.iterator().hasNext()) { throw new IllegalArgumentException(); } elementsToInsert = Helpers.cycle(elementsToInsertIterable); this.features = Helpers.copyToSet(features); this.expectedElements = Helpers.copyToList(expectedElements); this.knownOrder = knownOrder; this.startIndex = startIndex; } /** * I'd like to make this a parameter to the constructor, but I can't because * the stimulus instances refer to {@code this}. */ protected abstract Iterable<? extends Stimulus<E, ? super I>> getStimulusValues(); /** * Returns a new target iterator each time it's called. This is the iterator * you are trying to test. This must return an Iterator that returns the * expected elements passed to the constructor in the given order. Warning: it * is not enough to simply pull multiple iterators from the same source * Iterable, unless that Iterator is unmodifiable. */ protected abstract I newTargetIterator(); /** * Override this to verify anything after running a list of Stimuli. * * <p>For example, verify that calls to remove() actually removed * the correct elements. * * @param elements the expected elements passed to the constructor, as mutated * by {@code remove()}, {@code set()}, and {@code add()} calls */ protected void verify(List<E> elements) {} /** * Executes the test. */ public final void test() { try { recurse(0); } catch (RuntimeException e) { throw new RuntimeException(Arrays.toString(stimuli), e); } } private void recurse(int level) { // We're going to reuse the stimuli array 3^steps times by overwriting it // in a recursive loop. Sneaky. if (level == stimuli.length) { // We've filled the array. compareResultsForThisListOfStimuli(); } else { // Keep recursing to fill the array. for (Stimulus<E, ? super I> stimulus : getStimulusValues()) { stimuli[level] = stimulus; recurse(level + 1); } } } private void compareResultsForThisListOfStimuli() { MultiExceptionListIterator reference = new MultiExceptionListIterator(expectedElements); I target = newTargetIterator(); boolean shouldStopTestingCallsToRemove = false; for (int i = 0; i < stimuli.length; i++) { Stimulus<E, ? super I> stimulus = stimuli[i]; if (stimulus.equals(remove) && shouldStopTestingCallsToRemove) { break; } try { boolean threwException = stimulus.executeAndCompare(reference, target); if (threwException && stimulus.equals(next) && whenNextThrowsExceptionStopTestingCallsToRemove) { shouldStopTestingCallsToRemove = true; } if (threwException && stimulus.equals(add) && whenAddThrowsExceptionStopTesting) { break; } List<E> elements = reference.getElements(); verify(elements); } catch (AssertionFailedError cause) { Helpers.fail(cause, "failed with stimuli " + subListCopy(stimuli, i + 1)); } } } private static List<Object> subListCopy(Object[] source, int size) { final Object[] copy = new Object[size]; System.arraycopy(source, 0, copy, 0, size); return Arrays.asList(copy); } private interface IteratorOperation { Object execute(Iterator<?> iterator); } /** * Apply this method to both iterators and return normally only if both * produce the same response. * * @return {@code true} if an exception was thrown by the iterators. * * @see Stimulus#executeAndCompare(ListIterator, Iterator) */ private <T extends Iterator<E>> boolean internalExecuteAndCompare( T reference, T target, IteratorOperation method) throws AssertionFailedError { Object referenceReturnValue = null; PermittedMetaException referenceException = null; Object targetReturnValue = null; RuntimeException targetException = null; try { targetReturnValue = method.execute(target); } catch (RuntimeException e) { targetException = e; } try { if (method == NEXT_METHOD && targetException == null && knownOrder == KnownOrder.UNKNOWN_ORDER) { /* * We already know the iterator is an Iterator<E>, and now we know that * we called next(), so the returned element must be of type E. */ @SuppressWarnings("unchecked") E targetReturnValueFromNext = (E) targetReturnValue; /* * We have an Iterator<E> and want to cast it to * MultiExceptionListIterator. Because we're inside an * AbstractIteratorTester<E>, that's implicitly a cast to * AbstractIteratorTester<E>.MultiExceptionListIterator. The runtime * won't be able to verify the AbstractIteratorTester<E> part, so it's * an unchecked cast. We know, however, that the only possible value for * the type parameter is <E>, since otherwise the * MultiExceptionListIterator wouldn't be an Iterator<E>. The cast is * safe, even though javac can't tell. * * Sun bug 6665356 is an additional complication. Until OpenJDK 7, javac * doesn't recognize this kind of cast as unchecked cast. Neither does * Eclipse 3.4. Right now, this suppression is mostly unecessary. */ MultiExceptionListIterator multiExceptionListIterator = (MultiExceptionListIterator) reference; multiExceptionListIterator.promoteToNext(targetReturnValueFromNext); } referenceReturnValue = method.execute(reference); } catch (PermittedMetaException e) { referenceException = e; } catch (UnknownElementException e) { Helpers.fail(e, e.getMessage()); } if (referenceException == null) { if (targetException != null) { Helpers.fail(targetException, "Target threw exception when reference did not"); } /* * Reference iterator returned a value, so we should expect the * same value from the target */ assertEquals(referenceReturnValue, targetReturnValue); return false; } if (targetException == null) { fail("Target failed to throw " + referenceException); } /* * Reference iterator threw an exception, so we should expect an acceptable * exception from the target. */ referenceException.assertPermitted(targetException); return true; } private static final IteratorOperation REMOVE_METHOD = new IteratorOperation() { @Override public Object execute(Iterator<?> iterator) { iterator.remove(); return null; } }; private static final IteratorOperation NEXT_METHOD = new IteratorOperation() { @Override public Object execute(Iterator<?> iterator) { return iterator.next(); } }; private static final IteratorOperation PREVIOUS_METHOD = new IteratorOperation() { @Override public Object execute(Iterator<?> iterator) { return ((ListIterator<?>) iterator).previous(); } }; private final IteratorOperation newAddMethod() { final Object toInsert = elementsToInsert.next(); return new IteratorOperation() { @Override public Object execute(Iterator<?> iterator) { @SuppressWarnings("unchecked") ListIterator<Object> rawIterator = (ListIterator<Object>) iterator; rawIterator.add(toInsert); return null; } }; } private final IteratorOperation newSetMethod() { final E toInsert = elementsToInsert.next(); return new IteratorOperation() { @Override public Object execute(Iterator<?> iterator) { @SuppressWarnings("unchecked") ListIterator<E> li = (ListIterator<E>) iterator; li.set(toInsert); return null; } }; } abstract static class Stimulus<E, T extends Iterator<E>> { private final String toString; protected Stimulus(String toString) { this.toString = toString; } /** * Send this stimulus to both iterators and return normally only if both * produce the same response. * * @return {@code true} if an exception was thrown by the iterators. */ abstract boolean executeAndCompare(ListIterator<E> reference, T target); @Override public String toString() { return toString; } } Stimulus<E, Iterator<E>> hasNext = new Stimulus<E, Iterator<E>>("hasNext") { @Override boolean executeAndCompare(ListIterator<E> reference, Iterator<E> target) { // return only if both are true or both are false assertEquals(reference.hasNext(), target.hasNext()); return false; } }; Stimulus<E, Iterator<E>> next = new Stimulus<E, Iterator<E>>("next") { @Override boolean executeAndCompare(ListIterator<E> reference, Iterator<E> target) { return internalExecuteAndCompare(reference, target, NEXT_METHOD); } }; Stimulus<E, Iterator<E>> remove = new Stimulus<E, Iterator<E>>("remove") { @Override boolean executeAndCompare(ListIterator<E> reference, Iterator<E> target) { return internalExecuteAndCompare(reference, target, REMOVE_METHOD); } }; @SuppressWarnings("unchecked") List<Stimulus<E, Iterator<E>>> iteratorStimuli() { return Arrays.asList(hasNext, next, remove); } Stimulus<E, ListIterator<E>> hasPrevious = new Stimulus<E, ListIterator<E>>("hasPrevious") { @Override boolean executeAndCompare( ListIterator<E> reference, ListIterator<E> target) { // return only if both are true or both are false assertEquals(reference.hasPrevious(), target.hasPrevious()); return false; } }; Stimulus<E, ListIterator<E>> nextIndex = new Stimulus<E, ListIterator<E>>("nextIndex") { @Override boolean executeAndCompare( ListIterator<E> reference, ListIterator<E> target) { assertEquals(reference.nextIndex(), target.nextIndex()); return false; } }; Stimulus<E, ListIterator<E>> previousIndex = new Stimulus<E, ListIterator<E>>("previousIndex") { @Override boolean executeAndCompare( ListIterator<E> reference, ListIterator<E> target) { assertEquals(reference.previousIndex(), target.previousIndex()); return false; } }; Stimulus<E, ListIterator<E>> previous = new Stimulus<E, ListIterator<E>>("previous") { @Override boolean executeAndCompare( ListIterator<E> reference, ListIterator<E> target) { return internalExecuteAndCompare(reference, target, PREVIOUS_METHOD); } }; Stimulus<E, ListIterator<E>> add = new Stimulus<E, ListIterator<E>>("add") { @Override boolean executeAndCompare( ListIterator<E> reference, ListIterator<E> target) { return internalExecuteAndCompare(reference, target, newAddMethod()); } }; Stimulus<E, ListIterator<E>> set = new Stimulus<E, ListIterator<E>>("set") { @Override boolean executeAndCompare( ListIterator<E> reference, ListIterator<E> target) { return internalExecuteAndCompare(reference, target, newSetMethod()); } }; @SuppressWarnings("unchecked") List<Stimulus<E, ListIterator<E>>> listIteratorStimuli() { return Arrays.asList( hasPrevious, nextIndex, previousIndex, previous, add, set); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements.Strings; import java.util.List; import java.util.Queue; /** * Create queue of strings for tests. * * @author Jared Levy */ @GwtCompatible public abstract class TestStringQueueGenerator implements TestQueueGenerator<String> { @Override public SampleElements<String> samples() { return new Strings(); } @Override public Queue<String> create(Object... elements) { String[] array = new String[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (String) e; } return create(array); } protected abstract Queue<String> create(String[] elements); @Override public String[] createArray(int length) { return new String[length]; } /** Returns the original element list, unchanged. */ @Override public List<String> order(List<String> insertionOrder) { return insertionOrder; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements.Strings; import java.util.List; import java.util.Set; /** * Create string sets for collection tests. * * @author Kevin Bourrillion */ @GwtCompatible public abstract class TestStringSetGenerator implements TestSetGenerator<String> { @Override public SampleElements<String> samples() { return new Strings(); } @Override public Set<String> create(Object... elements) { String[] array = new String[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (String) e; } return create(array); } protected abstract Set<String> create(String[] elements); @Override public String[] createArray(int length) { return new String[length]; } /** * {@inheritDoc} * * <p>By default, returns the supplied elements in their given order; however, * generators for containers with a known order other than insertion order * must override this method. * * <p>Note: This default implementation is overkill (but valid) for an * unordered container. An equally valid implementation for an unordered * container is to throw an exception. The chosen implementation, however, has * the advantage of working for insertion-ordered containers, as well. */ @Override public List<String> order(List<String> insertionOrder) { return insertionOrder; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.Iterator; /** * Adapts a test iterable generator to give a TestIteratorGenerator. * * @author George van den Driessche */ @GwtCompatible public final class DerivedTestIteratorGenerator<E> implements TestIteratorGenerator<E>, DerivedGenerator { private final TestSubjectGenerator<? extends Iterable<E>> collectionGenerator; public DerivedTestIteratorGenerator( TestSubjectGenerator<? extends Iterable<E>> collectionGenerator) { this.collectionGenerator = collectionGenerator; } @Override public TestSubjectGenerator<? extends Iterable<E>> getInnerGenerator() { return collectionGenerator; } @Override public Iterator<E> get() { return collectionGenerator.createTestSubject().iterator(); } }
Java
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.annotations.GwtCompatible; import java.util.SortedSet; /** * Creates sorted sets, containing sample elements, to be tested. * * @author Louis Wasserman */ @GwtCompatible public interface TestSortedSetGenerator<E> extends TestSetGenerator<E> { @Override SortedSet<E> create(Object... elements); /** * Returns an element less than the {@link #samples()} and less than * {@link #belowSamplesGreater()}. */ E belowSamplesLesser(); /** * Returns an element less than the {@link #samples()} but greater than * {@link #belowSamplesLesser()}. */ E belowSamplesGreater(); /** * Returns an element greater than the {@link #samples()} but less than * {@link #aboveSamplesGreater()}. */ E aboveSamplesLesser(); /** * Returns an element greater than the {@link #samples()} and greater than * {@link #aboveSamplesLesser()}. */ E aboveSamplesGreater(); }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing; import com.google.common.collect.testing.features.CollectionFeature; import com.google.common.collect.testing.features.Feature; import com.google.common.collect.testing.testers.CollectionSerializationEqualTester; import com.google.common.collect.testing.testers.SetAddAllTester; import com.google.common.collect.testing.testers.SetAddTester; import com.google.common.collect.testing.testers.SetCreationTester; import com.google.common.collect.testing.testers.SetEqualsTester; import com.google.common.collect.testing.testers.SetHashCodeTester; import com.google.common.collect.testing.testers.SetRemoveTester; import com.google.common.testing.SerializableTester; import junit.framework.TestSuite; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Creates, based on your criteria, a JUnit test suite that exhaustively tests * a Set implementation. * * @author George van den Driessche */ public class SetTestSuiteBuilder<E> extends AbstractCollectionTestSuiteBuilder<SetTestSuiteBuilder<E>, E> { public static <E> SetTestSuiteBuilder<E> using( TestSetGenerator<E> generator) { return new SetTestSuiteBuilder<E>().usingGenerator(generator); } @Override protected List<Class<? extends AbstractTester>> getTesters() { List<Class<? extends AbstractTester>> testers = Helpers.copyToList(super.getTesters()); testers.add(CollectionSerializationEqualTester.class); testers.add(SetAddAllTester.class); testers.add(SetAddTester.class); testers.add(SetCreationTester.class); testers.add(SetHashCodeTester.class); testers.add(SetEqualsTester.class); testers.add(SetRemoveTester.class); // SetRemoveAllTester doesn't exist because, Sets not permitting // duplicate elements, there are no tests for Set.removeAll() that aren't // covered by CollectionRemoveAllTester. return testers; } @Override protected List<TestSuite> createDerivedSuites( FeatureSpecificTestSuiteBuilder< ?, ? extends OneSizeTestContainerGenerator<Collection<E>, E>> parentBuilder) { List<TestSuite> derivedSuites = new ArrayList<TestSuite>( super.createDerivedSuites(parentBuilder)); if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) { derivedSuites.add(SetTestSuiteBuilder .using(new ReserializedSetGenerator<E>(parentBuilder.getSubjectGenerator())) .named(getName() + " reserialized") .withFeatures(computeReserializedCollectionFeatures(parentBuilder.getFeatures())) .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite()); } return derivedSuites; } static class ReserializedSetGenerator<E> implements TestSetGenerator<E>{ final OneSizeTestContainerGenerator<Collection<E>, E> gen; private ReserializedSetGenerator(OneSizeTestContainerGenerator<Collection<E>, E> gen) { this.gen = gen; } @Override public SampleElements<E> samples() { return gen.samples(); } @Override public Set<E> create(Object... elements) { return (Set<E>) SerializableTester.reserialize(gen.create(elements)); } @Override public E[] createArray(int length) { return gen.createArray(length); } @Override public Iterable<E> order(List<E> insertionOrder) { return gen.order(insertionOrder); } } private static Set<Feature<?>> computeReserializedCollectionFeatures( Set<Feature<?>> features) { Set<Feature<?>> derivedFeatures = new HashSet<Feature<?>>(); derivedFeatures.addAll(features); derivedFeatures.remove(CollectionFeature.SERIALIZABLE); derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS); return derivedFeatures; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Collection; import java.util.Collections; import java.util.Set; /** * When describing the features of the collection produced by a given generator * (i.e. in a call to {@link * com.google.common.collect.testing.FeatureSpecificTestSuiteBuilder#withFeatures(Feature...)}), * this annotation specifies each of the different sizes for which a test suite * should be built. (In a typical case, the features should include {@link * CollectionSize#ANY}.) These semantics are thus a little different * from those of other Collection-related features such as {@link * CollectionFeature} or {@link SetFeature}. * <p> * However, when {@link CollectionSize.Require} is used to annotate a test it * behaves normally (i.e. it requires the collection instance under test to be * a certain size for the test to run). Note that this means a test should not * require more than one CollectionSize, since a particular collection instance * can only be one size at once. * * @author George van den Driessche */ // Enum values use constructors with generic varargs. @SuppressWarnings("unchecked") @GwtCompatible public enum CollectionSize implements Feature<Collection>, Comparable<CollectionSize> { /** Test an empty collection. */ ZERO(0), /** Test a one-element collection. */ ONE(1), /** Test a three-element collection. */ SEVERAL(3), /* * TODO: add VERY_LARGE, noting that we currently assume that the fourth * sample element is not in any collection */ ANY( ZERO, ONE, SEVERAL ); private final Set<Feature<? super Collection>> implied; private final Integer numElements; CollectionSize(int numElements) { this.implied = Collections.emptySet(); this.numElements = numElements; } CollectionSize(Feature<? super Collection> ... implied) { // Keep the order here, so that PerCollectionSizeTestSuiteBuilder // gives a predictable order of test suites. this.implied = Helpers.copyToSet(implied); this.numElements = null; } @Override public Set<Feature<? super Collection>> getImpliedFeatures() { return implied; } public int getNumElements() { if (numElements == null) { throw new IllegalStateException( "A compound CollectionSize doesn't specify a number of elements."); } return numElements; } @Retention(RetentionPolicy.RUNTIME) @Inherited @TesterAnnotation public @interface Require { CollectionSize[] value() default {}; CollectionSize[] absent() default {}; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import java.util.Set; /** * Base class for enumerating the features of an interface to be tested. * * @param <T> The interface whose features are to be enumerated. * @author George van den Driessche */ @GwtCompatible public interface Feature<T> { /** Returns the set of features that are implied by this feature. */ Set<Feature<? super T>> getImpliedFeatures(); }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Map; import java.util.Set; /** * Optional features of classes derived from {@code Map}. * * @author George van den Driessche */ // Enum values use constructors with generic varargs. @SuppressWarnings("unchecked") @GwtCompatible public enum MapFeature implements Feature<Map> { /** * The map does not throw {@code NullPointerException} on calls such as * {@code containsKey(null)}, {@code get(null)}, or {@code remove(null)}. */ ALLOWS_NULL_QUERIES, ALLOWS_NULL_KEYS (ALLOWS_NULL_QUERIES), ALLOWS_NULL_VALUES, RESTRICTS_KEYS, RESTRICTS_VALUES, SUPPORTS_PUT, SUPPORTS_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION, /** * Indicates that the constructor or factory method of a map, usually an * immutable map, throws an {@link IllegalArgumentException} when presented * with duplicate keys instead of discarding all but one. */ REJECTS_DUPLICATES_AT_CREATION, GENERAL_PURPOSE( SUPPORTS_PUT, SUPPORTS_REMOVE ); private final Set<Feature<? super Map>> implied; MapFeature(Feature<? super Map> ... implied) { this.implied = Helpers.copyToSet(implied); } @Override public Set<Feature<? super Map>> getImpliedFeatures() { return implied; } @Retention(RetentionPolicy.RUNTIME) @Inherited @TesterAnnotation public @interface Require { public abstract MapFeature[] value() default {}; public abstract MapFeature[] absent() default {}; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import java.util.Set; /** * Thrown when requirements on a tester method or class conflict with * each other. * * @author George van den Driessche */ @GwtCompatible public class ConflictingRequirementsException extends Exception { private Set<Feature<?>> conflicts; private Object source; public ConflictingRequirementsException( String message, Set<Feature<?>> conflicts, Object source) { super(message); this.conflicts = conflicts; this.source = source; } public Set<Feature<?>> getConflicts() { return conflicts; } public Object getSource() { return source; } @Override public String getMessage() { return super.getMessage() + " (source: " + source + ")"; } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; import java.util.SortedSet; /** * Optional features of classes derived from {@code Collection}. * * @author George van den Driessche */ // Enum values use constructors with generic varargs. @SuppressWarnings("unchecked") @GwtCompatible public enum CollectionFeature implements Feature<Collection> { /** * The collection must not throw {@code NullPointerException} on calls * such as {@code contains(null)} or {@code remove(null)}, but instead * must return a simple {@code false}. */ ALLOWS_NULL_QUERIES, ALLOWS_NULL_VALUES (ALLOWS_NULL_QUERIES), /** * Indicates that a collection disallows certain elements (other than * {@code null}, whose validity as an element is indicated by the presence * or absence of {@link #ALLOWS_NULL_VALUES}). * From the documentation for {@link Collection}: * <blockquote>"Some collection implementations have restrictions on the * elements that they may contain. For example, some implementations * prohibit null elements, and some have restrictions on the types of their * elements."</blockquote> */ RESTRICTS_ELEMENTS, /** * Indicates that a collection has a well-defined ordering of its elements. * The ordering may depend on the element values, such as a {@link SortedSet}, * or on the insertion ordering, such as a {@link LinkedHashSet}. All list * tests and sorted-collection tests automatically specify this feature. */ KNOWN_ORDER, /** * Indicates that a collection has a different {@link Object#toString} * representation than most collections. If not specified, the collection * tests will examine the value returned by {@link Object#toString}. */ NON_STANDARD_TOSTRING, /** * Indicates that the constructor or factory method of a collection, usually * an immutable set, throws an {@link IllegalArgumentException} when presented * with duplicate elements instead of collapsing them to a single element or * including duplicate instances in the collection. */ REJECTS_DUPLICATES_AT_CREATION, SUPPORTS_ADD, SUPPORTS_REMOVE, SUPPORTS_ITERATOR_REMOVE, FAILS_FAST_ON_CONCURRENT_MODIFICATION, /** * Features supported by general-purpose collections - * everything but {@link #RESTRICTS_ELEMENTS}. * @see java.util.Collection the definition of general-purpose collections. */ GENERAL_PURPOSE( SUPPORTS_ADD, SUPPORTS_REMOVE, SUPPORTS_ITERATOR_REMOVE), /** Features supported by collections where only removal is allowed. */ REMOVE_OPERATIONS( SUPPORTS_REMOVE, SUPPORTS_ITERATOR_REMOVE), SERIALIZABLE, SERIALIZABLE_INCLUDING_VIEWS(SERIALIZABLE), SUBSET_VIEW, DESCENDING_VIEW, /** * For documenting collections that support no optional features, such as * {@link java.util.Collections#emptySet} */ NONE; private final Set<Feature<? super Collection>> implied; CollectionFeature(Feature<? super Collection> ... implied) { this.implied = Helpers.copyToSet(implied); } @Override public Set<Feature<? super Collection>> getImpliedFeatures() { return implied; } @Retention(RetentionPolicy.RUNTIME) @Inherited @TesterAnnotation public @interface Require { CollectionFeature[] value() default {}; CollectionFeature[] absent() default {}; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.List; import java.util.Set; /** * Optional features of classes derived from {@code List}. * * @author George van den Driessche */ // Enum values use constructors with generic varargs. @SuppressWarnings("unchecked") @GwtCompatible public enum ListFeature implements Feature<List> { SUPPORTS_SET, SUPPORTS_ADD_WITH_INDEX(CollectionFeature.SUPPORTS_ADD), SUPPORTS_REMOVE_WITH_INDEX(CollectionFeature.SUPPORTS_REMOVE), GENERAL_PURPOSE( CollectionFeature.GENERAL_PURPOSE, SUPPORTS_SET, SUPPORTS_ADD_WITH_INDEX, SUPPORTS_REMOVE_WITH_INDEX ), /** Features supported by lists where only removal is allowed. */ REMOVE_OPERATIONS( CollectionFeature.REMOVE_OPERATIONS, SUPPORTS_REMOVE_WITH_INDEX ); private final Set<Feature<? super List>> implied; ListFeature(Feature<? super List> ... implied) { this.implied = Helpers.copyToSet(implied); } @Override public Set<Feature<? super List>> getImpliedFeatures() { return implied; } @Retention(RetentionPolicy.RUNTIME) @Inherited @TesterAnnotation public @interface Require { ListFeature[] value() default {}; ListFeature[] absent() default {}; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Set; /** * Optional features of classes derived from {@code Set}. * * @author George van den Driessche */ // Enum values use constructors with generic varargs. @SuppressWarnings("unchecked") @GwtCompatible public enum SetFeature implements Feature<Set> { GENERAL_PURPOSE( CollectionFeature.GENERAL_PURPOSE ); private final Set<Feature<? super Set>> implied; SetFeature(Feature<? super Set> ... implied) { this.implied = Helpers.copyToSet(implied); } @Override public Set<Feature<? super Set>> getImpliedFeatures() { return implied; } @Retention(RetentionPolicy.RUNTIME) @Inherited @TesterAnnotation public @interface Require { public abstract SetFeature[] value() default {}; public abstract SetFeature[] absent() default {}; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import java.util.Collections; import java.util.Set; /** * Encapsulates the constraints that a class under test must satisfy in order * for a tester method to be run against that class. * * @author George van den Driessche */ @GwtCompatible public final class TesterRequirements { private final Set<Feature<?>> presentFeatures; private final Set<Feature<?>> absentFeatures; public TesterRequirements( Set<Feature<?>> presentFeatures, Set<Feature<?>> absentFeatures) { this.presentFeatures = Helpers.copyToSet(presentFeatures); this.absentFeatures = Helpers.copyToSet(absentFeatures); } public TesterRequirements(TesterRequirements tr) { this(tr.getPresentFeatures(), tr.getAbsentFeatures()); } public TesterRequirements() { this(Collections.<Feature<?>>emptySet(), Collections.<Feature<?>>emptySet()); } public final Set<Feature<?>> getPresentFeatures() { return presentFeatures; } public final Set<Feature<?>> getAbsentFeatures() { return absentFeatures; } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof TesterRequirements) { TesterRequirements that = (TesterRequirements) object; return this.presentFeatures.equals(that.presentFeatures) && this.absentFeatures.equals(that.absentFeatures); } return false; } @Override public int hashCode() { return presentFeatures.hashCode() * 31 + absentFeatures.hashCode(); } @Override public String toString() { return "{TesterRequirements: present=" + presentFeatures + ", absent=" + absentFeatures + "}"; } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.collect.testing.Helpers; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Utilities for collecting and validating tester requirements from annotations. * * <p>This class can be referenced in GWT tests. * * @author George van den Driessche */ public class FeatureUtil { /** * A cache of annotated objects (typically a Class or Method) to its * set of annotations. */ private static Map<AnnotatedElement, Annotation[]> annotationCache = new HashMap<AnnotatedElement, Annotation[]>(); private static final Map<Class<?>, TesterRequirements> classTesterRequirementsCache = new HashMap<Class<?>, TesterRequirements>(); /** * Given a set of features, add to it all the features directly or indirectly * implied by any of them, and return it. * @param features the set of features to expand * @return the same set of features, expanded with all implied features */ public static Set<Feature<?>> addImpliedFeatures(Set<Feature<?>> features) { // The base case of the recursion is an empty set of features, which will // occur when the previous set contained only simple features. if (!features.isEmpty()) { features.addAll(impliedFeatures(features)); } return features; } /** * Given a set of features, return a new set of all features directly or * indirectly implied by any of them. * @param features the set of features whose implications to find * @return the implied set of features */ public static Set<Feature<?>> impliedFeatures(Set<Feature<?>> features) { Set<Feature<?>> implied = new LinkedHashSet<Feature<?>>(); for (Feature<?> feature : features) { implied.addAll(feature.getImpliedFeatures()); } addImpliedFeatures(implied); return implied; } /** * Get the full set of requirements for a tester class. * @param testerClass a tester class * @return all the constraints implicitly or explicitly required by the class * or any of its superclasses. * @throws ConflictingRequirementsException if the requirements are mutually * inconsistent. */ public static TesterRequirements getTesterRequirements(Class<?> testerClass) throws ConflictingRequirementsException { synchronized (classTesterRequirementsCache) { TesterRequirements requirements = classTesterRequirementsCache.get(testerClass); if (requirements == null) { requirements = buildTesterRequirements(testerClass); classTesterRequirementsCache.put(testerClass, requirements); } return requirements; } } /** * Get the full set of requirements for a tester class. * @param testerMethod a test method of a tester class * @return all the constraints implicitly or explicitly required by the * method, its declaring class, or any of its superclasses. * @throws ConflictingRequirementsException if the requirements are * mutually inconsistent. */ public static TesterRequirements getTesterRequirements(Method testerMethod) throws ConflictingRequirementsException { return buildTesterRequirements(testerMethod); } /** * Construct the full set of requirements for a tester class. * @param testerClass a tester class * @return all the constraints implicitly or explicitly required by the class * or any of its superclasses. * @throws ConflictingRequirementsException if the requirements are mutually * inconsistent. */ static TesterRequirements buildTesterRequirements(Class<?> testerClass) throws ConflictingRequirementsException { final TesterRequirements declaredRequirements = buildDeclaredTesterRequirements(testerClass); Class<?> baseClass = testerClass.getSuperclass(); if (baseClass == null) { return declaredRequirements; } else { final TesterRequirements clonedBaseRequirements = new TesterRequirements(getTesterRequirements(baseClass)); return incorporateRequirements( clonedBaseRequirements, declaredRequirements, testerClass); } } /** * Construct the full set of requirements for a tester method. * @param testerMethod a test method of a tester class * @return all the constraints implicitly or explicitly required by the * method, its declaring class, or any of its superclasses. * @throws ConflictingRequirementsException if the requirements are mutually * inconsistent. */ static TesterRequirements buildTesterRequirements(Method testerMethod) throws ConflictingRequirementsException { TesterRequirements clonedClassRequirements = new TesterRequirements( getTesterRequirements(testerMethod.getDeclaringClass())); TesterRequirements declaredRequirements = buildDeclaredTesterRequirements(testerMethod); return incorporateRequirements( clonedClassRequirements, declaredRequirements, testerMethod); } /** * Construct the set of requirements specified by annotations * directly on a tester class or method. * @param classOrMethod a tester class or a test method thereof * @return all the constraints implicitly or explicitly required by * annotations on the class or method. * @throws ConflictingRequirementsException if the requirements are mutually * inconsistent. */ public static TesterRequirements buildDeclaredTesterRequirements( AnnotatedElement classOrMethod) throws ConflictingRequirementsException { TesterRequirements requirements = new TesterRequirements(); Iterable<Annotation> testerAnnotations = getTesterAnnotations(classOrMethod); for (Annotation testerAnnotation : testerAnnotations) { TesterRequirements moreRequirements = buildTesterRequirements(testerAnnotation); incorporateRequirements( requirements, moreRequirements, testerAnnotation); } return requirements; } /** * Find all the tester annotations declared on a tester class or method. * @param classOrMethod a class or method whose tester annotations to find * @return an iterable sequence of tester annotations on the class */ public static Iterable<Annotation> getTesterAnnotations( AnnotatedElement classOrMethod) { List<Annotation> result = new ArrayList<Annotation>(); Annotation[] annotations; synchronized (annotationCache) { annotations = annotationCache.get(classOrMethod); if (annotations == null) { annotations = classOrMethod.getDeclaredAnnotations(); annotationCache.put(classOrMethod, annotations); } } for (Annotation a : annotations) { Class<? extends Annotation> annotationClass = a.annotationType(); if (annotationClass.isAnnotationPresent(TesterAnnotation.class)) { result.add(a); } } return result; } /** * Find all the constraints explicitly or implicitly specified by a single * tester annotation. * @param testerAnnotation a tester annotation * @return the requirements specified by the annotation * @throws ConflictingRequirementsException if the requirements are mutually * inconsistent. */ private static TesterRequirements buildTesterRequirements( Annotation testerAnnotation) throws ConflictingRequirementsException { Class<? extends Annotation> annotationClass = testerAnnotation.getClass(); final Feature<?>[] presentFeatures; final Feature<?>[] absentFeatures; try { presentFeatures = (Feature[]) annotationClass.getMethod("value") .invoke(testerAnnotation); absentFeatures = (Feature[]) annotationClass.getMethod("absent") .invoke(testerAnnotation); } catch (Exception e) { throw new IllegalArgumentException( "Error extracting features from tester annotation.", e); } Set<Feature<?>> allPresentFeatures = addImpliedFeatures(Helpers.<Feature<?>>copyToSet(presentFeatures)); Set<Feature<?>> allAbsentFeatures = addImpliedFeatures(Helpers.<Feature<?>>copyToSet(absentFeatures)); Set<Feature<?>> conflictingFeatures = intersection(allPresentFeatures, allAbsentFeatures); if (!conflictingFeatures.isEmpty()) { throw new ConflictingRequirementsException("Annotation explicitly or " + "implicitly requires one or more features to be both present " + "and absent.", conflictingFeatures, testerAnnotation); } return new TesterRequirements(allPresentFeatures, allAbsentFeatures); } /** * Incorporate additional requirements into an existing requirements object. * @param requirements the existing requirements object * @param moreRequirements more requirements to incorporate * @param source the source of the additional requirements * (used only for error reporting) * @return the existing requirements object, modified to include the * additional requirements * @throws ConflictingRequirementsException if the additional requirements * are inconsistent with the existing requirements */ private static TesterRequirements incorporateRequirements( TesterRequirements requirements, TesterRequirements moreRequirements, Object source) throws ConflictingRequirementsException { Set<Feature<?>> presentFeatures = requirements.getPresentFeatures(); Set<Feature<?>> absentFeatures = requirements.getAbsentFeatures(); Set<Feature<?>> morePresentFeatures = moreRequirements.getPresentFeatures(); Set<Feature<?>> moreAbsentFeatures = moreRequirements.getAbsentFeatures(); checkConflict( "absent", absentFeatures, "present", morePresentFeatures, source); checkConflict( "present", presentFeatures, "absent", moreAbsentFeatures, source); presentFeatures.addAll(morePresentFeatures); absentFeatures.addAll(moreAbsentFeatures); return requirements; } // Used by incorporateRequirements() only private static void checkConflict( String earlierRequirement, Set<Feature<?>> earlierFeatures, String newRequirement, Set<Feature<?>> newFeatures, Object source) throws ConflictingRequirementsException { Set<Feature<?>> conflictingFeatures; conflictingFeatures = intersection(newFeatures, earlierFeatures); if (!conflictingFeatures.isEmpty()) { throw new ConflictingRequirementsException(String.format( "Annotation requires to be %s features that earlier " + "annotations required to be %s.", newRequirement, earlierRequirement), conflictingFeatures, source); } } /** * Construct a new {@link java.util.Set} that is the intersection * of the given sets. */ // Calls generic varargs method. @SuppressWarnings("unchecked") public static <T> Set<T> intersection( Set<? extends T> set1, Set<? extends T> set2) { return intersection(new Set[] {set1, set2}); } /** * Construct a new {@link java.util.Set} that is the intersection * of all the given sets. * @param sets the sets to intersect * @return the intersection of the sets * @throws java.lang.IllegalArgumentException if there are no sets to * intersect */ public static <T> Set<T> intersection(Set<? extends T> ... sets) { if (sets.length == 0) { throw new IllegalArgumentException( "Can't intersect no sets; would have to return the universe."); } Set<T> results = Helpers.copyToSet(sets[0]); for (int i = 1; i < sets.length; i++) { Set<? extends T> set = sets[i]; results.retainAll(set); } return results; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect.testing.features; import com.google.common.annotations.GwtCompatible; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Use this to meta-annotate XxxFeature.Require annotations, so that those * annotations can be used to decide whether to apply a test to a given * class-under-test. * <br> * This is needed because annotations can't implement interfaces, which is also * why reflection is used to extract values from the properties of the various * annotations. * * @see CollectionFeature.Require * * @author George van den Driessche */ @Target(value = {java.lang.annotation.ElementType.ANNOTATION_TYPE}) @Retention(value = RetentionPolicy.RUNTIME) @Documented @GwtCompatible public @interface TesterAnnotation { }
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.collect.testing; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.NavigableSet; import java.util.SortedSet; import java.util.TreeSet; /** * A wrapper around {@code TreeSet} that aggressively checks to see if elements * are mutually comparable. This implementation passes the navigable set test * suites. * * @author Louis Wasserman */ public final class SafeTreeSet<E> implements Serializable, NavigableSet<E> { @SuppressWarnings("unchecked") private static final Comparator NATURAL_ORDER = new Comparator<Comparable>() { @Override public int compare(Comparable o1, Comparable o2) { return o1.compareTo(o2); } }; private final NavigableSet<E> delegate; public SafeTreeSet() { this(new TreeSet<E>()); } public SafeTreeSet(Collection<? extends E> collection) { this(new TreeSet<E>(collection)); } public SafeTreeSet(Comparator<? super E> comparator) { this(new TreeSet<E>(comparator)); } public SafeTreeSet(SortedSet<E> set) { this(new TreeSet<E>(set)); } private SafeTreeSet(NavigableSet<E> delegate) { this.delegate = delegate; for (E e : this) { checkValid(e); } } @Override public boolean add(E element) { return delegate.add(checkValid(element)); } @Override public boolean addAll(Collection<? extends E> collection) { for (E e : collection) { checkValid(e); } return delegate.addAll(collection); } @Override public E ceiling(E e) { return delegate.ceiling(checkValid(e)); } @Override public void clear() { delegate.clear(); } @SuppressWarnings("unchecked") @Override public Comparator<? super E> comparator() { Comparator<? super E> comparator = delegate.comparator(); if (comparator == null) { comparator = NATURAL_ORDER; } return comparator; } @Override public boolean contains(Object object) { return delegate.contains(checkValid(object)); } @Override public boolean containsAll(Collection<?> c) { return delegate.containsAll(c); } @Override public Iterator<E> descendingIterator() { return delegate.descendingIterator(); } @Override public NavigableSet<E> descendingSet() { return new SafeTreeSet<E>(delegate.descendingSet()); } @Override public E first() { return delegate.first(); } @Override public E floor(E e) { return delegate.floor(checkValid(e)); } @Override public SortedSet<E> headSet(E toElement) { return headSet(toElement, false); } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { return new SafeTreeSet<E>( delegate.headSet(checkValid(toElement), inclusive)); } @Override public E higher(E e) { return delegate.higher(checkValid(e)); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public Iterator<E> iterator() { return delegate.iterator(); } @Override public E last() { return delegate.last(); } @Override public E lower(E e) { return delegate.lower(checkValid(e)); } @Override public E pollFirst() { return delegate.pollFirst(); } @Override public E pollLast() { return delegate.pollLast(); } @Override public boolean remove(Object object) { return delegate.remove(checkValid(object)); } @Override public boolean removeAll(Collection<?> c) { return delegate.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return delegate.retainAll(c); } @Override public int size() { return delegate.size(); } @Override public NavigableSet<E> subSet( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return new SafeTreeSet<E>( delegate.subSet(checkValid(fromElement), fromInclusive, checkValid(toElement), toInclusive)); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } @Override public SortedSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { return new SafeTreeSet<E>(delegate.tailSet(checkValid(fromElement), inclusive)); } @Override public Object[] toArray() { return delegate.toArray(); } @Override public <T> T[] toArray(T[] a) { return delegate.toArray(a); } private <T> T checkValid(T t) { // a ClassCastException is what's supposed to happen! @SuppressWarnings("unchecked") E e = (E) t; comparator().compare(e, e); return t; } @Override public boolean equals(Object obj) { return delegate.equals(obj); } @Override public int hashCode() { return delegate.hashCode(); } @Override public String toString() { return delegate.toString(); } private static final long serialVersionUID = 0L; }
Java