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:ext.services.network.TestNetworkUtils.java

/**
 * Test get connection url proxy with proxy.
 * /*from   w  ww .j  a  v a  2 s  .  c o  m*/
 *
 * @throws Exception the exception
 */
public void testGetConnectionURLProxyWithProxy() throws Exception {
    final ServerSocket socket = new ServerSocket(PROXY_PORT);
    Thread thread = new Thread("ProxySocketAcceptThread") {
        @Override
        public void run() {
            try {
                while (!bStop) {
                    Socket sock = socket.accept();
                    Log.debug("Accepted connection, sending back garbage and close socket...");
                    sock.getOutputStream().write(1);
                    sock.close();
                }
            } catch (IOException e) {
                Log.error(e);
            }
        }
    };
    thread.setDaemon(true); // to finish tests even if this is still running
    thread.start();
    Log.debug("Using local port: " + socket.getLocalPort());
    try {
        // useful content when inet access is allowed
        Conf.setProperty(Const.CONF_NETWORK_NONE_INTERNET_ACCESS, "false");
        HttpURLConnection connection = NetworkUtils.getConnection(new java.net.URL(URL),
                new Proxy(Type.SOCKS, "localhost", socket.getLocalPort(), "user", "password"));
        assertNotNull(connection);
        connection.disconnect();
    } finally {
        bStop = true;
        socket.close();
        thread.join();
    }
}

From source file:io.warp10.quasar.trl.QuasarTokenRevocationListLoader.java

public void init() {
    // initialize only once per JVM
    if (initialized.get()) {
        return;//w w w .  ja  v a 2 s. co m
    }

    Thread t = new Thread() {

        @Override
        public void run() {
            while (true) {
                loadTrl();
                // time to sleep
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException ie) {
                }
            } // while(true)
        } // run()
    };

    if (null != path && initialized.compareAndSet(false, true)) {
        t.setName("[TokenRevocationListLoader]");
        t.setDaemon(true);
        t.start();
    }
}

From source file:com.cti.vpx.listener.VPXTFTPMonitor.java

public void run() {

    try {/*from  ww w  .j  a v a 2  s  . c  om*/

        while (!shutdownServer) {

            TFTPPacket tftpPacket;

            tftpPacket = serverTftp_.receive();

            TFTPTransfer tt = new TFTPTransfer(tftpPacket);

            synchronized (transfers_) {
                transfers_.add(tt);
            }

            Thread thread = new Thread(tt);

            thread.setDaemon(true);

            thread.start();

        }

    } catch (Exception e) {

        if (!shutdownServer) {

            serverException = e;
            logError_.println("Unexpected Error in TFTP Server - Server shut down! + " + e);

        }

    } finally {

        shutdownServer = true; // set this to true, so the launching thread
        // can check to see if it started.
        if (serverTftp_ != null && serverTftp_.isOpen()) {

            serverTftp_.close();
        }
    }
}

From source file:org.hawkular.apm.tests.common.ApmMockServer.java

