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.codefollower.lealone.omid.tso.TSOHandler.java

/**
 * Constructor/*  w ww  .  jav a  2  s . co m*/
 * @param channelGroup
 */
public TSOHandler(ChannelGroup channelGroup, TSOState state, int batchSize) {
    this.channelGroup = channelGroup;
    this.timestampOracle = state.getTimestampOracle();
    this.sharedState = state;

    this.flushThread = new FlushThread();
    this.scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(Thread.currentThread().getThreadGroup(), r);
            t.setDaemon(true);
            t.setName("Flush Thread");
            return t;
        }
    });
    this.batchSize = batchSize;
}

From source file:com.tascape.qa.th.Utils.java

/**
 * Executes command, and waits for the expected pass/fail phrase in console printout within timeout,
 *
 * @param command    command line//ww  w. j  a v  a 2s.  c  o  m
 * @param pass       skip checking if null
 * @param fail       skip checking if null
 * @param timeout    set 0 for not to check the output message, otherwise, waiting for timeout
 * @param workingDir working directory
 *
 * @return console output as a list of strings
 *
 * @throws IOException          for command error
 * @throws InterruptedException when interrupted
 */
public static List<String> cmd(String[] command, final String pass, final String fail, final long timeout,
        final String workingDir) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(command);
    if (workingDir != null) {
        pb.directory(new File(workingDir));
    }
    pb.redirectErrorStream(true);
    LOG.debug("Running command: " + pb.command().toString().replace(",", ""));
    final Process p = pb.start();
    Thread thread;
    final List<String> output = new ArrayList<>();

    if (timeout == 0) {
        LOG.debug("This is a start-and-exit command");
        output.add(PASS);
        return output;
    } else {
        thread = new Thread() {
            @Override
            public void run() {
                try {
                    LOG.debug("Command timeouts in {} ms", timeout);
                    Thread.sleep(timeout);
                    try {
                        p.exitValue();
                    } catch (IllegalThreadStateException ex) {
                        LOG.debug("killing subprocess {} - {}", p, ex.getMessage());
                        p.destroy();
                    }
                } catch (InterruptedException ex) {
                    LOG.warn(ex.getMessage());
                }
            }
        };
        thread.setName(Thread.currentThread().getName() + "-" + p.hashCode());
        thread.setDaemon(true);
        thread.start();
    }

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String c = p + " - ";
    for (String line = stdIn.readLine(); line != null;) {
        LOG.trace("{}{}", c, line);
        output.add(line);
        try {
            line = stdIn.readLine();
        } catch (IOException ex) {
            LOG.warn(ex.getMessage());
            break;
        }
    }
    LOG.debug("Command exit code {}", p.waitFor());
    thread.interrupt();
    try {
        stdIn.close();
    } catch (IOException ex) {
        LOG.warn("", ex);
    }

    for (String s : output) {
        if (pass != null && (s.contains(pass) || s.matches(pass))) {
            output.add(PASS);
            break;
        } else if (fail != null && s.contains(fail)) {
            output.add(FAIL);
            break;
        }
    }
    return output;
}

From source file:net.sbbi.upnp.jmx.UPNPMBeanDevicesDiscoveryHandler.java

protected void addUPNPMBeanDevice(UPNPMBeanDevice rootDevice) throws IOException {
    if (!rootDevice.isRootDevice())
        return;/*from   ww w . j  av  a  2  s.  c o  m*/
    synchronized (handledDevices) {
        for (Iterator i = handledDevices.iterator(); i.hasNext();) {
            UPNPMBeanDevice registred = (UPNPMBeanDevice) i.next();
            if (registred.getDeviceType().equals(rootDevice.getDeviceType())
                    && registred.getUuid().equals(rootDevice.getUuid())) {
                // API Use error
                throw new RuntimeException("An UPNPMBeanDevice object of type " + rootDevice.getDeviceType()
                        + " with uuid " + rootDevice.getUuid()
                        + " is already registred within this class, use a different UPNPMBeanDevice internalId");
            }
        }
        if (handledDevices.size() == 0) {
            Thread runner = new Thread(this, "UPNPMBeanDeviceDiscoveryHandler " + bindAddress.toString());
            runner.setDaemon(true);
            runner.start();

            SSDPAliveBroadcastMessageSender sender = new SSDPAliveBroadcastMessageSender(handledDevices);
            Thread runner2 = new Thread(sender, "SSDPAliveBroadcastMessageSender " + bindAddress.toString());
            runner2.setDaemon(true);
            runner2.start();

        }
        sendHello(rootDevice);
        handledDevices.add(rootDevice);
    }
}

From source file:com.mindcognition.mindraider.install.Installer.java

/**
 * Asynchronous repository backup ensuring dialog refreshing.
 *///from  w ww  .  j a  va2s .co m
