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:gov.nih.nci.caintegrator.application.gpvisualizer.CaIntegratorRunVisualizer.java

protected Thread copyStream(final InputStream is, final PrintStream out) throws IOException {
    // create thread to read from the a process' output or error stream

    Thread copyThread = new Thread(new Runnable() {
        public void run() {
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String line;//www . j a  v  a2  s .c om
            // copy inputstream to outputstream

            try {

                while ((line = in.readLine()) != null) {
                    out.println(line);
                }
            } catch (IOException ioe) {
                System.err.println(ioe + " while reading from process stream");
            }
        }
    });
    copyThread.setDaemon(true);

    return copyThread;
}

From source file:com.gemstone.gemfire.test.dunit.standalone.ProcessManager.java

private void linkStreams(final int vmNum, final ProcessHolder holder, final InputStream in,
        final PrintStream out) {
    Thread ioTransport = new Thread() {
        public void run() {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String vmName = (vmNum == -2) ? "[locator]" : "[vm_" + vmNum + "]";
            try {
                String line = reader.readLine();
                while (line != null) {
                    if (line.length() == 0) {
                        out.println();/*ww  w  .  j  a  va  2  s .  c  o m*/
                    } else {
                        out.print(vmName);
                        out.println(line);
                    }
                    line = reader.readLine();
                }
            } catch (Exception e) {
                if (!holder.isKilled()) {
                    out.println("Error transporting IO from child process");
                    e.printStackTrace(out);
                }
            }
        }
    };

    ioTransport.setDaemon(true);
    ioTransport.start();
}

From source file:com.alibaba.cobar.client.CobarSqlMapClientTemplate.java

private ExecutorService createCustomExecutorService(int poolSize, final String method) {
    int coreSize = Runtime.getRuntime().availableProcessors();
    if (poolSize < coreSize) {
        coreSize = poolSize;//from   w ww.  ja v a  2  s  .  c  o m
    }
    ThreadFactory tf = new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "thread created at CobarSqlMapClientTemplate method [" + method + "]");
            t.setDaemon(true);
            return t;
        }
    };
    BlockingQueue<Runnable> queueToUse = new LinkedBlockingQueue<Runnable>(coreSize);
    final ThreadPoolExecutor executor = new ThreadPoolExecutor(coreSize, poolSize, 60, TimeUnit.SECONDS,
            queueToUse, tf, new ThreadPoolExecutor.CallerRunsPolicy());

    return executor;
}

From source file:com.google.dart.tools.ui.internal.typehierarchy.TypeHierarchyContentProvider_OLD.java

/**
 * Schedules possibly long-running sub-types search operation.
 *//*from  w  ww.j  av a 2 s .c om*/
private void scheduleSubTypesSearch(final Viewer viewer, final ClassElement inputClass) {
    Thread thread = new Thread() {
        @Override
        public void run() {
            // prepare sub types
            fillSubTypes(inputClass);
            if (memberName != null) {
                keepBranchesWithMemberOverride(inputClass);
            }
            // refresh viewer
            Display.getDefault().asyncExec(new Runnable() {
                @Override
                public void run() {
                    Control control = viewer.getControl();
                    if (control != null && !control.isDisposed()) {
                        viewer.refresh();
                        if (viewer instanceof TreeViewer) {
                            ((TreeViewer) viewer).expandAll();
                        }
                    }
                }
            });
        }
    };
    thread.setDaemon(true);
    thread.start();
}

From source file:com.baifendian.swordfish.execserver.engine.hive.HiveSqlExec.java

/**
 *  sql ? ?, ?,  execute, ?//from   w w w .  java  2  s . c  o  m
 *
 * @param createFuncs ?
 * @param sqls  sql
 * @param isContinue ?, ???
 * @param resultCallback , ?
 * @param queryLimit ?
 * @param remainTime ?, 
 */