public void run() {
    log.info("************** STARTED TEST MOCK SERVICE: host=" + host + " port=" + port + " shutdownTimer="
            + shutdown);// w ww.  j  av a2  s  .  com

    if (shutdown != -1) {
        // Create shutdown thread, just in case hangs
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (this) {
                    try {
                        wait(shutdown);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                log.severe("************** ABORTING TEST MOCK SERVICE");
                System.exit(1);
            }
        });
        t.setDaemon(true);
        t.start();
    }

    server = Undertow.builder().addHttpListener(port, host)
            .setHandler(path().addPrefixPath("hawkular/apm/shutdown", new HttpHandler() {
                @Override
                public void handleRequest(final HttpServerExchange exchange) throws Exception {
                    log.info("Shutdown called");

                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
                    exchange.getResponseSender().send("ok");
                    shutdown();
                }
            }).addPrefixPath("hawkular/apm/traces/fragments", new HttpHandler() {
                @Override
                public void handleRequest(final HttpServerExchange exchange) throws Exception {
                    if (exchange.isInIoThread()) {
                        exchange.dispatch(this);
                        return;
                    }

                    log.info("Transactions request received: " + exchange);

                    if (exchange.getRequestMethod() == Methods.POST) {
                        exchange.startBlocking();

                        String body = getBody(exchange.getInputStream());
                        List<Trace> btxns = mapper.readValue(body, TRACE_LIST);

                        synchronized (traces) {
                            traces.addAll(btxns);
                        }

                        exchange.setResponseCode(204);
                    } else if (exchange.getRequestMethod() == Methods.GET) {
                        // TODO: Currently returns all - support proper query
                        synchronized (traces) {
                            String btxns = mapper.writeValueAsString(traces);
                            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
                            exchange.getResponseSender().send(btxns);
                        }
                    }
                }
            }).addPrefixPath("hawkular/apm/config/collector", new HttpHandler() {
                @Override
                public void handleRequest(final HttpServerExchange exchange) throws Exception {
                    if (exchange.isInIoThread()) {
                        exchange.dispatch(this);
                        return;
                    }

                    log.info("Config request received: " + exchange);

                    if (exchange.getRequestMethod() == Methods.GET) {
                        CollectorConfiguration config = ConfigurationLoader.getConfiguration(null);

                        if (testConfig != null) {
                            config.merge(testConfig, true);
                        }

                        String cc = mapper.writeValueAsString(config);
                        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
                        exchange.getResponseSender().send(cc);
                    }
                }
            }).addPrefixPath("v1/spans", new HttpHandler() {
                @Override
                public void handleRequest(HttpServerExchange exchange) throws Exception {
                    if (exchange.isInIoThread()) {
                        exchange.dispatch(this);
                        return;
                    }

                    log.info("Zipkin spans request received: " + exchange);

                    if (exchange.getRequestMethod() == Methods.POST) {
                        exchange.startBlocking();

                        String body = getBody(exchange.getInputStream());
                        List<Span> spans = mapper.readValue(body, SPAN_LIST);

                        synchronized (zipkinSpans) {
                            zipkinSpans.addAll(spans);
                        }

                        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
                        exchange.getResponseSender().send("");
                    } else if (exchange.getRequestMethod() == Methods.GET) {
                        synchronized (zipkinSpans) {
                            String zipkinSpansStr = mapper.writeValueAsString(zipkinSpans);
                            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
                            exchange.getResponseSender().send(zipkinSpansStr);
                        }
                    }
                }
            })).build();
    server.start();
}

From source file:NanoHTTPD.java

/**
 * Starts a HTTP server to given port./* ww  w.  j a  v  a 2s  . co  m*/
 * <p>
 * Throws an IOException if the socket is already in use
 */
public NanoHTTPD(int port) throws IOException {
    myTcpPort = port;

    final ServerSocket ss = new ServerSocket(myTcpPort);
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                while (true)
                    new HTTPSession(ss.accept());
            } catch (IOException ioe) {
            }
        }
    });
    t.setDaemon(true);
    t.start();
}

From source file:co.cask.cdap.internal.app.runtime.spark.SparkRuntimeService.java

@Override
protected Executor executor() {
    // Always execute in new daemon thread.
    return new Executor() {
        @Override//w w  w  . j av  a  2  s .c o m
        public void execute(final Runnable runnable) {
            final Thread t = new Thread(new Runnable() {

                @Override
                public void run() {
                    // note: this sets logging context on the thread level
                    LoggingContextAccessor.setLoggingContext(context.getLoggingContext());
                    runnable.run();
                }
            });
            t.setDaemon(true);
            t.setName(getServiceName());
            t.start();
        }
    };
}

From source file:com.projity.job.Job.java

