Example usage for java.lang Thread setDaemon

List of usage examples for java.lang Thread setDaemon

Introduction

In this page you can find the example usage for java.lang Thread setDaemon.

Prototype

public final void setDaemon(boolean on) 

Source Link

Document

Marks this thread as either a #isDaemon daemon thread or a user thread.

Usage

From source file:fi.jumi.launcher.remote.ProcessStartingDaemonSummoner.java

private static void copyInBackground(@WillClose InputStream src, @WillClose OutputStream dest) {
    // TODO: after removing me, update also ReleasingResourcesTest
    Thread t = new Thread(() -> {
        try {/*from  w ww.  jav  a2s.  c  om*/
            IOUtils.copy(src, dest);
        } catch (IOException e) {
            throw Boilerplate.rethrow(e);
        } finally {
            IOUtils.closeQuietly(src);
            IOUtils.closeQuietly(dest);
        }
    }, "Daemon Output Copier");
    t.setDaemon(true);
    t.start();
}

From source file:com.ery.estorm.util.Threads.java

/**
 * Get a named {@link ThreadFactory} that just builds daemon threads.
 * /*  ww  w  . java  2 s  . c o  m*/
 * @param prefix
 *            name prefix for all threads created from the factory
 * @param handler
 *            unhandles exception handler to set for all threads
 * @return a thread factory that creates named, daemon threads with the supplied exception handler and normal priority
 */
public static ThreadFactory newDaemonThreadFactory(final String prefix,
        final UncaughtExceptionHandler handler) {
    final ThreadFactory namedFactory = getNamedThreadFactory(prefix);
    return new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = namedFactory.newThread(r);
            if (handler != null) {
                t.setUncaughtExceptionHandler(handler);
            }
            if (!t.isDaemon()) {
                t.setDaemon(true);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }

    };
}

From source file:co.paralleluniverse.fibers.dropwizard.FiberDropwizardTest.java

@BeforeClass
public static void setUpClass() throws InterruptedException, IOException {
    Thread t = new Thread(new Runnable() {

        @Override/*from   w ww .  j  ava 2s.c o m*/
        public void run() {
            try {
                new MyDropwizardApp()
                        .run(new String[] { "server", Resources.getResource("server.yml").getPath() });
            } catch (final Exception ignored) {
            }
        }
    });
    t.setDaemon(true);
    t.start();
    waitUrlAvailable(SERVER_BASE_URL);
}

From source file:com.mindcognition.mindraider.tools.Checker.java

public static void checkAndFixRepositoryAsync() {
    Thread thread = new Thread() {
        public void run() {
            Checker.checkAndFixRepository();
        }//from w  ww  .jav  a 2 s.c  o m
    };
    thread.setDaemon(true);
    thread.start();

}

From source file:com.ariatemplates.seleniumjavarobot.Main.java

private static void closeOnStreamEnd(final SeleniumJavaRobot seleniumJavaRobot, final InputStream inputStream) {
    Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                while (inputStream.read() > -1) {
                    // do nothing
                }//from ww  w.  j a v  a2  s .c  om
            } catch (IOException e) {
            }
            try {
                seleniumJavaRobot.stop();
            } catch (InterruptedException e) {
            }
        }
    });
    thread.setDaemon(true);
    thread.start();
}

From source file:com.joyent.manta.benchmark.Benchmark.java

/**
 * Method used to run a multi-threaded benchmark.
 *
 * @param method to measure/*w w  w .j  a  va2 s  .  c  om*/
 * @param path path to store benchmarking test data
 * @param iterations number of iterations to run
 * @param concurrency number of threads to run
 * @throws IOException thrown when we can't communicate with the server
 */
