Java TimeUnit Calculate run(final Runnable runnable, long timeout, TimeUnit unit)

Here you can find the source of run(final Runnable runnable, long timeout, TimeUnit unit)

Description

Executes given Runnable with timeout.

License

Open Source License

Return

true if the finished within the timeout.

Declaration

public static boolean run(final Runnable runnable, long timeout, TimeUnit unit) 

Method Source Code


//package com.java2s;
/*//from   ww w. j a  v  a 2s .c  om
 * Copyright (c) 2014, the Dart project authors.
 * 
 * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

import com.google.common.util.concurrent.Uninterruptibles;
import java.util.concurrent.TimeUnit;

public class Main {
    /**
     * Executes given {@link Runnable} with timeout.
     * 
     * @return {@code true} if the {@link Runnable} finished within the timeout.
     */
    public static boolean run(final Runnable runnable, long timeout, TimeUnit unit) {
        final boolean done[] = { false };
        Thread thread = new Thread("TimeboxUtils.run") {
            @Override
            public void run() {
                runnable.run();
                done[0] = true;
            }
        };
        thread.start();
        Uninterruptibles.joinUninterruptibly(thread, timeout, unit);
        return done[0];
    }
}

Related

  1. parseTimeUnit(Object property, TimeUnit defaultValue)
  2. pause(long duration, TimeUnit unit)
  3. printTime(long time, TimeUnit unit)
  4. randomSleep(int duration, TimeUnit timeUnit)
  5. resetWithClockStep(long clockStep, TimeUnit clockStepUnit)
  6. shortName(TimeUnit unit)
  7. sleep(int duration, TimeUnit unit)
  8. sleep(long duration, TimeUnit timeUnit)
  9. sleep(long duration, TimeUnit timeUnit)