private void runThread(final InternalRunnable runnable, final JobMutex runMutex) {
    if (runnable.isCreateThread()) {
        Thread t = new Thread() {
            public void run() {
                runSwing(runnable, runMutex);
            }/*  w w w. java  2s . co  m*/
        };
        t.setDaemon(isDaemon());
        t.start();
    } else {
        runSwing(runnable, runMutex);
    }
}

From source file:editeurpanovisu.EquiCubeDialogController.java

/**
 *
 *//*w  w  w  .  j a  va  2 s .  c o m*/
private void validerE2C() {
    if (fileLstFichier == null) {
        Alert alert = new Alert(AlertType.ERROR);
        alert.setTitle(rbLocalisation.getString("transformation.traiteImages"));
        alert.setHeaderText(null);
        alert.setContentText(rbLocalisation.getString("transformation.traiteImagesPasFichiers"));
        alert.showAndWait();
    } else {
        Alert alert = new Alert(AlertType.WARNING);
        alert.setTitle(rbLocalisation.getString("transformation.traiteImages"));
        alert.setHeaderText(null);
        alert.setContentText(rbLocalisation.getString("transformation.traiteImagesMessage"));
        alert.showAndWait();

        lblTermine = new Label();
        lblTermine.setText("Traitement en cours");
        lblTermine.setLayoutX(24);
        lblTermine.setLayoutY(250);
        paneChoixTypeFichier.getChildren().add(lblTermine);
        pbBarreAvancement.setId("bar");
        lblTermine.setId("lblTermine");
        pbBarreAvancement.setVisible(true);
        pbBarreImage.setVisible(true);
        Task taskTraitement;
        taskTraitement = tskTraitement();
        pbBarreAvancement.progressProperty().unbind();
        pbBarreImage.setProgress(0.001);
        pbBarreAvancement.setProgress(0.001);
        pbBarreAvancement.progressProperty().bind(taskTraitement.progressProperty());
        lblTermine.textProperty().unbind();
        lblTermine.textProperty().bind(taskTraitement.messageProperty());
        Thread thrTraitement = new Thread(taskTraitement);
        thrTraitement.setDaemon(true);
        thrTraitement.start();
    }
}

From source file:com.runwaysdk.dataaccess.database.general.ProcessReader.java

/**
 * Consumes the output of the process in a separate thread.
 * /*  w  w  w. j a v  a2s . c o  m*/
 * @param inputStream
 * @param stream
 */
private void consumeOutput(final InputStream inputStream, final PrintStream stream) {
    final BufferedReader out = new BufferedReader(new InputStreamReader(inputStream));

    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                String line = new String();

                while ((line = out.readLine()) != null) {
                    stream.println(line);
                }

                stream.close();
            } catch (Throwable t) {
                String msg = "Error when consuming the process output.";
                throw new ProgrammingErrorException(msg, t);
            }
        }
    }, OUTPUT_THREAD);

    t.setUncaughtExceptionHandler(this);
    t.setDaemon(true);
    t.start();
}

From source file:com.foilen.smalltools.spring.resourceresolver.BundleResourceResolver.java

/**
 * If you are using cache, a thread will run now to prepare all the bundles that are already defined.
 *
 * @return this//from w w  w  .ja va  2s .co m
 */
public BundleResourceResolver primeCache() {
    if (cachedResources == null) {
        logger.warn("You are requesting to prime the cache now, but the caching is not enabled");
    }

    Thread thread = new Thread(() -> {
        ThreadTools.nameThread().clear().appendText("Prime the cache - Started at - ").appendDate().change();
        logger.info("[BEGIN] Prime the cache");

        for (String bundleName : resourcesByBundleName.keySet()) {
            try {
                logger.info("Priming {}", bundleName);
                cachedResources.get(bundleName);
            } catch (ExecutionException e) {
                logger.error("Got an error while priming {}", bundleName);
            }
        }

        logger.info("[END] Prime the cache");
    });
    thread.setDaemon(true);
    thread.start();

    return this;
}