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:org.dasein.cloud.tier3.APIHandler.java

public @Nonnull APIResponse get(final @Nonnull String operation, final @Nonnull String resource,
        final @Nullable String id, final @Nullable NameValuePair... parameters) {
    final APIResponse apiResponse = new APIResponse();

    Thread t = new Thread() {
        @Override//from  w  w  w.java2 s.c o m
        public void run() {
            try {
                APITrace.begin(provider, operation);
                try {
                    try {
                        get(apiResponse, null, 1, resource, id, parameters);
                    } catch (Throwable t) {
                        apiResponse.receive(new CloudException(t));
                    }
                } finally {
                    APITrace.end();
                }
            } finally {
                provider.release();
            }
        }
    };

    t.setName(operation);
    t.setDaemon(true);

    provider.hold();
    t.start();
    return apiResponse;
}

From source file:com.chiralBehaviors.autoconfigure.AutoConfigure.java

/**
 * Reestablish the configuration/* w  ww. j  a  v a2 s  .c  om*/
 */
private void restart(final AutoConfigureService configuredService) {
    restart();
    Thread startup = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                configuredService.succeed(generatedConfigurations);
            } catch (Exception e) {
                logger.error("Failed to restart the service", e);
                try {
                    configuredService.fail(generatedConfigurations);
                } catch (Exception e1) {
                    logger.error("Exception encountered during the running failure action", e1);
                }
            }
        }
    });
    startup.setDaemon(true);
    startup.start();
}

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

private void oneClickDoAll() {
    try {//from  ww w.  j  a  v a  2 s .  c o m
        Log.Setting.NORMAL.apply();
        //1.---------------------------------------------------
        final JdbcFastQuery exe1 = new JdbcFastQuery();
        JdbcFastQuery.debugMode = isDebug.isSelected();
        exe1.setOut(JCommonUtil.getNewPrintStream2JTextArea(logArea, 500, true));
        //2.---------------------------------------------------
        final LoadToDBAndWriteFile exe2 = new LoadToDBAndWriteFile();
        if (StringUtils.isNotBlank(xmlFileText.getText())) {
            File file = new File(xmlFileText.getText());
            if (file.exists()) {
                exe2.bulkTxt = file;
            }
        } else if (getBulkFile() != null) {
            xmlFileText.setText(getBulkFile().getAbsolutePath());
        }
        exe2.setOut(JCommonUtil.getNewPrintStream2JTextArea(logArea, 500, true));
        //3.---------------------------------------------------
        File file = JCommonUtil.filePathCheck(srcDirText.getText(), "", true);
        final Rcdf002eExcelMaker exe3 = new Rcdf002eExcelMaker();
        exe3.setBaseDir(file);
        Log.Setting.NORMAL.apply();
        exe3.setOut(JCommonUtil.getNewPrintStream2JTextArea(logArea, 500, true));
        //---------------------------------------------------
        Thread thread = new Thread(Thread.currentThread().getThreadGroup(), new Runnable() {
            @Override
            public void run() {
                try {
                    long current = System.currentTimeMillis();
                    setTitle("[1xml].......");
                    exe1.execute();
                    xmlFileText.setText(getBulkFile().getAbsolutePath());
                    setTitle("[2].......");
                    exe2.execute();
                    setTitle("[3excel].......");
                    exe3.execute();
                    current = System.currentTimeMillis() - current;
                    setTitle("?!!,:" + current);
                } catch (Exception ex) {
                    JCommonUtil.handleException(ex);
                    setTitle("......" + ex.getMessage());
                }
            }
        }, "xxxxxxxxxxxxxxxxxcxccx");
        thread.setDaemon(true);
        thread.start();
    } catch (Exception ex) {
        JCommonUtil.handleException(ex);
        setTitle("......" + ex.getMessage());
    }
}

From source file:org.dasein.cloud.skeleton.RESTMethod.java

public @Nonnull APIResponse get(final @Nonnull String operation, final @Nonnull String resource,
        final @Nullable String id, final @Nullable NameValuePair... parameters) {
    final APIResponse response = new APIResponse();

    Thread t = new Thread() {
        public void run() {
            try {
                APITrace.begin(provider, operation);
                try {
                    try {
                        get(response, null, 1, resource, id, parameters);
                    } catch (Throwable t) {
                        response.receive(new CloudException(t));
                    }//from ww w. jav a  2s. co m
                } finally {
                    APITrace.end();
                }
            } finally {
                provider.release();
            }
        }
    };

    t.setName(operation);
    t.setDaemon(true);

    provider.hold();
    t.start();
    return response;
}