public boolean execute(List<String> createFuncs, List<String> sqls, boolean isContinue,
        ResultCallback resultCallback, Integer queryLimit, int remainTime) {

    // ?
    if (remainTime <= 0) {
        return false;
    }

    // ?
    queryLimit = (queryLimit != null) ? queryLimit : defaultQueryLimit;

    HiveConnection hiveConnection = null;
    Statement sta = null;
    Thread logThread = null;

    //  hive ?
    HiveService2ConnectionInfo hiveService2ConnectionInfo = hiveUtil.getHiveService2ConnectionInfo(userName);

    logger.info("execution connection information:{}", hiveService2ConnectionInfo);

    HiveService2Client hiveService2Client = hiveUtil.getHiveService2Client();

    try {
        try {
            hiveConnection = hiveService2Client.borrowClient(hiveService2ConnectionInfo);

            sta = hiveConnection.createStatement();
            //        sta.setQueryTimeout(remainTime);

            // 
            logThread = new Thread(new JdbcLogRunnable(sta));
            logThread.setDaemon(true);
            logThread.start();

            // set queue
            if (queueSQL != null) {
                logger.info("hive queue : {}", queueSQL);
                sta.execute(queueSQL);
            }

            //  function
            if (createFuncs != null) {
                for (String createFunc : createFuncs) {
                    logger.info("hive create function sql: {}", createFunc);
                    sta.execute(createFunc);
                }
            }
        } catch (Exception e) {
            logger.error("execute query exception", e);

            // , , ?
            handlerResults(0, sqls, FlowStatus.FAILED, resultCallback);

            return false;
        }

        //  sql ?
        for (int index = 0; index < sqls.size(); ++index) {
            String sql = sqls.get(index);

            Date startTime = new Date();

            logger.info("hive execute sql: {}", sql);

            ExecResult execResult = new ExecResult();
            execResult.setIndex(index);
            execResult.setStm(sql);

            try {
                // ? query  show ?
                if (HiveUtil.isTokQuery(sql) || HiveUtil.isLikeShowStm(sql)) {
                    sta.setMaxRows(queryLimit);
                    ResultSet res = sta.executeQuery(sql);

                    ResultSetMetaData resultSetMetaData = res.getMetaData();
                    int count = resultSetMetaData.getColumnCount();

                    List<String> colums = new ArrayList<>();
                    for (int i = 1; i <= count; i++) {
                        colums.add(resultSetMetaData.getColumnLabel(
                                i)/*parseColumnName(resultSetMetaData.getColumnLabel(i), colums)*/);
                    }

                    execResult.setTitles(colums);

                    List<List<String>> datas = new ArrayList<>();

                    //  1,  query ?
                    if (count > 1 || HiveUtil.isTokQuery(sql)) {
                        while (res.next()) {
                            List<String> values = new ArrayList<>();
                            for (int i = 1; i <= count; ++i) {
                                values.add(res.getString(i));
                            }

                            datas.add(values);
                        }
                    } else {
                        StringBuffer buffer = new StringBuffer();

                        while (res.next()) {
                            buffer.append(res.getString(1));
                            buffer.append("\n");
                        }

                        List<String> values = new ArrayList<>();
                        values.add(buffer.toString().trim());

                        datas.add(values);
                    }

                    execResult.setValues(datas);
                } else {
                    sta.execute(sql);
                }

                // ??
                execResult.setStatus(FlowStatus.SUCCESS);

                // ?
                if (resultCallback != null) {
                    Date endTime = new Date();
                    resultCallback.handleResult(execResult, startTime, endTime);
                }
            } catch (SQLTimeoutException e) {
                // sql 
                logger.error("executeQuery timeout exception", e);

                handlerResults(index, sqls, FlowStatus.FAILED, resultCallback);
                return false;
            } catch (DaoSemanticException | HiveSQLException e) {
                // 
                logger.error("executeQuery exception", e);

                if (isContinue) {
                    handlerResult(index, sql, FlowStatus.FAILED, resultCallback);
                } else {
                    handlerResults(index, sqls, FlowStatus.FAILED, resultCallback);
                    return false;
                }
            } catch (Exception e) {
                // TTransport 
                if (e.toString().contains("TTransportException")) {
                    logger.error("Get TTransportException return a client", e);
                    // ???
                    //            hiveService2Client.invalidateObject(hiveService2ConnectionInfo, hiveConnection);
                    handlerResults(index, sqls, FlowStatus.FAILED, resultCallback);
                    return false;
                }

                // socket 
                if (e.toString().contains("SocketException")) {
                    logger.error("SocketException clear pool", e);
                    hiveService2Client.clear();
                    handlerResults(index, sqls, FlowStatus.FAILED, resultCallback);
                    return false;
                }

                logger.error("executeQuery exception", e);

                if (isContinue) {
                    handlerResult(index, sql, FlowStatus.FAILED, resultCallback);
                } else {
                    handlerResults(index, sqls, FlowStatus.FAILED, resultCallback);
                    return false;
                }
            }
        }
    } finally {
        // 
        try {
            if (sta != null) {
                sta.close();
            }
        } catch (Exception e) {
            logger.error("Catch an exception", e);
        }

        try {
            // 
            if (hiveConnection != null) {
                // 
                hiveConnection.close();

                // , ??
                hiveService2Client.returnClient(hiveService2ConnectionInfo, hiveConnection);
            }
        } catch (Exception e) {
            logger.error("Catch an exception", e);
        }

        // 
        try {
            if (logThread != null) {
                logThread.interrupt();
                logThread.join(HiveUtil.DEFAULT_QUERY_PROGRESS_THREAD_TIMEOUT);
            }
        } catch (Exception e) {
            //        logger.error("Catch an exception", e);
        }
    }

    return true;
}

