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:com.baifendian.swordfish.execserver.ExecThriftServer.java

/**
 * @throws UnknownHostException//from  w  w w.j a va2  s. c o m
 * @throws TTransportException
 */
public void run() throws UnknownHostException, TTransportException, InterruptedException {
    HdfsClient.init(ConfigurationUtil.getConfiguration());

    logger.info("register to master {}:{}", masterServer.getHost(), masterServer.getPort());

    //  master
    boolean ret = masterClient.registerExecutor(host, port, System.currentTimeMillis());
    if (!ret) {
        // ?, ?
        Thread.sleep(3000);

        ret = masterClient.registerExecutor(host, port, System.currentTimeMillis());

        if (!ret) {
            logger.error("register to master {}:{} failed", masterServer.getHost(), masterServer.getPort());
            throw new RuntimeException("register executor error");
        }
    }

    // 
    heartBeatInterval = conf.getInt(Constants.EXECUTOR_HEARTBEAT_INTERVAL,
            Constants.defaultExecutorHeartbeatInterval);

    heartbeatExecutorService = Executors.newScheduledThreadPool(Constants.defaultExecutorHeartbeatThreadNum);

    Runnable heartBeatThread = getHeartBeatThread();
    heartbeatExecutorService.scheduleAtFixedRate(heartBeatThread, 10, heartBeatInterval, TimeUnit.SECONDS);

    // ? worker service
    TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();
    TTransportFactory tTransportFactory = new TTransportFactory();

    workerService = new ExecServiceImpl(host, port, conf);

    TProcessor tProcessor = new WorkerService.Processor(workerService);
    inetSocketAddress = new InetSocketAddress(host, port);
    server = getTThreadPoolServer(protocolFactory, tProcessor, tTransportFactory, inetSocketAddress,
            Constants.defaultServerMinNum, Constants.defaultServerMaxNum);

    logger.info("start thrift server on port:{}", port);

    //  daemon, ??
    Thread serverThread = new TServerThread(server);
    serverThread.setDaemon(true);
    serverThread.start();

    // ?, ??
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        postProcess();

        logger.info("exec server stop");
    }));

    synchronized (this) {
        // 
        while (running.get()) {
            try {
                logger.info("wait....................");
                wait();
            } catch (InterruptedException e) {
                logger.error("error", e);
            }
        }

        postProcess();

        logger.info("exec server stop");
    }
}

From source file:net.pms.util.BasicThreadFactory.java

@Override
public Thread newThread(Runnable runnable) {
    String threadName;/*from   www .ja v  a  2 s  .  c o m*/
    switch (numVariables) {
    case 0:
        threadName = namePattern;
        break;
    case 1:
        threadName = String.format(Locale.ROOT, namePattern, threadNumber.getAndIncrement());
        break;
    default:
        threadName = String.format(Locale.ROOT, namePattern, instancePoolNumber,
                threadNumber.getAndIncrement());
    }
    Thread thread = new Thread(group, runnable, threadName, 0);
    if (thread.isDaemon()) {
        thread.setDaemon(false);
    }
    if (thread.getPriority() != threadPriority) {
        thread.setPriority(threadPriority);
    }
    return thread;
}

From source file:functionaltests.matlab.AbstractMatlabTest.java

protected void runCommand(String testName, int nb_iter) throws Exception {

    ProcessBuilder pb = initCommand(testName, nb_iter);
    System.out.println("Running command : " + pb.command());

    File okFile = new File(mat_tb_home + fs + "ok.tst");
    File koFile = new File(mat_tb_home + fs + "ko.tst");
    File startFile = new File(mat_tb_home + fs + "start.tst");

    if (okFile.exists()) {
        okFile.delete();//from w  w  w  .  j  a v a2 s.  c o  m
    }

    if (koFile.exists()) {
        koFile.delete();
    }
    if (startFile.exists()) {
        startFile.delete();
    }

    Process p = pb.start();

    IOTools.LoggingThread lt1 = new IOTools.LoggingThread(p.getInputStream(), "[" + testName + "]", System.out);
    Thread t1 = new Thread(lt1, testName);
    t1.setDaemon(true);
    t1.start();

    p.waitFor();
    // sometimes a matlab laucher is used and it returns immediately, the waitFor will not be of use and we need to wait
    // for files to be created
    while (!startFile.exists()) {
        Thread.sleep(100);
    }

    while (!okFile.exists() && !koFile.exists()) {
        Thread.sleep(100);
    }

    if (logFile.exists()) {
        System.out.println(IOUtils.toString(logFile.toURI()));
    }

    assertTrue(testName + " passed", okFile.exists());
}