From source file:io.apiman.manager.api.war.WarApiManagerBootstrapperServlet.java

/**
 * @see javax.servlet.GenericServlet#init()
 *//*ww w .  j  a v  a 2s  . c o  m*/
@Override
public void init() throws ServletException {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            // Wait 5s before doing this - hopefully dependencies will have started up by then
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e1) {
            }
            File dataDir = getDataDir();
            if (dataDir != null && dataDir.isDirectory()) {
                logger.debug("Checking for bootstrap files in " + dataDir); //$NON-NLS-1$
                Collection<File> files = FileUtils.listFiles(dataDir, new String[] { "json" }, false); //$NON-NLS-1$
                TreeSet<File> sortedFiles = new TreeSet<>(files);
                for (File file : sortedFiles) {
                    File alreadyProcessed = new File(file.getAbsolutePath() + ".imported"); //$NON-NLS-1$
                    if (!alreadyProcessed.isFile()) {
                        doImport(file);
                        try {
                            FileUtils.touch(alreadyProcessed);
                        } catch (IOException e) {
                        }
                    } else {
                        logger.debug("Skipping (already processed) file: " + file); //$NON-NLS-1$
                    }
                }
            }
        }
    });
    t.setDaemon(true);
    t.start();
}

From source file:ml.shifu.shifu.core.dtrain.dt.DTMaster.java