From source file:com.twinsoft.convertigo.engine.ContextManager.java

public void remove(Context context) {
    if (context == null) {
        // Silently ignore
        Engine.logContextManager.warn("The context cannot be removed because it does not exist any more!");
        return;//ww  w.jav a 2  s .c  o m
    }

    // To prevent from deadlock, we must synchronize on the context itself (see #3048)
    // to avoid another request thread to try to use the context simultaneously.
    // This lock must occur BEFORE acquiring lock the the contexts table.
    synchronized (context) {
        String contextID = context.contextID;
        Engine.logContextManager.info("Removing context " + contextID);

        synchronized (contexts) {
            contexts.remove(contextID);
        }

        context.isDestroying = true;

        if ((context.requestedObject != null) && (context.requestedObject.runningThread != null)) {
            Engine.logContextManager.debug("Stopping requestable thread for context " + contextID);
            //context.requestedObject.runningThread.bContinue = false;
            context.abortRequestable();
        }

        // Trying to execute the end transaction (only in the engine mode)
        if ((Engine.isEngineMode()) && (context.getConnector() != null)) {
            // Execute the end transaction
            String endTransactionName = "n/a";
            try {
                endTransactionName = context.getConnector().getEndTransactionName();
                if ((endTransactionName != null) && (!endTransactionName.equals(""))) {
                    Engine.logContextManager
                            .debug("Trying to execute the end transaction: \"" + endTransactionName + "\"");
                    context.transactionName = endTransactionName;
                    DefaultRequester defaultRequester = new DefaultRequester();
                    // #4910 - prevent loop for destroying context renew
                    context.isDestroying = false;
                    defaultRequester.processRequest(context);
                    Engine.logContextManager.debug("End transaction successfull");
                }
            } catch (Throwable e) {
                Engine.logContextManager.error("Unable to execute the end transaction; " + "context: "
                        + context.contextID + ", " + "project: " + context.projectName + ", " + "connector: "
                        + context.connectorName + ", " + "end transaction: " + endTransactionName, e);
            } finally {
                context.isDestroying = true;
            }
            // Unlocks device if any
            // WARNING: removing the device pool MUST BE DONE AFTER the end transaction!!!
            String connectorQName = context.getConnector().getQName();
            DevicePool devicePool = getDevicePool(connectorQName);
            if (devicePool != null) {
                long contextNum = (Long.valueOf(Integer.toString(context.contextNum, 10))).longValue();
                Engine.logContextManager.trace("DevicePool for '" + connectorQName
                        + "' exist: unlocking device for context number " + contextNum + ".");
                devicePool.unlockDevice(contextNum);
            }
        }
        if (Engine.isEngineMode()) {
            for (final Connector connector : context.getOpenedConnectors()) {
                Engine.logContextManager.trace("Releasing " + connector.getName() + " connector ("
                        + connector.getClass().getName() + ") for context id " + context.contextID);
                Thread th = new Thread(new Runnable() {
                    public void run() {
                        connector.release();
                    }
                });
                th.setDaemon(true);
                th.start();
            }
        }

        context.clearConnectors();

        // Set TwsCachedXPathAPI to null
        context.cleanXpathApi();

        Engine.theApp.sessionManager.removeSession(contextID);
        String projectName = (String) context.projectName;

        /* Fix: #1754 - Slower transaction execution with many session */
        // HTTP session maintain its own context list in order to
        // improve context removal on session unbound process
        // See also #4198 which fix a regression
        String sessionID = context.httpSession != null ? context.httpSession.getId()
                : context.contextID.substring(0, context.contextID.indexOf("_"));
        HttpSession httpSession = HttpSessionListener.getHttpSession(sessionID);
        if (httpSession != null) {
            synchronized (httpSession) {
                try {
                    ArrayList<Context> contextList = GenericUtils.cast(httpSession.getAttribute("contexts"));
                    if ((contextList != null) && contextList.contains(context)) {
                        contextList.remove(context);
                        Engine.logContextManager.debug("(ContextManager) context " + contextID
                                + " has been removed from http session's context list");
                    }
                    httpSession.setAttribute("contexts", contextList);
                } catch (Exception e) {
                    // Ignore: HTTP session may have already been invalidated
                }
            }
        }

        Engine.logContextManager.debug("Context " + contextID + " has been removed");
        Engine.logContext.debug("[" + contextID + "] Context removed, project: " + projectName);
        Engine.logContextManager.info("Current in-use contexts: " + contexts.size());
        Engine.logUsageMonitor.info("[Contexts] Current in-use contexts: " + contexts.size());
    }
}

