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:edu.wisc.commons.httpclient.CleanShutdownPoolingClientConnectionManager.java

@Override
public void shutdown() {
    if (shutdownComplete.get() || !this.shutdownLock.tryLock()) {
        //Already shutdown or shutdown in progress
        return;/*from   w w  w  . java  2s . com*/
    }

    try {
        //Create Thread to call shutdown
        final Thread shutdownThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    logger.info("PoolingClientConnectionManager shutdown started");
                    CleanShutdownPoolingClientConnectionManager.super.shutdown();
                } finally {
                    shutdownComplete.set(true);
                    logger.info("PoolingClientConnectionManager shutdown complete");
                }
            }
        });
        shutdownThread.setName("PoolingClientConnectionManager Shutdown Monitor");
        shutdownThread.setDaemon(true);

        //start shutdown thread
        shutdownThread.start();

        //track initial shutdown start time and time spent by the shutdown thread waiting or blocked
        final long shutdownStart = System.nanoTime();
        long waitStart = shutdownStart;

        //Monitor the shutdown thread
        while (!shutdownComplete.get()) {
            final long now = System.nanoTime();
            final long shutdownTime = TimeUnit.NANOSECONDS.toMillis(now - shutdownStart);

            //if time spent shutting down is greater than kill time forcibly stop the shutdown thread
            if (shutdownTime > this.shutdownThreadKillTime) {
                final String stackTrace = getStackTrace(shutdownThread);
                logger.error("Shutdown thread " + shutdownThread.getName() + " has been stopping for "
                        + shutdownTime + "ms, killing it. THIS IS BAD. \n" + stackTrace);
                shutdownThread.stop();

                //break out of the monitoring loop
                break;
            }
            //if time spent shutting down is greater than max time immediately interrupt the thread
            else if (shutdownTime > this.shutdownThreadMaxTime) {
                logger.warn("Shutdown thread " + shutdownThread.getName() + " has been stopping for "
                        + shutdownTime + "ms, interrupting immediately");
                shutdownThread.interrupt();
            }
            //otherwise check the state of the thread
            else {
                //If the thread is blocked or waiting and has been for longer than the max wait time
                //interrupt the thread. If not in blocked or waiting state update the wait-start time
                final State state = shutdownThread.getState();
                switch (state) {
                case BLOCKED:
                case TIMED_WAITING:
                case WAITING: {
                    final long waitTime = TimeUnit.NANOSECONDS.toMillis(now - waitStart);
                    if (waitTime > shutdownThreadMaxWaitTime) {
                        logger.info("Shutdown thread " + shutdownThread.getName() + " has been waiting for "
                                + waitTime + "ms, interrupting");
                        shutdownThread.interrupt();
                    } else {
                        break;
                    }
                }

                default: {
                    waitStart = now;
                    break;
                }
                }
            }

            //Sleep between state checks, don't want to overload anything
            try {
                Thread.sleep(shutdownThreadPollRate);
            } catch (InterruptedException e) {
                //ignore
            }
        }
    } finally {
        this.shutdownLock.unlock();
    }
}

From source file:com.chicm.cmraft.core.NodeConnectionManager.java

private void appendEntries(long term, ServerInfo leaderId, long leaderCommit, long prevLogIndex,
        long prevLogTerm, List<RaftLogEntry> entries, long maxIndex) {
    Preconditions.checkNotNull(entries);

    int nServers = getRemoteServers().size();
    if (nServers <= 0) {
        return;//from  w ww .j a va2  s . c  o  m
    }

    ExecutorService executor = Executors.newFixedThreadPool(nServers, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(getRaftNode().getName() + "-AsyncRpcCaller" + (byte) System.currentTimeMillis());
            return t;
        }
    });

    for (ServerInfo server : getRemoteServers()) {
        NodeConnection connection = connections.get(server);
        LOG.debug(getRaftNode().getName() + ": SENDING appendEntries Request TO: " + server);
        Thread t = new Thread(new AsynchronousAppendEntriesWorker(getRaftNode(), connection,
                getRaftNode().getRaftLog(), getRaftNode().getServerInfo(), term, leaderCommit, prevLogIndex,
                prevLogTerm, entries, maxIndex));
        t.setDaemon(true);
        executor.execute(t);
    }
}