@Override
public DTMasterParams doCompute(MasterContext<DTMasterParams, DTWorkerParams> context) {
    if (context.isFirstIteration()) {
        return buildInitialMasterParams();
    }// w ww.java 2s  .  c o  m

    if (this.cpMasterParams != null) {
        DTMasterParams tmpMasterParams = rebuildRecoverMasterResultDepthList();
        // set it to null to avoid send it in next iteration
        this.cpMasterParams = null;
        if (this.isGBDT) {
            // don't need to send full trees because worker will get existing models from HDFS
            // only set last tree to do node stats, no need check switch to next tree because of message may be send
            // to worker already
            tmpMasterParams.setTrees(trees.subList(trees.size() - 1, trees.size()));
            // set tmp trees for DTOutput
            tmpMasterParams.setTmpTrees(this.trees);
        }
        return tmpMasterParams;
    }

    boolean isFirst = false;
    Map<Integer, NodeStats> nodeStatsMap = null;
    double trainError = 0d, validationError = 0d;
    double weightedTrainCount = 0d, weightedValidationCount = 0d;
    for (DTWorkerParams params : context.getWorkerResults()) {
        if (!isFirst) {
            isFirst = true;
            nodeStatsMap = params.getNodeStatsMap();
        } else {
            Map<Integer, NodeStats> currNodeStatsmap = params.getNodeStatsMap();
            for (Entry<Integer, NodeStats> entry : nodeStatsMap.entrySet()) {
                NodeStats resultNodeStats = entry.getValue();
                mergeNodeStats(resultNodeStats, currNodeStatsmap.get(entry.getKey()));
            }
            // set to null after merging, release memory at the earliest stage
            params.setNodeStatsMap(null);
        }
        trainError += params.getTrainError();
        validationError += params.getValidationError();
        weightedTrainCount += params.getTrainCount();
        weightedValidationCount += params.getValidationCount();
    }
    for (Entry<Integer, NodeStats> entry : nodeStatsMap.entrySet()) {
        NodeStats nodeStats = entry.getValue();
        int treeId = nodeStats.getTreeId();
        Node doneNode = Node.getNode(trees.get(treeId).getNode(), nodeStats.getNodeId());
        // doneNode, NodeStats
        Map<Integer, double[]> statistics = nodeStats.getFeatureStatistics();

        List<GainInfo> gainList = new ArrayList<GainInfo>();
        for (Entry<Integer, double[]> gainEntry : statistics.entrySet()) {
            int columnNum = gainEntry.getKey();
            ColumnConfig config = this.columnConfigList.get(columnNum);
            double[] statsArray = gainEntry.getValue();
            GainInfo gainInfo = this.impurity.computeImpurity(statsArray, config);
            if (gainInfo != null) {
                gainList.add(gainInfo);
            }
        }

        GainInfo maxGainInfo = GainInfo.getGainInfoByMaxGain(gainList);
        if (maxGainInfo == null) {
            // null gain info, set to leaf and continue next stats
            doneNode.setLeaf(true);
            continue;
        }
        populateGainInfoToNode(treeId, doneNode, maxGainInfo);

        if (this.isLeafWise) {
            boolean isNotSplit = maxGainInfo.getGain() <= 0d;
            if (!isNotSplit) {
                this.toSplitQueue.offer(new TreeNode(treeId, doneNode));
            } else {
                LOG.info("Node {} in tree {} is not to be split", doneNode.getId(), treeId);
            }
        } else {
            boolean isLeaf = maxGainInfo.getGain() <= 0d
                    || Node.indexToLevel(doneNode.getId()) == this.maxDepth;
            doneNode.setLeaf(isLeaf);
            // level-wise is to split node when stats is ready
            splitNodeForLevelWisedTree(isLeaf, treeId, doneNode);
        }
    }

    if (this.isLeafWise) {
        // get node in toSplitQueue and split
        int currSplitIndex = 0;
        while (!toSplitQueue.isEmpty() && currSplitIndex < this.maxBatchSplitSize) {
            TreeNode treeNode = this.toSplitQueue.poll();
            splitNodeForLeafWisedTree(treeNode.getTreeId(), treeNode.getNode());
        }
    }

    Map<Integer, TreeNode> todoNodes = new HashMap<Integer, TreeNode>();
    double averageValidationError = validationError / weightedValidationCount;
    if (this.isGBDT && this.dtEarlyStopDecider != null && averageValidationError > 0) {
        this.dtEarlyStopDecider.add(averageValidationError);
        averageValidationError = this.dtEarlyStopDecider.getCurrentAverageValue();
    }

    boolean vtTriggered = false;
    // if validationTolerance == 0d, means vt check is not enabled
    if (validationTolerance > 0d
            && Math.abs(this.bestValidationError - averageValidationError) < this.validationTolerance
                    * averageValidationError) {
        LOG.debug("Debug: bestValidationError {}, averageValidationError {}, validationTolerance {}",
                bestValidationError, averageValidationError, validationTolerance);
        vtTriggered = true;
    }

    if (averageValidationError < this.bestValidationError) {
        this.bestValidationError = averageValidationError;
    }

    // validation error is averageValidationError * weightedValidationCount because of here averageValidationError
    // is divided by validation count.
    DTMasterParams masterParams = new DTMasterParams(weightedTrainCount, trainError, weightedValidationCount,
            averageValidationError * weightedValidationCount);

    if (toDoQueue.isEmpty()) {
        if (this.isGBDT) {
            TreeNode treeNode = this.trees.get(this.trees.size() - 1);
            Node node = treeNode.getNode();
            if (this.trees.size() >= this.treeNum) {
                // if all trees including trees read from existing model over treeNum, stop the whole process.
                masterParams.setHalt(true);
                LOG.info("Queue is empty, training is stopped in iteration {}.", context.getCurrentIteration());
            } else if (node.getLeft() == null && node.getRight() == null) {
                // if very good performance, here can be some issues, say you'd like to get 5 trees, but in the 2nd
                // tree, you get one perfect tree, no need continue but warn users about such issue: set
                // BaggingSampleRate not to 1 can solve such issue to avoid overfit
                masterParams.setHalt(true);
                LOG.warn(
                        "Tree is learned 100% well, there must be overfit here, please tune BaggingSampleRate, training is stopped in iteration {}.",
                        context.getCurrentIteration());
            } else if (this.dtEarlyStopDecider != null
                    && (this.enableEarlyStop && this.dtEarlyStopDecider.canStop())) {
                masterParams.setHalt(true);
                LOG.info("Early stop identified, training is stopped in iteration {}.",
                        context.getCurrentIteration());
            } else if (vtTriggered) {
                LOG.info("Early stop training by validation tolerance.");
                masterParams.setHalt(true);
            } else {
                // set first tree to true even after ROOT node is set in next tree
                masterParams.setFirstTree(this.trees.size() == 1);
                // finish current tree, no need features information
                treeNode.setFeatures(null);
                TreeNode newRootNode = new TreeNode(this.trees.size(), new Node(Node.ROOT_INDEX),
                        this.learningRate);
                LOG.info("The {} tree is to be built.", this.trees.size());
                this.trees.add(newRootNode);
                newRootNode.setFeatures(
                        getSubsamplingFeatures(this.featureSubsetStrategy, this.featureSubsetRate));
                // only one node
                todoNodes.put(0, newRootNode);
                masterParams.setTodoNodes(todoNodes);
                // set switch flag
                masterParams.setSwitchToNextTree(true);
            }
        } else {
            // for rf
            masterParams.setHalt(true);
            LOG.info("Queue is empty, training is stopped in iteration {}.", context.getCurrentIteration());
        }
    } else {
        int nodeIndexInGroup = 0;
        long currMem = 0L;
        List<Integer> depthList = new ArrayList<Integer>();
        if (this.isGBDT) {
            depthList.add(-1);
        }

        if (isRF) {
            for (int i = 0; i < this.trees.size(); i++) {
                depthList.add(-1);
            }
        }

        while (!toDoQueue.isEmpty() && currMem <= this.maxStatsMemory) {
            TreeNode node = this.toDoQueue.poll();
            int treeId = node.getTreeId();
            int oldDepth = this.isGBDT ? depthList.get(0) : depthList.get(treeId);
            int currDepth = Node.indexToLevel(node.getNode().getId());
            if (currDepth > oldDepth) {
                if (this.isGBDT) {
                    // gbdt only for last depth
                    depthList.set(0, currDepth);
                } else {
                    depthList.set(treeId, currDepth);
                }
            }

            List<Integer> subsetFeatures = getSubsamplingFeatures(this.featureSubsetStrategy,
                    this.featureSubsetRate);
            node.setFeatures(subsetFeatures);
            currMem += getStatsMem(subsetFeatures);
            todoNodes.put(nodeIndexInGroup, node);
            nodeIndexInGroup += 1;
        }
        masterParams.setTreeDepth(depthList);
        masterParams.setTodoNodes(todoNodes);
        masterParams.setSwitchToNextTree(false);
        masterParams.setContinuousRunningStart(false);
        masterParams.setFirstTree(this.trees.size() == 1);
        LOG.info("Todo node size is {}", todoNodes.size());
    }

    if (this.isGBDT) {
        if (masterParams.isSwitchToNextTree()) {
            // send last full growth tree and current todo ROOT node tree
            masterParams.setTrees(trees.subList(trees.size() - 2, trees.size()));
        } else {
            // only send current trees
            masterParams.setTrees(trees.subList(trees.size() - 1, trees.size()));
        }
    }

    if (this.isRF) {
        // for rf, reset trees sent to workers for only trees with todo nodes, this saves message space. While
        // elements in todoTrees are also the same reference in this.trees, reuse the same object to save memory.
        if (masterParams.getTreeDepth().size() == this.trees.size()) {
            // if normal iteration
            List<TreeNode> todoTrees = new ArrayList<TreeNode>();
            for (int i = 0; i < trees.size(); i++) {
                if (masterParams.getTreeDepth().get(i) >= 0) {
                    // such tree in current iteration treeDepth is not -1, add it to todoTrees.
                    todoTrees.add(trees.get(i));
                } else {
                    // mock a TreeNode instance to make sure no surprise in further serialization. In fact
                    // meaningless.
                    todoTrees.add(new TreeNode(i, new Node(Node.INVALID_INDEX), 1d));
                }
            }
            masterParams.setTrees(todoTrees);
        } else {
            // if last iteration without maxDepthList
            masterParams.setTrees(trees);
        }
    }
    if (this.isGBDT) {
        // set tmp trees to DTOutput
        masterParams.setTmpTrees(this.trees);
    }

    if (context.getCurrentIteration() % 100 == 0) {
        // every 100 iterations do gc explicitly to avoid one case:
        // mapper memory is 2048M and final in our cluster, if -Xmx is 2G, then occasionally oom issue.
        // to fix this issue: 1. set -Xmx to 1800m; 2. call gc to drop unused memory at early stage.
        // this is ugly and if it is stable with 1800m, this line should be removed
        Thread gcThread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.gc();
            }
        });
        gcThread.setDaemon(true);
        gcThread.start();
    }

    // before master result, do checkpoint according to n iteration set by user
    doCheckPoint(context, masterParams, context.getCurrentIteration());

    LOG.debug("weightedTrainCount {}, weightedValidationCount {}, trainError {}, validationError {}",
            weightedTrainCount, weightedValidationCount, trainError, validationError);
    return masterParams;
}