From source file:gtu.jpa.hibernate.Rcdf002eDBUI.java

private void executeReportBtnActionPerformed(ActionEvent evt) {
    try {/* w  w w .  j  a  v a2 s  . c  om*/
        final LoadToDBAndWriteFile exe = new LoadToDBAndWriteFile();
        if (StringUtils.isNotBlank(xmlFileText.getText())) {
            File file = new File(xmlFileText.getText());
            if (file.exists()) {
                exe.bulkTxt = file;
            }
        } else if (getBulkFile() != null) {
            xmlFileText.setText(getBulkFile().getAbsolutePath());
        }
        Log.Setting.NORMAL.apply();
        exe.setOut(new PrintStream(new PrintStreamAdapter("big5") {
            @Override
            public void println(String message) {
                Log.debug(message);
                if (StringUtils.length(logArea.getText()) > 500) {
                    logArea.setText("");
                }
                logArea.append(message + "\n");
            }
        }));
        setTitle(".......");
        Thread thread = new Thread(Thread.currentThread().getThreadGroup(), new Runnable() {
            @Override
            public void run() {
                try {
                    long current = System.currentTimeMillis();
                    exe.execute();
                    current = System.currentTimeMillis() - current;
                    setTitle(" : ?");
                    JCommonUtil._jOptionPane_showMessageDialog_info(
                            " : ?,:" + current + "\n?!");
                } catch (Exception ex) {
                    setTitle(":" + ex.getMessage());
                    JCommonUtil.handleException(ex);
                }
            }
        }, "xxxxxxxxxxxxxxxxxcxccx");
        thread.setDaemon(true);
        thread.start();
    } catch (Exception ex) {
        setTitle(":" + ex.getMessage());
        JCommonUtil.handleException(ex);
    }
}

From source file:com.igormaznitsa.zxpoly.MainForm.java

public MainForm(final String title, final String romPath) throws IOException {
    initComponents();//  ww  w .  jav  a  2  s .  co  m
    this.setTitle(title);

    this.getInputContext().selectInputMethod(Locale.ENGLISH);

    setIconImage(Utils.loadIcon("appico.png"));

    final RomData rom = loadRom(romPath);

    this.board = new Motherboard(rom);
    this.board.setZXPolyMode(true);
    this.menuOptionsZX128Mode.setSelected(!this.board.isZXPolyMode());
    this.menuOptionsTurbo.setSelected(this.turboMode);

    log.info("Main form completed");
    this.board.reset();

    this.scrollPanel.getViewport().add(this.board.getVideoController());
    this.keyboardAndTapeModule = this.board.findIODevice(KeyboardKempstonAndTapeIn.class);
    this.kempstonMouse = this.board.findIODevice(KempstonMouse.class);

    final KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
    manager.addKeyEventDispatcher(new KeyboardDispatcher(this.keyboardAndTapeModule));

    final GridBagConstraints cpuIndicatorConstraint = new GridBagConstraints();
    cpuIndicatorConstraint.ipadx = 5;

    this.panelIndicators.add(this.indicatorCPU0, cpuIndicatorConstraint, 0);
    this.panelIndicators.add(this.indicatorCPU1, cpuIndicatorConstraint, 1);
    this.panelIndicators.add(this.indicatorCPU2, cpuIndicatorConstraint, 2);
    this.panelIndicators.add(this.indicatorCPU3, cpuIndicatorConstraint, 3);

    updateTapeMenu();

    final Thread daemon = new Thread(this, "ZXPolyThread");
    daemon.setDaemon(true);
    daemon.start();

    updateInfoPanel();

    pack();

    this.setLocationRelativeTo(null);
}

From source file:com.google.dart.tools.core.DartCore.java

