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:io.webfolder.cdp.ChromiumDownloader.java

public Path download(ChromiumVersion version) {
    final Path destinationRoot = getChromiumPath(version);
    final Path executable = getExecutable(version);

    String url;/*from   w w w.j a v a2s  .c  o  m*/
    if (WINDOWS) {
        url = format("%s/Win_x64/%d/chrome-win.zip", DOWNLOAD_HOST, version.getRevision());
    } else if (LINUX) {
        url = format("%s/Linux_x64/%d/chrome-linux.zip", DOWNLOAD_HOST, version.getRevision());
    } else if (MAC) {
        url = format("%s/Mac/%d/chrome-mac.zip", DOWNLOAD_HOST, version.getRevision());
    } else {
        throw new CdpException("Unsupported OS found - " + OS);
    }

    try {
        URL u = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setRequestMethod("HEAD");
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        if (conn.getResponseCode() != 200) {
            throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage());
        }
        long contentLength = conn.getHeaderFieldLong("x-goog-stored-content-length", 0);
        String fileName = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")) + "-r"
                + version.getRevision() + ".zip";
        Path archive = get(getProperty("java.io.tmpdir")).resolve(fileName);
        if (exists(archive) && contentLength != size(archive)) {
            delete(archive);
        }
        if (!exists(archive)) {
            logger.info("Downloading Chromium [revision=" + version.getRevision() + "] 0%");
            u = new URL(url);
            if (conn.getResponseCode() != 200) {
                throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage());
            }
            conn = (HttpURLConnection) u.openConnection();
            conn.setConnectTimeout(TIMEOUT);
            conn.setReadTimeout(TIMEOUT);
            Thread thread = null;
            AtomicBoolean halt = new AtomicBoolean(false);
            Runnable progress = () -> {
                try {
                    long fileSize = size(archive);
                    logger.info("Downloading Chromium [revision={}] {}%", version.getRevision(),
                            round((fileSize * 100L) / contentLength));
                } catch (IOException e) {
                    // ignore
                }
            };
            try (InputStream is = conn.getInputStream()) {
                logger.info("Download location: " + archive.toString());
                thread = new Thread(() -> {
                    while (true) {
                        try {
                            if (halt.get()) {
                                break;
                            }
                            progress.run();
                            sleep(1000);
                        } catch (Throwable e) {
                            // ignore
                        }
                    }
                });
                thread.setName("cdp4j");
                thread.setDaemon(true);
                thread.start();
                copy(conn.getInputStream(), archive);
            } finally {
                if (thread != null) {
                    progress.run();
                    halt.set(true);
                }
            }
        }
        logger.info("Extracting to: " + destinationRoot.toString());
        if (exists(archive)) {
            createDirectories(destinationRoot);
            unpack(archive.toFile(), destinationRoot.toFile());
        }

        if (!exists(executable) || !isExecutable(executable)) {
            throw new CdpException("Chromium executable not found: " + executable.toString());
        }

        if (!WINDOWS) {
            Set<PosixFilePermission> permissions = getPosixFilePermissions(executable);
            if (!permissions.contains(OWNER_EXECUTE)) {
                permissions.add(OWNER_EXECUTE);
                setPosixFilePermissions(executable, permissions);
            }
            if (!permissions.contains(GROUP_EXECUTE)) {
                permissions.add(GROUP_EXECUTE);
                setPosixFilePermissions(executable, permissions);
            }
        }
    } catch (IOException e) {
        throw new CdpException(e);
    }
    return executable;
}

From source file:com.cinchapi.concourse.server.plugin.PluginManager.java