From source file:com.cyberway.issue.crawler.Heritrix.java

protected static Thread getShutdownThread(final boolean sysexit, final int exitCode, final String name) {
    Thread t = new Thread(name) {
        public void run() {
            Heritrix.prepareHeritrixShutDown();
            if (sysexit) {
                Heritrix.performHeritrixShutDown(exitCode);
            }//w  w w. j  a va  2 s . co  m
        }
    };
    t.setDaemon(true);
    return t;
}

From source file:com.googlecode.jsonrpc4j.JsonRpcHttpAsyncClient.java

private void initialize() {
    if (initialized.getAndSet(true)) {
        return;/*www.  ja v a  2 s .c o  m*/
    }

    // HTTP parameters for the client
    final HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
            Integer.getInteger("com.googlecode.jsonrpc4j.async.socket.timeout", 30000));
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
            Integer.getInteger("com.googlecode.jsonrpc4j.async.connect.timeout", 30000));
    params.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,
            Integer.getInteger("com.googlecode.jsonrpc4j.async.socket.buffer", 8 * 1024));
    params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,
            Boolean.valueOf(System.getProperty("com.googlecode.jsonrpc4j.async.tcp.nodelay", "true")));
    params.setParameter(CoreProtocolPNames.USER_AGENT, "jsonrpc4j/1.0");

    // Create client-side I/O reactor
    final ConnectingIOReactor ioReactor;
    try {
        IOReactorConfig config = new IOReactorConfig();
        config.setIoThreadCount(Integer.getInteger("com.googlecode.jsonrpc4j.async.reactor.threads", 1));
        ioReactor = new DefaultConnectingIOReactor(config);
    } catch (IOReactorException e) {
        throw new RuntimeException("Exception initializing asynchronous Apache HTTP Client", e);
    }

    // Create a default SSLSetupHandler that accepts any certificate
    if (sslContext == null) {
        try {
            sslContext = SSLContext.getDefault();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // Create HTTP connection pool
    BasicNIOConnFactory nioConnFactory = new BasicNIOConnFactory(sslContext, null, params);
    pool = new BasicNIOConnPool(ioReactor, nioConnFactory, params);
    // Limit total number of connections to 500 by default
    pool.setDefaultMaxPerRoute(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.route", 500));
    pool.setMaxTotal(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.total", 500));

    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                // Create client-side HTTP protocol handler
                HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
                // Create client-side I/O event dispatch
                IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, sslContext,
                        params);
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
        }

    }, "jsonrpc4j HTTP IOReactor");
    // Start the client thread
    t.setDaemon(true);
    t.start();

    // Create HTTP protocol processing chain
    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Use standard client-side protocol interceptors
            new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(),
            new RequestExpectContinue() });

    // Create HTTP requester
    requester = new HttpAsyncRequester(httpproc, new DefaultConnectionReuseStrategy(), params);
}