private static void multithreadedBenchmark(final String method, final String path, final int iterations,
        final int concurrency) throws IOException {
    final AtomicLong fullAggregation = new AtomicLong(0L);
    final AtomicLong serverAggregation = new AtomicLong(0L);
    final AtomicLong count = new AtomicLong(0L);
    final long perThreadCount = perThreadCount(iterations, concurrency);

    System.out.printf("Running %d iterations per thread\n", perThreadCount);

    final long testStart = System.nanoTime();

    Runtime.getRuntime().addShutdownHook(new Thread(Benchmark::cleanUp));

    final Callable<Void> worker = () -> {
        for (int i = 0; i < perThreadCount; i++) {
            Duration[] durations;

            if (method.equals("put")) {
                durations = measurePut(sizeInBytesOrNoOfDirs);
            } else if (method.equals("putDir")) {
                durations = measurePutDir(sizeInBytesOrNoOfDirs);
            } else {
                durations = measureGet(path);
            }

            long fullLatency = durations[0].toMillis();
            long serverLatency = durations[1].toMillis();
            fullAggregation.addAndGet(fullLatency);
            serverAggregation.addAndGet(serverLatency);

            System.out.printf("%s %d full=%dms, server=%dms, thread=%s\n", method, count.getAndIncrement(),
                    fullLatency, serverLatency, Thread.currentThread().getName());
        }

        return null;
    };

    final Thread.UncaughtExceptionHandler handler = (t, e) -> LOG.error("Error when executing benchmark", e);

    final AtomicInteger threadCounter = new AtomicInteger(0);
    ThreadFactory threadFactory = r -> {
        Thread t = new Thread(r);
        t.setDaemon(true);
        t.setUncaughtExceptionHandler(handler);
        t.setName(String.format("benchmark-%d", threadCounter.incrementAndGet()));

        return t;
    };

    ExecutorService executor = Executors.newFixedThreadPool(concurrency, threadFactory);

    List<Callable<Void>> workers = new ArrayList<>(concurrency);
    for (int i = 0; i < concurrency; i++) {
        workers.add(worker);
    }

    try {
        List<Future<Void>> futures = executor.invokeAll(workers);

        boolean completed = false;
        while (!completed) {
            try (Stream<Future<Void>> stream = futures.stream()) {
                completed = stream.allMatch((f) -> f.isDone() || f.isCancelled());

                if (!completed) {
                    Thread.sleep(CHECK_INTERVAL);
                }
            }
        }

    } catch (InterruptedException e) {
        return;
    } finally {
        System.err.println("Shutting down the thread pool");
        executor.shutdown();
    }

    final long testEnd = System.nanoTime();

    final long fullAverage = Math.round(fullAggregation.get() / iterations);
    final long serverAverage = Math.round(serverAggregation.get() / iterations);
    final long totalTime = Duration.ofNanos(testEnd - testStart).toMillis();

    System.out.printf("Average full latency: %d ms\n", fullAverage);
    System.out.printf("Average server latency: %d ms\n", serverAverage);
    System.out.printf("Total test time: %d ms\n", totalTime);
    System.out.printf("Total invocations: %d\n", count.get());
}

From source file:com.excuseme.rocketleaguelivestats.scanner.tailer.Tailer.java

/**
 * Creates and starts a Tailer for the given file.
 *
 * @param file the file to follow.//  w w  w . j  a v a  2s  .  com
 * @param listener the TailerListener to use.
 * @param delayMillis the delay between checks of the file for new content in milliseconds.
 * @param end Set to true to tail from the end of the file, false to tail from the beginning of the file.
 * @param bufSize buffer size.
 * @return The new tailer
 */
public static Tailer create(File file, TailerListener listener, long delayMillis, boolean end, int bufSize) {
    Tailer tailer = new Tailer(file, listener, delayMillis, end, bufSize);
    Thread thread = new Thread(tailer);
    thread.setDaemon(true);
    thread.start();
    return tailer;
}

From source file:com.excuseme.rocketleaguelivestats.scanner.tailer.Tailer.java

/**
 * Creates and starts a Tailer for the given file.
 *
 * @param file the file to follow.//from www .j a  v  a 2 s  . c om
 * @param listener the TailerListener to use.
 * @param delayMillis the delay between checks of the file for new content in milliseconds.
 * @param end Set to true to tail from the end of the file, false to tail from the beginning of the file.
 * @param reOpen whether to close/reopen the file between chunks
 * @param bufSize buffer size.
 * @return The new tailer
 */
public static Tailer create(File file, TailerListener listener, long delayMillis, boolean end, boolean reOpen,
        int bufSize) {
    Tailer tailer = new Tailer(file, listener, delayMillis, end, reOpen, bufSize);
    Thread thread = new Thread(tailer);
    thread.setDaemon(true);
    thread.start();
    return tailer;
}

From source file:com.vuze.android.remote.rpc.RestJsonClient.java

private static void closeOnNewThread(final Reader reader) {
    Thread thread = new Thread(new Runnable() {
        @Override//  w w w . j a  va2s .  com
        public void run() {
            try {
                reader.close();
            } catch (Throwable ignore) {
            }
        }
    }, "closeInputStream");
    thread.setDaemon(true);
    thread.start();
}

From source file:com.asakusafw.runtime.util.hadoop.ConfigurationProvider.java

private static Thread redirect(InputStream in, OutputStream out) {
    Thread t = new Thread(new StreamRedirectTask(in, out));
    t.setDaemon(true);
    t.start();/*ww  w. ja va 2s. co m*/
    return t;
}