From source file:com.legstar.protobuf.cobol.ProtoCobol.java

/**
 * From Google's org.waveprotocol.pst.PstFileDescriptor.
 * <p/>//from   w  ww .  ja  v  a  2 s .c  o  m
 * Will kill a process if it takes too long.
 * 
 * @param delay how long to wait (
 * @param unit the unit of time delay is expressed in
 * @param process the process to kill
 */
protected void killProcessAfter(final long delay, final TimeUnit unit, final Process process) {
    Thread processKiller = new Thread() {
        @Override
        public void run() {
            try {
                Thread.sleep(unit.toMillis(delay));
                process.destroy();
            } catch (InterruptedException e) {
            }
        }
    };
    processKiller.setDaemon(true);
    processKiller.start();
}

From source file:com.zimbra.cs.mailclient.imap.ImapConnection.java

private ImapResponse sendIdle(ImapRequest req) {
    request = req;/*  www. ja v a 2  s . c o m*/
    try {
        req.write(getImapOutputStream());
        ImapResponse res = waitForResponse();
        if (res.isTagged()) {
            return res;
        }
        assert res.isContinuation();
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                idleHandler();
            }
        });
        t.setName("IMAP IDLE thread");
        t.setDaemon(true);
        t.start();
    } catch (IOException e) {
        request = null;
    }
    return null;
}

From source file:io.apiman.gateway.engine.jdbc.PollCachingJdbcRegistry.java

/**
 * Starts up a thread that polls the ES store for updates.
 *//*from  w  w w  .  jav a 2 s . c  o m*/
protected void startCacheInvalidator() {
    polling = true;
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            // Wait on startup before starting to poll.
            try {
                Thread.sleep(startupDelayMillis);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }

            while (polling) {
                try {
                    Thread.sleep(pollIntervalMillis);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                checkCacheVersion();
            }
        }
    }, "JdbcRegistryCacheInvalidator"); //$NON-NLS-1$
    thread.setDaemon(true);
    thread.start();
}

From source file:com.chicm.cmraft.rpc.RpcServer.java

public void startTPSReport() {
    if (tpsReportStarted)
        return;/*from w  w w .j  a  v a2  s  . co  m*/

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                long calls = callCounter.get();
                long starttm = System.currentTimeMillis();
                try {
                    Thread.sleep(5000);
                } catch (Exception e) {
                    LOG.error("exception", e);
                }
                long sec = (System.currentTimeMillis() - starttm) / 1000;
                if (sec == 0)
                    sec = 1;
                long n = callCounter.get() - calls;
                LOG.info("TPS: " + (n / sec));
                LOG.info("request queue: " + requestQueue.size() + " response queue: " + responseQueue.size());
            }
        }
    });
    thread.setDaemon(true);
    thread.setName("TPS report");
    thread.start();
    tpsReportStarted = true;
    LOG.info("TPS report started");
}

From source file:com.clank.launcher.swing.MessageLog.java

/**
 * Internal method to consume a stream.//w  w  w .j a  va 2  s .c  o  m
 * 
 * @param from stream to consume
 * @param outputStream console stream to write to
 */
private void consume(InputStream from, ConsoleOutputStream outputStream) {
    final InputStream in = from;
    final PrintWriter out = new PrintWriter(outputStream, true);
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            byte[] buffer = new byte[1024];
            try {
                int len;
                while ((len = in.read(buffer)) != -1) {
                    String s = new String(buffer, 0, len);
                    System.out.print(s);
                    out.append(s);
                    out.flush();
                }
            } catch (IOException e) {
            } finally {
                closeQuietly(in);
                closeQuietly(out);
            }
        }
    });
    thread.setDaemon(true);
    thread.start();
}