/**
 * Start a {@link Thread} that serves as an event loop; processing both
 * requests and responses {@code #fromPlugin}.
 * <p>/*w  ww  .  j  a  v  a  2  s  .co m*/
 * Requests are forked to a {@link RemoteInvocationThread} for processing.
 * </p>
 * <p>
 * Responses are placed on the appropriate
 * {@link PluginInfoColumn#FROM_PLUGIN_RESPONSES queue} and listeners are
 * notified.
 * </p>
 * 
 * @param id the plugin id
 * @return the event loop thread
 */
private Thread startEventLoop(String id) {
    final SharedMemory requests = (SharedMemory) router.get(id, PluginInfoColumn.FROM_PLUGIN);
    final SharedMemory responses = (SharedMemory) router.get(id, PluginInfoColumn.FROM_SERVER);
    final ConcurrentMap<AccessToken, RemoteMethodResponse> fromPluginResponses = (ConcurrentMap<AccessToken, RemoteMethodResponse>) router
            .get(id, PluginInfoColumn.FROM_PLUGIN_RESPONSES);
    Thread loop = new Thread(new Runnable() {

        @Override
        public void run() {
            ByteBuffer data;
            while ((data = requests.read()) != null) {
                Plugin.Instruction type = ByteBuffers.getEnum(data, Plugin.Instruction.class);
                data = ByteBuffers.getRemaining(data);
                if (type == Instruction.REQUEST) {
                    RemoteMethodRequest request = Serializables.read(data, RemoteMethodRequest.class);
                    new RemoteInvocationThread(request, requests, responses, this, true, fromPluginResponses)
                            .start();
                } else if (type == Instruction.RESPONSE) {
                    RemoteMethodResponse response = Serializables.read(data, RemoteMethodResponse.class);
                    ConcurrentMaps.putAndSignal(fromPluginResponses, response.creds, response);
                } else { // STOP
                    break;
                }
            }

        }

    });
    loop.setDaemon(true);
    loop.start();
    return loop;
}

From source file:com.saysth.commons.quartz.SchedulerFactoryBean.java

/**
 * Start the Quartz Scheduler, respecting the "startupDelay" setting.
 * //from ww  w . j  a v  a2  s  .c  om
 * @param scheduler
 *            the Scheduler to start
 * @param startupDelay
 *            the number of seconds to wait before starting the Scheduler
 *            asynchronously
 */
protected void startScheduler(final Scheduler scheduler, final int startupDelay) throws SchedulerException {
    if (startupDelay <= 0) {
        logger.info("Starting Quartz Scheduler now");
        scheduler.start();
    } else {
        if (logger.isInfoEnabled()) {
            logger.info("Will start Quartz Scheduler [" + scheduler.getSchedulerName() + "] in " + startupDelay
                    + " seconds");
        }
        Thread schedulerThread = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(startupDelay * 1000);
                } catch (InterruptedException ex) {
                    // simply proceed
                }
                if (logger.isInfoEnabled()) {
                    logger.info("Starting Quartz Scheduler now, after delay of " + startupDelay + " seconds");
                }
                try {
                    scheduler.start();
                } catch (SchedulerException ex) {
                    throw new SchedulingException("Could not start Quartz Scheduler after delay", ex);
                }
            }
        };
        schedulerThread.setName("Quartz Scheduler [" + scheduler.getSchedulerName() + "]");
        schedulerThread.setDaemon(true);
        schedulerThread.start();
    }
}

From source file:ml.shifu.shifu.core.dtrain.nn.NNOutput.java

