Example usage for java.util.concurrent TimeUnit SECONDS

List of usage examples for java.util.concurrent TimeUnit SECONDS

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit SECONDS.

Prototype

TimeUnit SECONDS

To view the source code for java.util.concurrent TimeUnit SECONDS.

Click Source Link

Document

Time unit representing one second.

Usage

From source file:Main.java

/**
 * Creates a fixed priority thread pool.
 *///from  w  w  w .ja va2 s  . c o  m
public static ExecutorService newPriorityThreadPool(String name, int numThreads) {
    return new ThreadPoolExecutor(numThreads, numThreads, 1, TimeUnit.SECONDS,
            new PriorityBlockingQueue<Runnable>(numThreads), newNamedThreadFactory(name));
}

From source file:Main.java

/**
 * Properly shutdown and await pool termination for an arbitrary
 * amount of time./*www  . j av  a  2s  .  com*/
 *
 * @param pool        Pool to shutdown
 * @param waitSeconds Seconds to wait before throwing exception
 * @throws java.util.concurrent.TimeoutException Thrown if the pool does not shutdown in the specified time
 */
public static void shutdownAndWaitForTermination(ExecutorService pool, int waitSeconds)
        throws TimeoutException {
    // shut it down
    pool.shutdown();
    try {
        // wait, wait, wait
        if (!pool.awaitTermination(waitSeconds, TimeUnit.SECONDS)) {
            // things still running, nuke it
            pool.shutdownNow();
            // wait, wait, wai
            if (!pool.awaitTermination(waitSeconds, TimeUnit.SECONDS)) {
                // boo hiss, didn't shutdown
                throw new TimeoutException("Pool did not terminate");
            }
        }
    } catch (InterruptedException ie) {
        // try, try again
        pool.shutdownNow();
        Thread.currentThread().interrupt();
    }
}

From source file:example.springdata.cassandra.util.CassandraSocket.java

/**
 * @param host must not be {@literal null} or empty.
 * @param port/*from  w w w  .  java 2s.  co m*/
 * @return {@literal true} if the TCP port accepts a connection.
 */
public static boolean isConnectable(String host, int port) {

    Assert.hasText(host, "Host must not be null or empty!");

    try (Socket socket = new Socket()) {

        socket.setSoLinger(true, 0);
        socket.connect(new InetSocketAddress(host, port),
                (int) TimeUnit.MILLISECONDS.convert(10, TimeUnit.SECONDS));

        return true;

    } catch (Exception e) {
        return false;
    }
}

From source file:Main.java

public void runTest() throws Exception {
    ThreadPoolExecutor tp = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>());
    tp.setRejectedExecutionHandler(/*from   w  ww.  j a va2s. c o  m*/
            (Runnable r, ThreadPoolExecutor executor) -> System.out.println("Task rejected: " + r));
    Semaphore oneTaskDone = new Semaphore(0);
    tp.execute(() -> {
        System.out.println("Sleeping");
        try {
            Thread.sleep(300);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Done sleeping");
        oneTaskDone.release();
    });
    tp.execute(new Runnable() {
        @Override
        public void run() {
            System.out.println("Never happends");
        }

        @Override
        public String toString() {
            return "Rejected Runnable";
        }
    });
    oneTaskDone.acquire();
    tp.execute(() -> System.out.println("Running"));
    tp.shutdown();
    tp.awaitTermination(100, TimeUnit.MILLISECONDS);
    System.out.println("Finished");
}

From source file:com.shazam.fork.system.adb.SpoonUtils.java

private static void waitForAdb(AndroidDebugBridge adb) {
    long timeOutMs = TimeUnit.SECONDS.toMillis(30);
    long sleepTimeMs = TimeUnit.SECONDS.toMillis(1);
    while (!adb.hasInitialDeviceList() && timeOutMs > 0) {
        try {//from w  ww .  j a v a 2 s .c om
            Thread.sleep(sleepTimeMs);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        timeOutMs -= sleepTimeMs;
    }
    if (timeOutMs <= 0 && !adb.hasInitialDeviceList()) {
        throw new RuntimeException("Timeout getting device list.", null);
    }
}

From source file:Main.java

/**
 * Similar to {@link #newCoalescingThreadPool(String)}, but always runs the
 * last runnable put into the pool. If runnable a is executed, and then
 * runnables b and c are executed while a is still running, runnable b will
 * be dropped and c will executed./*from  w w  w.  j  ava2 s. c o  m*/
 */
public static ExecutorService newLastRequestThreadPool(String name) {
    return new ThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>() {
        @Override
        public boolean offer(Runnable e) {
            clear();
            return super.offer(e);
        }
    }, newNamedThreadFactory(name));
}

From source file:Main.java

public void startRandomMover() {
    executor.scheduleAtFixedRate(new Runnable() {
        public void run() {
            moveNow();//from   w w w.  j av  a 2  s .  co  m
        }
    }, 0, 1, TimeUnit.SECONDS);
}

From source file:Main.java

public static ThreadPoolExecutor newLimitedThreadPool(int minNumberOfThreads, int maxNumberOfThreads,
        long defaultRemoveIdleThread, int bufferSize) {
    return new ThreadPoolExecutor(minNumberOfThreads, maxNumberOfThreads, defaultRemoveIdleThread,
            TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(bufferSize));
}

From source file:com.amazonaws.http.HttpRequestTimer.java

private static ScheduledThreadPoolExecutor createExecutor() {
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5);
    safeSetRemoveOnCancel(executor);//from   w w w.j  a  v a 2  s.  c o m
    executor.setKeepAliveTime(5, TimeUnit.SECONDS);
    executor.allowCoreThreadTimeOut(true);
    return executor;
}

From source file:com.appstarter.utils.WebUtils.java

public static String doHttpGet(String url) throws AppStarterException {
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "doHttpGet - url: " + url);
    }//from   ww w .j a  va 2s  . co  m

    String ret = "";

    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout
    client.setReadTimeout(15, TimeUnit.SECONDS); // socket timeout

    try {
        Request request = new Request.Builder().url(new URL(url))
                //               .header("User-Agent", "OkHttp Headers.java")
                //               .addHeader("Accept", "application/json; q=0.5")
                .build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            String debugMessage = "doHttpGet - OkHttp.Response is not successful - " + response.message() + " ("
                    + response.code() + ")";
            throw new AppStarterException(AppStarterException.ERROR_SERVER, debugMessage);
        }
        ret = response.body().string();
    } catch (IOException e) {
        throw new AppStarterException(e, AppStarterException.ERROR_NETWORK_GET);
    }

    return ret;
}