public static void backupRepositoryAsync() {
    Thread thread = new Thread() {
        public void run() {

            String targetFile;
            if ((targetFile = backupRepository()) == null) {
                JOptionPane.showMessageDialog(MindRaider.mainJFrame,
                        Messages.getString("Installer.UnableToBackupRepository"),
                        Messages.getString("Installer.backupError"), JOptionPane.ERROR_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(MindRaider.mainJFrame,
                        Messages.getString("Installer.repositoryBackupStoredTo", targetFile),
                        Messages.getString("Installer.backupResult"), JOptionPane.INFORMATION_MESSAGE);
            }
        }
    };
    thread.setDaemon(true);
    thread.start();
}

From source file:com.cisco.oss.foundation.message.HornetQMessagingFactory.java

static void infiniteRetry() {

    Thread thread = new Thread(new Runnable() {

        private boolean done = false;

        @Override/*from  w ww  .j  a va  2s.c o m*/
        public void run() {

            while (!done) {

                LOGGER.trace("attempting to reconnect to HornetQ");
                try {
                    connectInternal();
                    LOGGER.trace("reconnect to HornetQ is successful");
                    INIT_READY.countDown();
                    done = true;
                } catch (Exception e) {
                    LOGGER.trace("failed to reconnect. retrying...", e);
                    try {
                        Thread.sleep(ConfigurationFactory.getConfiguration()
                                .getInt("service.hornetq.attachRetryDelay", 10000));
                    } catch (InterruptedException e1) {
                        LOGGER.trace("thread interrupted!!!", e1);
                    }
                }
            }
        }
    });
    thread.setName("hornetq-reconnect");
    thread.setDaemon(true);
    thread.start();
}

From source file:com.horstmeier.java.tftp.TFTPBaseServer.java

private void launch() throws IOException {
    log.debug("Starting TFTP Server on port " + port_ + ".");

    serverTftp_ = new TFTP();

    //This is the value used in response to each client.
    socketTimeout_ = serverTftp_.getDefaultTimeout();

    //we want the server thread to listen forever.
    serverTftp_.setDefaultTimeout(0);//from   w w  w . j a  v a 2 s  .c  o m

    serverTftp_.open(port_);

    Thread go = new Thread(this, "TFTPServer");
    go.setDaemon(true);
    go.start();
}

From source file:ExcelFx.FXMLDocumentController.java

private void mainProcessing(Task task) {
    final Thread thread = new Thread(null, task, "Background");
    thread.setDaemon(true);
    thread.start();/* ww  w .j a va 2 s .c  om*/
    new Thread() {
        @Override
        public void run() {
            try {
                thread.join();
            } catch (InterruptedException e) {
            }
            Platform.runLater(() -> {
                setProgressBar(0);
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("");
                alert.setHeaderText("");
                alert.setContentText(" ");
                alert.showAndWait();

            });

        }
    }.start();

    this.Print.setDisable(false);
}

From source file:de.uni_hannover.dcsec.siafu.control.Controller.java

/**
 * Initialize the simulator itself, and run the simulation.
 * //w ww.  ja va2 s  . c  o  m
 * @param configPath
 *            the file that defines the parameters of the simulation
 * @param simulationPath
 *            the path to the simulation data
 */
public Controller(final String configPath, final String simulationPath) {
    String verifiedConfigPath = configPath;

    if (configPath == null) {
        verifiedConfigPath = Controller.DEFAULT_CONFIG_FILE;
    }

    try {
        config = new XMLConfiguration(verifiedConfigPath);
        System.out.println("Using configuration at " + verifiedConfigPath);
    } catch (ConfigurationException e) {
        System.out.println("The config file doesn't exist or " + "is malformed. Recreating.");
        config = createDefaultConfigFile();
    }

    // Command Listener thread (for external commands)
    if (config.getBoolean("commandlistener.enable")) {
        int tcpPort = config.getInt("commandlistener.tcpport");
        try {
            commandListener = new CommandListener(this, tcpPort);
            output = new Output(this, tcpPort);
            // Start threads
            new Thread(commandListener, "Command Listener thread").start();
        } catch (IOException e) {
            System.err.println("The TCP port " + tcpPort + " is already in use. Is there another copy of "
                    + "Siafu running? Consider changing the port " + "number in the config file.");
            return;
        }
    }

    guiUsed = config.getBoolean("ui.usegui");

    if (guiUsed) {
        // Printout to the GUI
        progress = new GUIProgress();

        // If there's a GUI, let it load the
        // simulation, if it's avaialble
        gui = new GUI(this, simulationPath);
        Thread guiThread = new Thread(gui, "GUI thread");
        guiThread.setDaemon(false);
        guiThread.start();
    } else if (simulationPath != null) {
        // Printout to the Console
        progress = new ConsoleProgress();

        // Start the simulation without a GUI
        simulation = new Simulation(simulationPath, this);
    } else {
        // No simulation and no GUI to load. This won't
        // work. Die.
        System.err.println(
                "Please activate the GUI in the config file " + "or provide a simulation at the command line.");
        System.exit(1);
    }

}

From source file:de.micromata.genome.chronos.spi.DispatcherImpl.java

/**
 * Creates the thread.//from   w ww . j  a  v  a  2  s  .c o m
 *
 * @param jobStore the job store
 * @return the thread
 */
private Thread createThread(final JobStore jobStore) {
    final Thread t = new Thread(getCreateDispatcherThreadGroup(), this,
            "JCDT[" + getShortApplicationName() + "]: " + getDispatcherName());
    t.setDaemon(true);
    return t;
}

From source file:fish.payara.maven.plugins.micro.StartMojo.java

private void redirectStreamToGivenOutputStream(final InputStream inputStream, final OutputStream outputStream) {
    Thread thread = new Thread(threadGroup, () -> {
        try {/*from  w ww.  j ava  2 s.c  o m*/
            IOUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
            getLog().error("Error occurred while reading stream", e);
        }
    });
    thread.setDaemon(false);
    thread.start();
}