@Override
public void postIteration(final MasterContext<NNParams, NNParams> context) {
    if (this.isDry) {
        // for dry mode, we don't save models files.
        return;/*from   ww w  . j  a  v a2s  .c  o  m*/
    }

    if (minimumEpochs < 0) {
        double minimumStepsRatio = DTrainUtils.getDouble(context.getProps(), // get # of steps to choose parameters
                CommonConstants.SHIFU_TRAIN_VAL_STEPS_RATIO, 0.1);
        minimumEpochs = (int) (modelConfig.getNumTrainEpochs() * minimumStepsRatio);
    }

    if (context.getCurrentIteration() < minimumEpochs) {
        this.optimizedWeights = context.getMasterResult().getWeights();
    } else {
        double currentError = ((modelConfig.getTrain().getValidSetRate() < EPSILON)
                ? context.getMasterResult().getTrainError()
                : context.getMasterResult().getTestError());
        if (currentError < this.minTestError) {
            this.minTestError = currentError;
            this.optimizedWeights = Arrays.copyOf(context.getMasterResult().getWeights(),
                    context.getMasterResult().getWeights().length);
            LOG.info("change minTestError to {}, and update best weights at {}-th epoch.", this.minTestError,
                    context.getCurrentIteration());
        }
    }

    // save tmp to hdfs according to raw trainer logic
    final int tmpModelFactor = DTrainUtils.tmpModelFactor(context.getTotalIteration());
    final int currentIteration = context.getCurrentIteration();
    final double[] weights = context.getMasterResult().getWeights();
    final int totalIteration = context.getTotalIteration();
    final boolean isHalt = context.getMasterResult().isHalt();
    // currentIteration - 1 because the first iteration is used for sync master models to workers
    if (currentIteration > 1 && (currentIteration - 1) % tmpModelFactor == 0) {
        Thread tmpNNThread = new Thread(new Runnable() {
            @Override
            public void run() {
                saveTmpNNToHDFS(currentIteration - 1, weights);
                // save model results for continue model training, if current job is failed, then next running
                // we can start from this point to save time.
                // another case for master recovery, if master is failed, read such checkpoint model
                Path out = new Path(context.getProps().getProperty(CommonConstants.GUAGUA_OUTPUT));

                // if current iteration is the last iteration, or it is halted by early stop condition, no need to
                // save checkpoint model here as it is replicated with postApplicaiton.
                // There is issue here if saving the same model in this thread and another thread in
                // postApplication, sometimes this conflict will cause model writing failed.
                if (!isHalt && currentIteration != totalIteration) {
                    writeModelWeightsToFileSystem(optimizedWeights, out, false);
                }
            }
        }, "saveTmpNNToHDFS thread");
        tmpNNThread.setDaemon(true);
        tmpNNThread.start();
    }

    updateProgressLog(context);
}

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

/**
 * Do checkpoint for master states, this is for master fail over
 *///w w  w.  j a  v a2  s .  c o m
private void doCheckPoint(final MasterContext<DTMasterParams, DTWorkerParams> context,
        final DTMasterParams masterParams, int iteration) {
    String intervalStr = context.getProps().getProperty(CommonConstants.SHIFU_TREE_CHECKPOINT_INTERVAL);
    int interval = 100;
    try {
        interval = Integer.parseInt(intervalStr);
    } catch (Exception ignore) {
    }

    // only do checkpoint in interval configured.
    if (iteration != 0 && iteration % interval != 0) {
        return;
    }

    LOG.info("Do checkpoint at hdfs file {} at iteration {}.", this.checkpointOutput, iteration);
    final Queue<TreeNode> finalTodoQueue = this.toDoQueue;
    final Queue<TreeNode> finalToSplitQueue = this.toSplitQueue;
    final boolean finalIsLeaf = this.isLeafWise;
    final List<TreeNode> finalTrees = this.trees;

    Thread cpPersistThread = new Thread(new Runnable() {
        @Override
        public void run() {
            long start = System.currentTimeMillis();
            writeStatesToHdfs(DTMaster.this.checkpointOutput, masterParams, finalTrees, finalIsLeaf,
                    finalTodoQueue, finalToSplitQueue);
            LOG.info("Do checkpoint in iteration {} with run time {}", context.getCurrentIteration(),
                    (System.currentTimeMillis() - start));
        }
    }, "Master checkpoint thread");
    cpPersistThread.setDaemon(true);
    cpPersistThread.start();
}

From source file:eu.stratosphere.pact.compiler.PactCompiler.java

private InstanceTypeDescription getInstanceTypeInfo() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Connecting compiler to JobManager to dertermine instance information.");
    }/*from  ww w .  j  av  a 2s.  c  o  m*/

    // create the connection in a separate thread, such that this thread
    // can abort, if an unsuccessful connection occurs.
    Map<InstanceType, InstanceTypeDescription> instances = null;

    JobManagerConnector jmc = new JobManagerConnector(this.jobManagerAddress);
    Thread connectorThread = new Thread(jmc, "Compiler - JobManager connector.");
    connectorThread.setDaemon(true);
    connectorThread.start();

    // connect and get the result
    try {
        jmc.waitForCompletion();
        instances = jmc.instances;
        if (instances == null) {
            throw new NullPointerException("Returned instance map is <null>");
        }
    } catch (Throwable t) {
        throw new CompilerException(
                "Available instances could not be determined from job manager: " + t.getMessage(), t);
    }

    // determine which type to run on
    return getType(instances);
}

From source file:eu.stratosphere.compiler.PactCompiler.java

