Search in sources :

Example 16 with TimeUnit

use of java.util.concurrent.TimeUnit in project Store by NYTimes.

the class Stopwatch method toString.

/**
     * Returns a string representation of the current elapsed time.
     */
@Override
public String toString() {
    long nanos = elapsedNanos();
    TimeUnit unit = chooseUnit(nanos);
    double value = (double) nanos / NANOSECONDS.convert(1, unit);
    // Too bad this functionality is not exposed as a regular method call
    return String.format(Locale.ROOT, "%.4g %s", value, abbreviate(unit));
}
Also used : TimeUnit(java.util.concurrent.TimeUnit)

Example 17 with TimeUnit

use of java.util.concurrent.TimeUnit in project Hystrix by Netflix.

the class HystrixCommand method queue.

/**
     * Used for asynchronous execution of command.
     * <p>
     * This will queue up the command on the thread pool and return an {@link Future} to get the result once it completes.
     * <p>
     * NOTE: If configured to not run in a separate thread, this will have the same effect as {@link #execute()} and will block.
     * <p>
     * We don't throw an exception but just flip to synchronous execution so code doesn't need to change in order to switch a command from running on a separate thread to the calling thread.
     * 
     * @return {@code Future<R>} Result of {@link #run()} execution or a fallback from {@link #getFallback()} if the command fails for any reason.
     * @throws HystrixRuntimeException
     *             if a fallback does not exist
     *             <p>
     *             <ul>
     *             <li>via {@code Future.get()} in {@link ExecutionException#getCause()} if a failure occurs</li>
     *             <li>or immediately if the command can not be queued (such as short-circuited, thread-pool/semaphore rejected)</li>
     *             </ul>
     * @throws HystrixBadRequestException
     *             via {@code Future.get()} in {@link ExecutionException#getCause()} if invalid arguments or state were used representing a user failure, not a system failure
     * @throws IllegalStateException
     *             if invoked more than once
     */
public Future<R> queue() {
    /*
         * The Future returned by Observable.toBlocking().toFuture() does not implement the
         * interruption of the execution thread when the "mayInterrupt" flag of Future.cancel(boolean) is set to true;
         * thus, to comply with the contract of Future, we must wrap around it.
         */
    final Future<R> delegate = toObservable().toBlocking().toFuture();
    final Future<R> f = new Future<R>() {

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            if (delegate.isCancelled()) {
                return false;
            }
            if (HystrixCommand.this.getProperties().executionIsolationThreadInterruptOnFutureCancel().get()) {
                /*
                     * The only valid transition here is false -> true. If there are two futures, say f1 and f2, created by this command
                     * (which is super-weird, but has never been prohibited), and calls to f1.cancel(true) and to f2.cancel(false) are
                     * issued by different threads, it's unclear about what value would be used by the time mayInterruptOnCancel is checked.
                     * The most consistent way to deal with this scenario is to say that if *any* cancellation is invoked with interruption,
                     * than that interruption request cannot be taken back.
                     */
                interruptOnFutureCancel.compareAndSet(false, mayInterruptIfRunning);
            }
            final boolean res = delegate.cancel(interruptOnFutureCancel.get());
            if (!isExecutionComplete() && interruptOnFutureCancel.get()) {
                final Thread t = executionThread.get();
                if (t != null && !t.equals(Thread.currentThread())) {
                    t.interrupt();
                }
            }
            return res;
        }

        @Override
        public boolean isCancelled() {
            return delegate.isCancelled();
        }

        @Override
        public boolean isDone() {
            return delegate.isDone();
        }

        @Override
        public R get() throws InterruptedException, ExecutionException {
            return delegate.get();
        }

        @Override
        public R get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
            return delegate.get(timeout, unit);
        }
    };
    /* special handling of error states that throw immediately */
    if (f.isDone()) {
        try {
            f.get();
            return f;
        } catch (Exception e) {
            Throwable t = decomposeException(e);
            if (t instanceof HystrixBadRequestException) {
                return f;
            } else if (t instanceof HystrixRuntimeException) {
                HystrixRuntimeException hre = (HystrixRuntimeException) t;
                switch(hre.getFailureType()) {
                    case COMMAND_EXCEPTION:
                    case TIMEOUT:
                        // we don't throw these types from queue() only from queue().get() as they are execution errors
                        return f;
                    default:
                        // these are errors we throw from queue() as they as rejection type errors
                        throw hre;
                }
            } else {
                throw Exceptions.sneakyThrow(t);
            }
        }
    }
    return f;
}
Also used : HystrixBadRequestException(com.netflix.hystrix.exception.HystrixBadRequestException) Future(java.util.concurrent.Future) TimeUnit(java.util.concurrent.TimeUnit) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) TimeoutException(java.util.concurrent.TimeoutException) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) ExecutionException(java.util.concurrent.ExecutionException) HystrixBadRequestException(com.netflix.hystrix.exception.HystrixBadRequestException)