From source file:calendarioSeries.vistas.NewSerieController.java

@FXML
public void handleOk() {
    String tituloAux = titulo.getText().replaceAll(" ", "+").toLowerCase();
    String toJson = readUrl(BASE + tituloAux + "&type=series" + "&r=json");
    resultados.getChildren().clear();//from ww  w.java  2  s.c  om
    try {
        JSONObject busqueda = new JSONObject(toJson);
        if (busqueda.getString("Response").equals("True")) {
            JSONArray res = busqueda.getJSONArray("Search");
            resultados.setPrefRows(res.length());
            for (int i = 0; i < res.length(); i++) {
                JSONObject resActual = new JSONObject(res.get(i).toString());
                HBox resultadoActual = new HBox(50);
                resultadoActual.setMaxWidth(Double.MAX_VALUE);
                resultadoActual.setAlignment(Pos.CENTER_LEFT);
                ImageView posterActual = new ImageView();

                try {
                    Image image = new Image(resActual.getString("Poster"));
                    posterActual.setImage(image);
                    posterActual.setFitHeight(240);
                    posterActual.setFitWidth(180);
                    posterActual.setPreserveRatio(false);
                    resultadoActual.getChildren().add(posterActual);
                } catch (IllegalArgumentException e) {
                    //                        System.out.println("Bad url");
                    Image image = new Image(
                            MainApp.class.getResource("resources/no-image.png").toExternalForm());
                    posterActual.setImage(image);
                    posterActual.setFitHeight(240);
                    posterActual.setFitWidth(180);
                    posterActual.setPreserveRatio(false);
                    resultadoActual.getChildren().add(posterActual);
                }

                String details;
                String nomSerie = new String(resActual.getString("Title").getBytes(), "UTF-8");
                String anoSerie = new String(resActual.getString("Year").getBytes(), "UTF-8");
                if (nomSerie.length() > 15) {
                    details = "%-12.12s...\t\t Ao: %-10s";
                } else {
                    details = "%-12s\t\t Ao: %-10s";
                }
                details = String.format(details, nomSerie, anoSerie);
                Label elemento = new Label(details);
                elemento.setMaxWidth(Double.MAX_VALUE);
                elemento.setMaxHeight(Double.MAX_VALUE);
                resultadoActual.getChildren().add(elemento);

                posterActual.setId(resActual.getString("imdbID"));
                posterActual.setOnMouseClicked(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        ImageView clickedButton = (ImageView) event.getSource();
                        Stage stage = (Stage) clickedButton.getScene().getWindow();
                        Task task = new Task() {
                            @Override
                            protected Object call() throws Exception {
                                mainController.mainApp.scene.setCursor(Cursor.WAIT);
                                Serie toAdd = new Serie(clickedButton.getId());
                                boolean possible = true;
                                for (Serie serie : mainController.getSeries()) {
                                    if (serie.equals(toAdd))
                                        possible = false;
                                }
                                if (possible)
                                    mainController.getSeries().add(toAdd);

                                try {
                                    mainController.populateImagenes();
                                    mainController.showDetallesMes(mainController.getMesActual());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                } finally {
                                    mainController.mainApp.scene.setCursor(Cursor.DEFAULT);

                                    return mainController.getSeries();
                                }
                            }
                        };
                        Thread th = new Thread(task);
                        th.setDaemon(true);
                        th.start();
                        stage.close();
                    }
                });
                resultados.getChildren().add(resultadoActual);
            }
        } else {
            resultados.getChildren().add(new Label("La busqueda no obtuvo resultados"));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(NewSerieController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:de.ufinke.cubaja.sort.SortManager.java

private ThreadFactory createThreadFactory() {

    return new ThreadFactory() {

        public Thread newThread(Runnable r) {

            Thread thread = new Thread(r);
            thread.setDaemon(true);
            return thread;
        }//from  w ww  .  j  ava  2 s  . com
    };
}

From source file:com.example.gridtest.MyPumpStreamHandler.java

/**
 * Creates a stream pumper to copy the given input stream to the given
 * output stream./*from  www. j  a  v  a  2 s .  c  om*/
 *
 * @param is the System.in input stream to copy from
 * @param os the output stream to copy into
 * @return the stream pumper thread
 */
private Thread createSystemInPump(InputStream is, OutputStream os) {
    inputStreamPumper = new InputStreamPumper(is, os);
    final Thread result = new Thread(inputStreamPumper);
    result.setDaemon(true);
    return result;
}

From source file:com.haulmont.cuba.core.app.scheduling.RunnerBean.java

@PostConstruct
public void init() {
    int nThreads = configuration.getConfig(ServerConfig.class).getSchedulingThreadPoolSize();
    executorService = Executors.newFixedThreadPool(nThreads, new ThreadFactory() {
        private final AtomicInteger threadNumber = new AtomicInteger(1);

        @Override/* w w w  .  j av  a 2 s .c om*/
        public Thread newThread(@Nonnull Runnable r) {
            Thread thread = new Thread(r, "ScheduledRunnerThread-" + threadNumber.getAndIncrement());
            thread.setDaemon(true);
            return thread;
        }
    });
}

From source file:immf.SendMailPicker.java

public SendMailPicker(Config conf, ServerMain server, ImodeNetClient client, StatusManager status) {
    this.conf = conf;
    this.server = server;
    this.client = client;
    this.status = status;
    this.forcePlainText = conf.isSenderMailForcePlainText();
    this.isForwardSent = conf.isForwardSent();

    if (true) {//from  w w w  .j a v  a 2 s  .  c  o m
        Thread t = new Thread(this);
        t.setName("SendMailPicker");
        t.setDaemon(true);
        t.start();
    }
}

From source file:fr.isen.browser5.Util.UrlLoader.java

public void loadInThread(final String url, final Object... args) {
    Runnable urlLoaderRunnable = new Runnable() {
        public void run() {
            load(url, args);/*from w w w . ja  v  a  2  s . c  o m*/
        }
    };
    Thread thread = new Thread(urlLoaderRunnable);
    thread.setDaemon(true);
    thread.start();
}

From source file:com.github.restdriver.clientdriver.integration.WhenCompletedTest.java

/**
 * This test might seem a touch weird so is worthy of comment:
 * //from   w w w  . ja  va 2s.  c  o  m
 * It sets up a thread that fires after 500 milliseconds and adds an expectation to receive that request within
 * 1 second. Once the request has been sent the 'done' boolean is set to true. We add a completion listener that
 * asserts that done is true.
 * 
 * If we were to write this normally (where the assertion is simply at the end of the method) it would fail.
 */
@Test
public void assertionWaitsUntilClientDriverIsFinished() throws Exception {

    clientDriver.addExpectation(onRequestTo("/hello"), giveEmptyResponse().within(1, TimeUnit.SECONDS));

    clientDriver.whenCompleted(new ClientDriverCompletedListener() {
        @Override
        public void hasCompleted() {
            assertThat(done, is(true));
        }
    });

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            schnoozeFor(500);
            hitThat(clientDriver.getBaseUrl() + "/hello");
            done = true;
        }
    });
    thread.setDaemon(true);
    thread.start();

}