private InstanceTypeDescription getInstanceTypeInfo() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Connecting compiler to JobManager to dertermine instance information.");
    }/*from  w w  w .  ja v  a 2s . co m*/

    // create the connection in a separate thread, such that this thread
    // can abort, if an unsuccessful connection occurs.
    Map<InstanceType, InstanceTypeDescription> instances = null;

    JobManagerConnector jmc = new JobManagerConnector(this.jobManagerAddress);
    Thread connectorThread = new Thread(jmc, "Compiler - JobManager connector.");
    connectorThread.setDaemon(true);
    connectorThread.start();

    // connect and get the result
    try {
        jmc.waitForCompletion();
        instances = jmc.instances;
        if (instances == null) {
            throw new NullPointerException("Returned instance map is <null>");
        }
    } catch (IOException e) {
        throw new CompilerException(e.getMessage());
    } catch (Throwable t) {
        throw new CompilerException("Cannot connect to the JobManager to determine the available TaskManagers. "
                + "Check if the JobManager is running (using the web interface or log files). Reason: "
                + t.getMessage(), t);
    }

    // determine which type to run on
    return getType(instances);
}

From source file:com.alibaba.wasp.master.AssignmentManager.java

/**
 * Get a named {@link java.util.concurrent.ThreadFactory} that just builds daemon threads
 *
 * @param prefix/*from w  w w .  java  2s  .  co m*/
 *          name prefix for all threads created from the factory
 * @return a thread factory that creates named, daemon threads
 */
private static ThreadFactory newDaemonThreadFactory(final String prefix) {
    final ThreadFactory namedFactory = Threads.getNamedThreadFactory(prefix);
    return new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = namedFactory.newThread(r);
            if (!t.isDaemon()) {
                t.setDaemon(true);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    };
}

From source file:net.dv8tion.jda.core.audio.AudioConnection.java

public void ready() {
    Thread readyThread = new Thread(threadIdentifier + " Ready Thread") {
        @Override/*from www . jav  a  2  s  . c  o  m*/
        public void run() {
            final long timeout = getGuild().getAudioManager().getConnectTimeout();

            JDAImpl api = (JDAImpl) getJDA();
            long started = System.currentTimeMillis();
            boolean connectionTimeout = false;
            while (!webSocket.isReady() && !connectionTimeout) {
                if (timeout > 0 && System.currentTimeMillis() - started > timeout) {
                    connectionTimeout = true;
                    break;
                }

                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    LOG.log(e);
                    Thread.currentThread().interrupt();
                }
            }
            if (!connectionTimeout) {
                AudioConnection.this.udpSocket = webSocket.getUdpSocket();

                setupSendSystem();
                setupReceiveSystem();
            } else {
                webSocket.close(ConnectionStatus.ERROR_CONNECTION_TIMEOUT);
            }
        }
    };
    readyThread.setDaemon(true);
    readyThread.start();
}

From source file:com.twinsoft.convertigo.eclipse.wizards.setup.SetupWizard.java

public void checkConnected(final CheckConnectedCallback callback) {
    Thread th = new Thread(new Runnable() {

        public void run() {
            synchronized (SetupWizard.this) {
                boolean isConnected = false;
                String message;/*from  www. j  a v a  2 s.c  o m*/

                try {
                    String[] urlSource = { "https://c8o.convertigo.net/cems/index.html" };

                    HttpClient client = prepareHttpClient(urlSource);
                    GetMethod method = new GetMethod(urlSource[0]);

                    int statusCode = client.executeMethod(method);
                    if (statusCode == HttpStatus.SC_OK) {
                        isConnected = true;
                        message = "You are currently online";
                    } else {
                        message = "Bad response: HTTP status " + statusCode;
                    }
                } catch (HttpException e) {
                    message = "HTTP failure: " + e.getMessage();
                } catch (IOException e) {
                    message = "IO failure: " + e.getMessage();
                } catch (Exception e) {
                    message = "Generic failure: " + e.getClass().getSimpleName() + ", " + e.getMessage();
                }

                callback.onCheckConnected(isConnected, message);
            }
        }

    });
    th.setDaemon(true);
    th.setName("SetupWizard.checkConnected");
    th.start();
}