From source file:com.zavakid.mushroom.impl.TestSinkQueue.java

private SinkQueue<Integer> newSleepingConsumerQueue(int capacity, int... values) {
    final SinkQueue<Integer> q = new SinkQueue<Integer>(capacity);
    final Semaphore semaphore = new Semaphore(0);
    for (int i : values) {
        q.enqueue(i);//from w  w  w.java2  s . c o  m
    }
    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                q.consume(new Consumer<Integer>() {

                    public void consume(Integer e) throws InterruptedException {
                        semaphore.release(1);
                        LOG.info("sleeping");
                        Thread.sleep(1000 * 86400); // a long time
                    }
                });
            } catch (InterruptedException ex) {
                LOG.warn("Interrupted", ex);
            }
        }
    };
    t.setName("Sleeping consumer");
    t.setDaemon(true); // so jvm can exit
    t.start();
    try {
        semaphore.acquire();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    LOG.debug("Returning new sleeping consumer queue");
    return q;
}

From source file:com.betfair.cougar.test.socket.app.JarRunner.java

private void startOutputStreaming(final File dir, final InputStream is, final String name) {
    Thread t = new Thread(new Runnable() {
        @Override/*  w w w  .j  a va  2  s.com*/
        public void run() {
            try {
                PrintWriter fw = new PrintWriter(new File(dir, name + ".log"));
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String line;
                while ((line = br.readLine()) != null) {
                    fw.println(line);
                    fw.flush();
                    outputReceived(line);
                }
                is.close();
                fw.close();
            } catch (IOException ioe) {
                System.err.println("Error copying " + name + " for " + getName());
                ioe.printStackTrace();
            }
        }
    }, name + "-copier-" + getName());
    t.setDaemon(true);
    t.start();
}

From source file:com.hangum.tadpole.rdb.core.editors.sessionlist.SessionListEditor.java

/**
 *   ? ?  ./*  w  w  w.  ja  va 2s .  c  o m*/
 */