From source file:com.hellblazer.autoconfigure.AutoConfigure.java

/**
 * Reestablish the configuration/*from w w w . ja va  2  s  .  c o  m*/
 */
private void restart(final AutoConfigureService configuredService) {
    restart();
    Thread startup = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                jmxDiscovery.start(bound.get().getAddress());
                configuredService.succeed(generatedConfigurations);
            } catch (Exception e) {
                logger.error("Failed to restart the service", e);
                try {
                    configuredService.fail(generatedConfigurations);
                } catch (Exception e1) {
                    logger.error("Exception encountered during the running failure action", e1);
                }
            }
        }
    });
    startup.setDaemon(true);
    startup.start();
}

From source file:org.apache.nifi.remote.util.SiteToSiteRestApiClient.java

public SiteToSiteRestApiClient(final SSLContext sslContext, final HttpProxy proxy,
        final EventReporter eventReporter) {
    this.sslContext = sslContext;
    this.proxy = proxy;
    this.eventReporter = eventReporter;

    ttlExtendTaskExecutor = Executors.newScheduledThreadPool(1, new ThreadFactory() {
        private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();

        @Override//from w  w w .j  a  va2 s .co m
        public Thread newThread(final Runnable r) {
            final Thread thread = defaultFactory.newThread(r);
            thread.setName(Thread.currentThread().getName() + " TTLExtend");
            thread.setDaemon(true);
            return thread;
        }
    });
}