Example 18 with TimeUnit

use of java.util.concurrent.TimeUnit in project SimianArmy by Netflix.

the class BasicSimianArmyContext method createScheduler.

private void createScheduler() {
    int freq = (int) config.getNumOrElse("simianarmy.scheduler.frequency", 1);
    TimeUnit freqUnit = TimeUnit.valueOf(config.getStrOrElse("simianarmy.scheduler.frequencyUnit", "HOURS"));
    int threads = (int) config.getNumOrElse("simianarmy.scheduler.threads", MONKEY_THREADS);
    setScheduler(new BasicScheduler(freq, freqUnit, threads));
}
Also used : TimeUnit(java.util.concurrent.TimeUnit)

Example 19 with TimeUnit

use of java.util.concurrent.TimeUnit in project ribbon by Netflix.

the class DefaultClientConfigImpl method putDefaultTimeUnitProperty.

protected void putDefaultTimeUnitProperty(IClientConfigKey propName, TimeUnit defaultValue) {
    TimeUnit value = defaultValue;
    String propValue = ConfigurationManager.getConfigInstance().getString(getDefaultPropName(propName));
    if (propValue != null && propValue.length() > 0) {
        value = TimeUnit.valueOf(propValue);
    }
    setPropertyInternal(propName, value);
}
Also used : TimeUnit(java.util.concurrent.TimeUnit)

Example 20 with TimeUnit

use of java.util.concurrent.TimeUnit in project dubbo by alibaba.

the class RpcContext method asyncCall.

/**
     * 异步调用 ,需要返回值,即使步调用Future.get方法,也会处理调用超时问题.
     * @param callable
     * @return 通过future.get()获取返回结果.
     */
@SuppressWarnings("unchecked")
public <T> Future<T> asyncCall(Callable<T> callable) {
    try {
        try {
            setAttachment(Constants.ASYNC_KEY, Boolean.TRUE.toString());
            final T o = callable.call();
            //local调用会直接返回结果.
            if (o != null) {
                FutureTask<T> f = new FutureTask<T>(new Callable<T>() {

                    public T call() throws Exception {
                        return o;
                    }
                });
                f.run();
                return f;
            } else {
            }
        } catch (Exception e) {
            throw new RpcException(e);
        } finally {
            removeAttachment(Constants.ASYNC_KEY);
        }
    } catch (final RpcException e) {
        return new Future<T>() {

            public boolean cancel(boolean mayInterruptIfRunning) {
                return false;
            }

            public boolean isCancelled() {
                return false;
            }

            public boolean isDone() {
                return true;
            }

            public T get() throws InterruptedException, ExecutionException {
                throw new ExecutionException(e.getCause());
            }

            public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
                return get();
            }
        };
    }
    return ((Future<T>) getContext().getFuture());
}
Also used : TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) FutureTask(java.util.concurrent.FutureTask) TimeUnit(java.util.concurrent.TimeUnit) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

TimeUnit (java.util.concurrent.TimeUnit)190 Test (org.junit.Test)28 ExecutionException (java.util.concurrent.ExecutionException)16 IOException (java.io.IOException)11 TimeoutException (java.util.concurrent.TimeoutException)11 Future (java.util.concurrent.Future)10 HashMap (java.util.HashMap)7 TimeSpec (com.linkedin.thirdeye.api.TimeSpec)6 ArrayList (java.util.ArrayList)6 TimeValue (org.elasticsearch.common.unit.TimeValue)6 DataType (com.linkedin.pinot.common.data.FieldSpec.DataType)5 File (java.io.File)5 HashSet (java.util.HashSet)5 Matcher (java.util.regex.Matcher)5 WaitUntilGatewaySenderFlushedCoordinatorJUnitTest (org.apache.geode.internal.cache.wan.WaitUntilGatewaySenderFlushedCoordinatorJUnitTest)5 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)5 TimeGranularity (com.linkedin.thirdeye.api.TimeGranularity)4 GwtIncompatible (com.google.common.annotations.GwtIncompatible)3 RestException (com.linkedin.r2.message.rest.RestException)3 Map (java.util.Map)3