private void createSessionUI() {
    Composite compositSessionUI = new Composite(mainSashForm, SWT.NONE);
    compositSessionUI.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    GridLayout gl_compositeHead = new GridLayout(1, false);
    gl_compositeHead.marginHeight = 0;
    gl_compositeHead.horizontalSpacing = 0;
    gl_compositeHead.marginWidth = 0;
    compositSessionUI.setLayout(gl_compositeHead);

    Composite compositeSessionHead = new Composite(compositSessionUI, SWT.NONE);
    compositeSessionHead.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
    compositeSessionHead.setLayout(new GridLayout(2, false));

    Composite compositeSessionBody = new Composite(compositSessionUI, SWT.NONE);
    compositeSessionBody.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    textRefreshMil = new Text(compositeSessionHead, SWT.BORDER);
    textRefreshMil.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent event) {
            validateInterval();
        }
    });
    textRefreshMil.setText("10");
    GridData gd_textRefreshMil = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
    gd_textRefreshMil.widthHint = 30;
    gd_textRefreshMil.minimumWidth = 30;
    textRefreshMil.setLayoutData(gd_textRefreshMil);

    ToolBar toolBar = new ToolBar(compositeSessionHead, SWT.FLAT | SWT.RIGHT);
    toolBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));

    ToolItem tltmSecondsRefresh = new ToolItem(toolBar, SWT.NONE);
    tltmSecondsRefresh.setText(Messages.get().SessionListEditor_4);

    tltmStart = new ToolItem(toolBar, SWT.NONE);
    tltmStart.setToolTipText(CommonMessages.get().Start);
    tltmStart.setImage(GlobalImageUtils.getStart()); //$NON-NLS-1$
    tltmStart.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            if (!validateInterval())
                return;

            isNotRefreshUi = true;

            tltmStart.setEnabled(false);
            tltmStop.setEnabled(true);

            initSessionListData();
        }
    });
    tltmStart.setEnabled(true);

    tltmStop = new ToolItem(toolBar, SWT.NONE);
    tltmStop.setToolTipText(CommonMessages.get().Stop);
    tltmStop.setImage(GlobalImageUtils.getStop());
    tltmStop.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            isNotRefreshUi = false;

            tltmStart.setEnabled(true);
            tltmStop.setEnabled(false);
        }
    });
    tltmStop.setEnabled(false);

    new ToolItem(toolBar, SWT.SEPARATOR);

    ToolItem tltmRefresh = new ToolItem(toolBar, SWT.NONE);
    tltmRefresh.setToolTipText(CommonMessages.get().Refresh);
    tltmRefresh.setImage(GlobalImageUtils.getRefresh());
    tltmRefresh.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            initSessionListData();
        }
    });

    new ToolItem(toolBar, SWT.SEPARATOR);

    tltmKillProcess = new ToolItem(toolBar, SWT.NONE);
    tltmKillProcess.setToolTipText(Messages.get().SessionListEditor_3);
    tltmKillProcess.setImage(GlobalImageUtils.getKilling());
    tltmKillProcess.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            boolean isPossible = false;
            if (PermissionChecker.isDBAdminRole(userDB))
                isPossible = true;
            else {
                if (!PermissionChecker.isProductBackup(userDB))
                    isPossible = true;
            }

            if (isPossible) {
                killProcess();
            } else {
                MessageDialog.openWarning(PlatformUI.getWorkbench().getDisplay().getActiveShell(),
                        CommonMessages.get().Warning, Messages.get().MainEditor_21);
            }
        }
    });
    tltmKillProcess.setEnabled(false);
    compositeSessionBody.setLayout(new GridLayout(1, false));

    SashForm sashForm = new SashForm(compositeSessionBody, SWT.VERTICAL);
    sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    Composite compositeBody = new Composite(sashForm, SWT.NONE);
    compositeBody.setLayout(new GridLayout(1, false));

    tableViewerSessionList = new TableViewer(compositeBody, SWT.BORDER | SWT.FULL_SELECTION);
    tableViewerSessionList.addSelectionChangedListener(new ISelectionChangedListener() {
        public void selectionChanged(SelectionChangedEvent event) {
            if (tableViewerSessionList.getSelection().isEmpty())
                return;

            tltmKillProcess.setEnabled(true);

            StructuredSelection ss = (StructuredSelection) tableViewerSessionList.getSelection();
            SessionListDAO sl = (SessionListDAO) ss.getFirstElement();
            if (null != sl.getInfo()) {
                refreshLocksList(sl.getSID());
                textQuery.setText(sl.getInfo());
                textQuery.setFocus();
            } else {
                textQuery.setText(""); //$NON-NLS-1$
            }
        }
    });
    Table tableSessionList = tableViewerSessionList.getTable();
    tableSessionList.setHeaderVisible(true);
    tableSessionList.setLinesVisible(true);
    tableSessionList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

    Group compositeQuery = new Group(sashForm, SWT.NONE);
    compositeQuery.setLayout(new GridLayout(1, false));
    compositeQuery.setText(Messages.get().Query);

    textQuery = new Text(compositeQuery, SWT.BORDER | SWT.READ_ONLY | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI);
    textQuery.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
    comparator = new MySQLSessionListTableCompare();
    tableViewerSessionList.setSorter(comparator);

    createColumn();

    tableViewerSessionList.setContentProvider(new ArrayContentProvider());
    tableViewerSessionList.setLabelProvider(new MySQLSessionListLabelProvider());

    sashForm.setWeights(new int[] { 7, 3 });

    pushSession.start();
    Thread thread = new Thread(startUIThread());
    thread.setDaemon(true);
    thread.start();

    initSessionListData();
}