/**
 * Answer the unique project manager used for analysis of anything in the workspace.
 * //  ww  w . ja  v  a  2  s.  c om
 * @return the manager (not {@code null})
 */
public static ProjectManager getProjectManager() {
    synchronized (projectManagerLock) {
        if (projectManager == null) {
            // start index
            final Index index;
            {
                File stateDir = getPlugin().getStateLocation().toFile();
                File indexDir = new File(stateDir, "index");
                indexDir.mkdirs();
                IndexStore indexStore = IndexFactory.newFileIndexStore(indexDir);
                index = IndexFactory.newIndex(indexStore);
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        index.run();
                    }
                };
                thread.setName("Index Thread");
                thread.setDaemon(true);
                thread.start();
            }
            // create ProjectManagerImpl
            projectManager = new ProjectManagerImpl(ResourcesPlugin.getWorkspace().getRoot(),
                    DartSdkManager.getManager().getSdk(), DartSdkManager.getManager().getSdkContextId(), index,
                    DartIgnoreManager.getInstance());
        }
    }
    return projectManager;
}

From source file:com.edgenius.wiki.webapp.action.BaseAction.java

/**
 * Ugly, but 2 Action class need it..../* w w  w .  j  a  v a 2  s .  c o  m*/
 * @param listener
 * @param indexService
 */
protected void rebuildIndexes(final IndexRebuildListener listener, final IndexServiceImpl indexService) {
    //this method only clean index files so far...
    indexService.cleanIndexes(listener);

    final String uuid = UUID.randomUUID().toString();
    //I don't know how invoke HibernateInceptor inside IndexServiceImpl.rebuildIndex() threads, so I copy 
    //them into here, so that each rebuild*() thread will be surround  HibernateInceptor to avoid lazy loading problem
    //see http://forum.springframework.org/showthread.php?p=200379#post200379
    Thread t1 = new Thread(new Runnable() {
        public void run() {
            try {
                //Some page render need space read permission, such as PageIndex needs PageService.getPageTree() method.
                securityService.proxyLoginAsSystemAdmin();
                ((IndexServiceImpl) indexService).rebuildPageIndex();
            } catch (Exception e) {
                log.warn("Page index rebuid complete with error", e);
            } finally {
                securityService.proxyLogout();
            }
            listener.indexComplete(IndexRebuildListener.PAGE);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.PAGE);
        }

    });
    t1.setName("Rebuild page index");
    t1.setDaemon(true);
    t1.start();

    Thread t2 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildCommentIndex();
            listener.indexComplete(IndexRebuildListener.COMMENT);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.COMMENT);
        }
    });
    t2.setDaemon(true);
    t2.setName("Rebuild comment index");
    t2.start();

    Thread t3 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildSpaceIndex();
            listener.indexComplete(IndexRebuildListener.SPACE);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.SPACE);
        }
    });
    t3.setDaemon(true);
    t3.setName("Rebuild space index");
    t3.start();

    Thread t4 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildUserIndex();
            listener.indexComplete(IndexRebuildListener.USER);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.USER);

        }
    });
    t4.setDaemon(true);
    t4.setName("Rebuild user index");
    t4.start();

    Thread t5 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildRoleIndex();
            listener.indexComplete(IndexRebuildListener.ROLE);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.ROLE);
        }
    });
    t5.setDaemon(true);
    t5.setName("Rebuild role index");
    t5.start();

    Thread t6 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildPageTagIndex();
            listener.indexComplete(IndexRebuildListener.PTAG);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.PTAG);
        }
    });
    t6.setDaemon(true);
    t6.setName("Rebuild page tag index");
    t6.start();

    Thread t7 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildSpaceTagIndex();
            listener.indexComplete(IndexRebuildListener.STAG);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.STAG);
        }
    });
    t7.setDaemon(true);
    t7.setName("Rebuild space tag index");
    t7.start();

    Thread t8 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildAttachmentIndex();
            listener.indexComplete(IndexRebuildListener.ATTACHMENT);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.ATTACHMENT);
        }
    });
    t8.setDaemon(true);
    t8.setName("Rebuild attachment index");
    t8.start();

    Thread t9 = new Thread(new Runnable() {
        public void run() {
            ((IndexServiceImpl) indexService).rebuildWidgetIndex();
            listener.indexComplete(IndexRebuildListener.WIDGET);

            //log activity
            logRebuildIndexEvent(uuid, IndexRebuildListener.WIDGET);
        }
    });
    t9.setDaemon(true);
    t9.setName("Rebuild widget index");
    t9.start();
}