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:convcao.com.agent.ConvcaoNeptusInteraction.java

public Thread auvMonitor() {
    Thread auvMon = new Thread("AuvMonitor") {
        public void run() {
            while (!cancel) {
                updateLocalStructures();
                boolean arrivedState = true;
                for (boolean arr : arrived.values())
                    if (!arr)
                        arrivedState = false;

                try {
                    if (arrivedState) {
                        showText("All vehicles arrived at desired positions. Starting new control sequence");
                        try {
                            controlLoop();
                        } catch (InterruptedException e) {
                            NeptusLog.pub().warn("Control thread interrupted");
                            manager.stop();
                            return;
                        } catch (Exception e) {
                            GuiUtils.errorMessage(getConsole(), e);
                            e.printStackTrace();
                            return;
                        }//from w w  w .j av a 2s.  c  o  m
                    } else {
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    showText("Control thread interrupted");
                    manager.stop();
                    return;
                }
            }
        };
    };
    auvMon.setDaemon(true);

    return auvMon;
}

From source file:com.rapidminer.tools.Tools.java

/**
 * Waits for process to die and writes log messages. Terminates if exit value is not 0.
 *//*  ww w  .j av a  2  s  . co m*/
public static void waitForProcess(final Operator operator, final Process process, final String name)
        throws OperatorException {
    int exitValue = -1;
    try {

        // if operator was provided, start an observer thread
        // that check if the operator was stopped
        if (operator != null) {
            Thread observerThread = new Thread(operator.getName() + "-stop-observer") {

                @Override
                public void run() {
                    Integer exitValue = null;
                    while (exitValue == null) {
                        try {
                            Thread.sleep(500);
                            exitValue = process.exitValue();
                        } catch (IllegalThreadStateException | InterruptedException e) {
                            try {
                                operator.checkForStop();
                            } catch (ProcessStoppedException e1) {
                                LogService.getRoot().log(Level.INFO,
                                        "com.rapidminer.tools.Tools.terminating_process", name);
                                process.destroy();
                                try {
                                    exitValue = process.waitFor();
                                } catch (InterruptedException e2) {
                                    // in case of another interrupt, set exit value to error
                                    exitValue = -1;
                                }
                            }
                        }
                    }
                }
            };
            observerThread.setDaemon(true);
            observerThread.start();
        }
        LogService.getRoot().log(Level.ALL, "com.rapidminer.tools.Tools.waiting_for_process", name);
        exitValue = process.waitFor();
    } catch (InterruptedException e) {

        // if process was stopped because user aborted it, re-throw exception
        if (operator != null) {
            operator.checkForStop();
        }

        // if process was stopped because of an error, set exit value to -1
        exitValue = -1;
    }
    if (exitValue == 0) {
        LogService.getRoot().log(Level.FINE, "com.rapidminer.tools.Tools.process_terminated_successfully",
                name);
    } else {
        throw new UserError(operator, 306, new Object[] { name, exitValue });
    }
}

From source file:com.actuate.development.tool.task.InstallBRDPro.java

private void startMonitorProcess(final IProgressMonitor monitor) {
    monitorAntProcess = true;/*from   ww w  .ja  v  a2 s.  c om*/
    Thread thread = new Thread("Monitor Process") {

        public void run() {
            while (monitorAntProcess) {
                if (monitor.isCanceled()) {
                    if (antProcess != null) {
                        antProcess.destroy();
                    }

                    try {
                        String path = new File(FileSystem.getCurrentDirectory()).getCanonicalPath();
                        ProcessEntry[] entrys = Kernel.getSystemProcessesSnap();
                        if (entrys != null) {
                            for (int i = 0; i < entrys.length; i++) {
                                ProcessEntry entry = entrys[i];
                                if (entry.getProcessName().toLowerCase().startsWith("7z")
                                        || entry.getProcessName().toLowerCase().startsWith("iscab")) {
                                    String entryPath = new File(entry.getExePath()).getCanonicalPath();
                                    if (entryPath.startsWith(path)) {
                                        Kernel.killProcess(entry.getProcessId());
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                    }
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
            }
        }
    };
    thread.setDaemon(true);
    thread.start();
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.ImageFrame.java

protected void generateThumbnailsInBackground(final List<WorkbenchRowImage> rowImages) {
    Collections.sort(rowImages);/*  ww  w. j ava 2s .c  o m*/

    Thread thumbGenTask = new Thread() {
        @Override
        @SuppressWarnings("synthetic-access")
        public void run() {
            // This is just a weird workaround.
            // For some reason, using the List directly resulted in a ConcurrentModificationException everytime
            // this method was called from addImages().
            // It doesn't look like it should throw an exception at all.
            WorkbenchRowImage[] imgs = new WorkbenchRowImage[rowImages.size()];
            rowImages.toArray(imgs);
            for (WorkbenchRowImage rowImage : imgs) {
                final WorkbenchRowImage ri = rowImage;
                try {
                    final ImageIcon thumb = generateThumbnail(rowImage);

                    // cache it so we don't have to do this again and again
                    rowImage.setThumbnail(thumb);

                    // update the UI
                    Runnable updateTrayUI = new Runnable() {
                        public void run() {
                            log.info("Thumbnail generation complete.  Updating the UI.  " + ri);
                            if (row == ri.getWorkbenchRow()) {
                                tray.getModel().set(ri.getImageOrder(), thumb);
                                tray.repaint();
                            }
                        }
                    };
                    SwingUtilities.invokeLater(updateTrayUI);
                } catch (IOException e) {
                    UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImageFrame.class, e);
                    log.warn("Failed to generate a thumbnail for " + rowImage.getCardImageFullPath(), e);
                }
            }
        }
    };

    thumbGenTask.setName("GenThumbs");
    thumbGenTask.setDaemon(true);
    thumbGenTask.setPriority(Thread.MIN_PRIORITY);
    thumbGenTask.start();
}

From source file:com.virus.removal.javafxapplication.FXMLDocumentController.java

/**
 * @param event//w  w  w  . j a  v a  2 s . c  o m
 */
@FXML
private void scanningPressed(final ActionEvent event) {

    /* Set the status of virus scanning */
    handler.setVirusScanStatus(VirusScanStatus.VIRUS_SCAN_STARTED);

    /* Clear the text */
    if (textForScanInProgress != null && textForScanInProgress.getText() != null) {
        textForScanInProgress.clear();
        javafx.application.Platform.runLater(new Runnable() {

            /* (non-Javadoc)
             * @see java.lang.Runnable#run()
             */
            @Override
            public void run() {
                /* Set the text */
                if (StringUtils.equals(drop.getText(), "English")) {
                    textForScanInProgress.appendText(
                            "VirusREM has began scanning your PC. Please allow up to 5 minutes per 500GB.");
                } else if (StringUtils.equals(drop.getText(), "Spanish")) {
                    textForScanInProgress.appendText(
                            "VirusREM de empezar el escaneo de su PC. Por favor, espere hasta 5 minutos por 500 GB.");
                } else if (drop.getText().equals("French")) {
                    textForScanInProgress.appendText(
                            "VirusREM a commenc la numrisation de votre PC. S'il vous plat permettre jusqu' 5 minutes par 500Go.");
                } else if (drop.getText().equals("Portuguese")) {
                    textForScanInProgress.appendText(
                            "VirusREM j comeou a varredura de seu PC. Por favor, aguarde at 5 minutos por 500GB.");
                }
            }
        });
    }

    /* Set the style */
    b5.setStyle("-fx-background-color:transparent");
    b6.setStyle("-fx-background-color:transparent");

    c4.setStyle("-fx-background-color:transparent");
    b4.setStyle("-fx-background-color:transparent");

    c2.setStyle("-fx-background-color:#00AEEF");
    b2.setStyle("-fx-background-color:transparent");

    c3.setStyle("-fx-background-color:transparent");
    b3.setStyle("-fx-background-color:transparent");

    c1.setStyle("-fx-background-color:transparent");
    b1.setStyle("-fx-background-color:#373E48");

    general.setVisible(false);
    general.setManaged(false);

    scann.setVisible(true);
    scann.setManaged(true);

    isProtected.setVisible(false);
    isProtected.setManaged(false);

    dash.setVisible(false);
    dash.setManaged(false);

    his.setVisible(false);
    his.setManaged(false);

    about.setVisible(false);
    about.setManaged(false);

    update.setVisible(false);
    update.setManaged(false);

    unprotected.setVisible(false);
    unprotected.setManaged(false);

    /* Create the task to start scan operation */
    workerThread = createWorker();

    progressBar.progressProperty().unbind();
    progressBar.progressProperty().bind(workerThread.progressProperty());

    /* Start the thread */
    Thread thread = new Thread(workerThread);
    thread.setDaemon(true);
    thread.start();

}

From source file:com.virus.removal.javafxapplication.FXMLDocumentController.java

/**
 * @param event/*from w w  w.j av  a  2 s  .  co  m*/
 */
@FXML
private void scanNowPressed(final ActionEvent event) {

    /* Set the style */
    b5.setStyle("-fx-background-color:transparent");
    b6.setStyle("-fx-background-color:transparent");

    c4.setStyle("-fx-background-color:transparent");
    b4.setStyle("-fx-background-color:transparent");

    c2.setStyle("-fx-background-color:#00AEEF");
    b2.setStyle("-fx-background-color:transparent");

    c3.setStyle("-fx-background-color:transparent");
    b3.setStyle("-fx-background-color:transparent");

    c1.setStyle("-fx-background-color:transparent");
    b1.setStyle("-fx-background-color:#373E48");

    general.setVisible(false);
    general.setManaged(false);

    scann.setVisible(true);
    scann.setManaged(true);

    isProtected.setVisible(false);
    isProtected.setManaged(false);

    dash.setVisible(false);
    dash.setManaged(false);

    his.setVisible(false);
    his.setManaged(false);

    about.setVisible(false);
    about.setManaged(false);

    update.setVisible(false);
    update.setManaged(false);

    unprotected.setVisible(false);
    unprotected.setManaged(false);

    if (workerThread == null || VirusScanStatus.VIRUS_JOB_COMPLETED == handler.getVirusScanStatus()
            || VirusScanStatus.VIRUS_SCAN_STOPPED == handler.getVirusScanStatus()) {

        /* Create the task to start scan operation */
        workerThread = createWorker();

        progressBar.progressProperty().unbind();
        progressBar.progressProperty().bind(workerThread.progressProperty());

        /* Set the status of virus scanning */
        handler.setVirusScanStatus(VirusScanStatus.VIRUS_SCAN_STARTED);

        /* Clear the text */
        if (textForScanInProgress != null && textForScanInProgress.getText() != null) {
            textForScanInProgress.clear();
            javafx.application.Platform.runLater(new Runnable() {

                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {
                    /* Set the text */
                    if (StringUtils.equals(drop.getText(), "English")) {
                        textForScanInProgress.appendText(
                                "VirusREM has began scanning your PC. Please allow up to 5 minutes per 500GB.");
                    } else if (StringUtils.equals(drop.getText(), "Spanish")) {
                        textForScanInProgress.appendText(
                                "VirusREM de empezar el escaneo de su PC. Por favor, espere hasta 5 minutos por 500 GB.");
                    } else if (drop.getText().equals("French")) {
                        textForScanInProgress.appendText(
                                "VirusREM a commenc la numrisation de votre PC. S'il vous plat permettre jusqu' 5 minutes par 500Go.");
                    } else if (drop.getText().equals("Portuguese")) {
                        textForScanInProgress.appendText(
                                "VirusREM j comeou a varredura de seu PC. Por favor, aguarde at 5 minutos por 500GB.");
                    }
                }
            });
        }

        /* Start the thread */
        Thread thread = new Thread(workerThread);
        thread.setDaemon(true);
        thread.start();
    }

}

From source file:mondrian.olap.Util.java

/**
 * Creates an {@link ScheduledExecutorService} object backed by a
 * thread pool with a fixed number of threads..
 * @param maxNbThreads Maximum number of concurrent
 * threads.//from  www. j a v a2  s .  c o  m
 * @param name The name of the threads.
 * @return An scheduled executor service preconfigured.
 */
public static ScheduledExecutorService getScheduledExecutorService(final int maxNbThreads, final String name) {
    return Executors.newScheduledThreadPool(maxNbThreads, new ThreadFactory() {
        final AtomicInteger counter = new AtomicInteger(0);

        public Thread newThread(Runnable r) {
            final Thread thread = Executors.defaultThreadFactory().newThread(r);
            thread.setDaemon(true);
            thread.setName(name + '_' + counter.incrementAndGet());
            return thread;
        }
    });
}

From source file:org.apache.activemq.transport.discovery.http.HTTPDiscoveryAgent.java

public void serviceFailed(DiscoveryEvent devent) throws IOException {

    final SimpleDiscoveryEvent event = (SimpleDiscoveryEvent) devent;
    if (event.failed.compareAndSet(false, true)) {
        discoveryListener.get().onServiceRemove(event);
        if (!event.removed.get()) {
            // Setup a thread to re-raise the event...
            Thread thread = new Thread() {
                public void run() {

                    // We detect a failed connection attempt because the
                    // service
                    // fails right away.
                    if (event.connectTime + minConnectTime > System.currentTimeMillis()) {
                        LOG.debug("Failure occured soon after the discovery event was generated.  "
                                + "It will be clasified as a connection failure: " + event);

                        event.connectFailures++;

                        if (maxReconnectAttempts > 0 && event.connectFailures >= maxReconnectAttempts) {
                            LOG.debug("Reconnect attempts exceeded " + maxReconnectAttempts
                                    + " tries.  Reconnecting has been disabled.");
                            return;
                        }/*from   w w  w  .j  ava 2  s  . c  o m*/

                        synchronized (sleepMutex) {
                            try {
                                if (!running.get() || event.removed.get()) {
                                    return;
                                }
                                LOG.debug("Waiting " + event.reconnectDelay
                                        + " ms before attepting to reconnect.");
                                sleepMutex.wait(event.reconnectDelay);
                            } catch (InterruptedException ie) {
                                Thread.currentThread().interrupt();
                                return;
                            }
                        }

                        if (!useExponentialBackOff) {
                            event.reconnectDelay = initialReconnectDelay;
                        } else {
                            // Exponential increment of reconnect delay.
                            event.reconnectDelay *= backOffMultiplier;
                            if (event.reconnectDelay > maxReconnectDelay) {
                                event.reconnectDelay = maxReconnectDelay;
                            }
                        }

                    } else {
                        event.connectFailures = 0;
                        event.reconnectDelay = initialReconnectDelay;
                    }

                    if (!running.get() || event.removed.get()) {
                        return;
                    }

                    event.connectTime = System.currentTimeMillis();
                    event.failed.set(false);
                    discoveryListener.get().onServiceAdd(event);
                }
            };
            thread.setDaemon(true);
            thread.start();
        }
    }
}

From source file:mondrian.olap.Util.java

/**
 * Creates an {@link ExecutorService} object backed by a thread pool.
 * @param maximumPoolSize Maximum number of concurrent
 * threads./*from   ww w . java2s  . c o  m*/
 * @param corePoolSize Minimum number of concurrent
 * threads to maintain in the pool, even if they are
 * idle.
 * @param keepAliveTime Time, in seconds, for which to
 * keep alive unused threads.
 * @param name The name of the threads.
 * @param rejectionPolicy The rejection policy to enforce.
 * @return An executor service preconfigured.
 */
public static ExecutorService getExecutorService(int maximumPoolSize, int corePoolSize, long keepAliveTime,
        final String name, RejectedExecutionHandler rejectionPolicy) {
    if (Util.PreJdk16) {
        // On JDK1.5, if you specify corePoolSize=0, nothing gets executed.
        // Bummer.
        corePoolSize = Math.max(corePoolSize, 1);
    }

    // We must create a factory where the threads
    // have the right name and are marked as daemon threads.
    final ThreadFactory factory = new ThreadFactory() {
        private final AtomicInteger counter = new AtomicInteger(0);

        public Thread newThread(Runnable r) {
            final Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setDaemon(true);
            t.setName(name + '_' + counter.incrementAndGet());
            return t;
        }
    };

    // Ok, create the executor
    final ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize,
            maximumPoolSize > 0 ? maximumPoolSize : Integer.MAX_VALUE, keepAliveTime, TimeUnit.SECONDS,
            // we use a sync queue. any other type of queue
            // will prevent the tasks from running concurrently
            // because the executors API requires blocking queues.
            // Important to pass true here. This makes the
            // order of tasks deterministic.
            // TODO Write a non-blocking queue which implements
            // the blocking queue API so we can pass that to the
            // executor.
            new SynchronousQueue<Runnable>(true), factory);

    // Set the rejection policy if required.
    if (rejectionPolicy != null) {
        executor.setRejectedExecutionHandler(rejectionPolicy);
    }

    // Done
    return executor;
}

From source file:com.frostwire.gui.bittorrent.SoundcloudTrackUrlDownload.java

private void start() {
    Thread t = new Thread(new Runnable() {

        @Override//from   w  w w  .  j  a va2 s .  c o  m
        public void run() {
            try {
                LinkCollector collector = LinkCollector.getInstance();
                LinkCrawler crawler = new LinkCrawler();
                crawler.setFilter(LinkFilterController.getInstance());
                crawler.crawl(trackUrl);
                crawler.waitForCrawling();

                if (_state.equals(STATE_STOPPED)) {
                    return;
                }

                _state = STATE_FINISHED;
                progress = 100;

                final List<FilePackage> packages = new ArrayList<FilePackage>();

                for (CrawledLink link : crawler.getCrawledLinks()) {
                    CrawledPackage parent = createCrawledPackage(link);
                    parent.setControlledBy(collector);
                    link.setParentNode(parent);
                    ArrayList<CrawledLink> links = new ArrayList<CrawledLink>();
                    links.add(link);
                    packages.add(createFilePackage(parent, links));
                }

                /*
                for (CrawledPackage pkg : new ArrayList<CrawledPackage>(collector.getPackages())) {
                for (CrawledLink link : new ArrayList<CrawledLink>(pkg.getChildren())) {
                    ArrayList<CrawledLink> links = new ArrayList<CrawledLink>();
                    links.add(link);
                    packages.addAll(collector.removeAndConvert(links));
                }
                }*/

                GUIMediator.safeInvokeAndWait(new Runnable() {
                    public void run() {
                        try {
                            // we assume there is only one link
                            for (FilePackage filePackage : packages) {
                                BTDownloadMediator.instance().openSoundcloudItem(filePackage, title, sr);
                            }
                        } catch (Throwable e) {
                            LOG.error("Error reading soundcloud package:" + e.getMessage(), e);
                            _state = STATE_ERROR;
                        }
                    }
                });

                GUIMediator.safeInvokeAndWait(new Runnable() {
                    public void run() {
                        BTDownloadMediator.instance().remove(SoundcloudTrackUrlDownload.this);
                    }
                });
            } catch (Throwable e) {
                LOG.error("Error crawling soundcloud: " + trackUrl, e);
                _state = STATE_ERROR;
            }
        }
    });
    t.setDaemon(true);
    t.setName("Soundcloud Crawl: " + trackUrl);
    t.start();
}