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.gaeproxy.GAEProxyService.java

/** Called when the activity is first created. */
public boolean handleConnection() {

    if (proxyType.equals("GAE")) {
        appHost = parseHost("g.maxcdn.info", true);
        if (appHost == null || appHost.equals("") || isInBlackList(appHost)) {
            appHost = settings.getString("appHost", DEFAULT_HOST);
        }/*from  www .j a v a 2 s. co  m*/
    } else if (proxyType.equals("PaaS")) {
        appHost = parseHost(appId, false);
        if (appHost == null || appHost.equals("") || isInBlackList(appHost)) {
            return false;
        }
    }

    videoHost = parseHost("v.maxcdn.info", true);
    if (videoHost == null || videoHost.equals("") || isInBlackList(videoHost)) {
        videoHost = settings.getString("videoHost", VIDEO_HOST);
    }

    handler.sendEmptyMessage(MSG_HOST_CHANGE);

    dnsHost = parseHost("myhosts.sinaapp.com", false);
    if (dnsHost == null || dnsHost.equals("") || isInBlackList(appHost)) {
        dnsHost = DEFAULT_DNS;
    }

    try {
        String[] hosts = dnsHost.split("\\|");
        dnsHost = hosts[hosts.length - 1];
        appMask = appHost.split("\\|");
        videoMask = videoHost.split("\\|");
    } catch (Exception ex) {
        return false;
    }

    if (!isGlobalProxy) {
        if (mProxiedApps == null) {
            mProxiedApps = App.getProxiedApps(this);
        }
    }

    // DNS Proxy Setup
    // with AsyncHttpClient
    if ("PaaS".equals(proxyType)) {
        Pair<String, String> orgHost = new Pair<String, String>(appId, appMask[0]);
        dnsServer = new DNSServer(this, dnsHost, orgHost);
    } else if ("GAE".equals(proxyType)) {
        dnsServer = new DNSServer(this, dnsHost, null);
    }
    dnsPort = dnsServer.getServPort();

    // Random mirror for load balance
    // only affect when appid equals proxyofmax
    if (appId.equals("proxyofmax")) {
        appId = new String(Base64.decodeBase64(getString(R.string.mirror_list).getBytes()));
        appPath = getString(R.string.mirror_path);
        sitekey = getString(R.string.mirror_sitekey);
    }

    if (!preConnection())
        return false;

    Thread dnsThread = new Thread(dnsServer);
    dnsThread.setDaemon(true);
    dnsThread.start();

    connect();
    flushDNS();

    return true;
}

From source file:com.tascape.qa.th.Utils.java

public static Process cmd(String[] commands, final File file, final File workingDir,
        final String... ignoreRegex) throws IOException {
    FileUtils.touch(file);//from w w  w .  j a  v a2 s . c  o m
    LOG.debug("Saving console output to {}", file.getAbsolutePath());

    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.redirectErrorStream(true);
    pb.directory(workingDir);
    LOG.info("Running command {}:  {}", workingDir == null ? "" : workingDir.getAbsolutePath(),
            pb.command().toString().replaceAll(",", ""));
    final Process p = pb.start();

    Thread t = new Thread(Thread.currentThread().getName() + "-" + p.hashCode()) {
        @Override
        public void run() {
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String console = "console-" + stdIn.hashCode();
            try (PrintWriter pw = new PrintWriter(file)) {
                for (String line = stdIn.readLine(); line != null;) {
                    LOG.trace("{}: {}", console, line);
                    if (null == ignoreRegex || ignoreRegex.length == 0) {
                        pw.println(line);
                    } else {
                        boolean ignore = false;
                        for (String regex : ignoreRegex) {
                            if (!regex.isEmpty() && (line.contains(regex) || line.matches(regex))) {
                                ignore = true;
                                break;
                            }
                        }
                        if (!ignore) {
                            pw.println(line);
                        }
                    }
                    pw.flush();
                    line = stdIn.readLine();
                }
            } catch (IOException ex) {
                LOG.warn(ex.getMessage());
            }
            LOG.trace("command is done");
        }
    };
    t.setDaemon(true);
    t.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            if (p != null) {
                p.destroy();
            }
        }
    });
    return p;
}

From source file:edu.umd.lib.servlets.permissions.PermissionsServlet.java

@Override
public void destroy() {
    // close repository
    log.info("Closing repository.");
    if (repository != null) {
        repository.close();/*from   w w  w  . j a  v a  2 s.  c  om*/
        repository = null;
    }

    // done
    log.info("Repository closed.");

    if (startRemoteServer) {
        // unbinding from registry
        String name = null;
        try {
            name = new RepositoryUrl(bindingAddress).getName();
            log.info("Unbinding '" + name + "' from registry.");
            registry.unbind(name);
        } catch (RemoteException e) {
            log.error("Error during unbinding '" + name + "': " + e.getMessage());
        } catch (NotBoundException e) {
            log.error("Error during unbinding '" + name + "': " + e.getMessage());
        } catch (MalformedURLException e) {
            log.error("MalformedURLException while parsing '" + bindingAddress + "': " + e.getMessage());
        }

        // unexporting from registry
        try {
            log.info("Unexporting rmi repository: " + bindingAddress);
            UnicastRemoteObject.unexportObject(rmiRepository, true);
        } catch (NoSuchObjectException e) {
            log.error("Error during rmi shutdown for address: " + bindingAddress, e);
        }

        // shutdown registry
        if (registryIsEmbedded) {
            try {
                log.info("Closing rmiregistry: " + bindingAddress);
                UnicastRemoteObject.unexportObject(registry, true);
            } catch (NoSuchObjectException e) {
                log.error("Error during rmi shutdown for address: " + bindingAddress, e);
            }
        }

        // force the distributed GC to fire, otherwise in tomcat with embedded
        // rmi registry the process won't end
        // this procedure is necessary specifically for Tomcat
        log.info("Repository terminated, waiting for garbage to clear");
        Thread garbageClearThread = new Thread("garbage clearer") {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    try {
                        Thread.sleep(3000);
                        System.gc();
                    } catch (InterruptedException ignored) {
                    }
                }
            }
        };
        garbageClearThread.setDaemon(true);
        garbageClearThread.start();

    }

    if (repositoryService != null) {
        HippoServiceRegistry.unregisterService(repositoryService, RepositoryService.class);
    }
    if (repositoryClusterService != null) {
        HippoServiceRegistry.unregisterService(repositoryClusterService, RepositoryClusterService.class);
    }
}

From source file:eu.tango.energymodeller.datastore.DataGatherer.java

@Override
public void run() {
    if (logVmsToDisk && performDataGathering) {
        vmUsageLogger = new VmEnergyUsageLogger(new File(loggerOutputFile), true);
        vmUsageLogger.setConsiderIdleEnergy(loggerConsiderIdleEnergy);
        Thread vmUsageLoggerThread = new Thread(vmUsageLogger);
        vmUsageLoggerThread.setDaemon(true);
        vmUsageLoggerThread.start();/* ww  w .  ja  v a2  s .c o m*/
    }
    if (logAppsToDisk && performDataGathering) {
        appUsageLogger = new ApplicationEnergyUsageLogger(new File(appLoggerOutputFile), true);
        appUsageLogger.setConsiderIdleEnergy(loggerConsiderIdleEnergy);
        Thread appUsageLoggerThread = new Thread(appUsageLogger);
        appUsageLoggerThread.setDaemon(true);
        appUsageLoggerThread.start();
    }
    /**
     * Polls the data source and write values to the database.
     */
    while (running) {
        try {
            Logger.getLogger(DataGatherer.class.getName()).log(Level.FINE,
                    "Data gatherer: Obtaining online host and vm list");
            List<EnergyUsageSource> energyConsumers = datasource.getHostAndVmList();
            List<Host> hostList = getHostList(energyConsumers);
            refreshKnownHostList(hostList);
            List<GeneralPurposePowerConsumer> generalPurposeList = datasource.getGeneralPowerConsumerList();
            refreshKnownGeneralPurposeNodesList(generalPurposeList);
            List<VmDeployed> vmList = getVMList(energyConsumers);
            refreshKnownVMList(vmList);
            Logger.getLogger(DataGatherer.class.getName()).log(Level.FINE,
                    "Data gatherer: Obtaining specific host information");
            List<HostMeasurement> measurements = datasource.getHostData(hostList);
            List<HostMeasurement> generalNodeMeasurements = datasource.getHostData(
                    GeneralPurposePowerConsumer.generalPurposeHostListToHostList(generalPurposeList));
            for (HostMeasurement measurement : measurements) {
                Host host = knownHosts.get(measurement.getHost().getHostName());
                /**
                 * This ensures all the calibration data is available, by
                 * setting the host from the cached data. HostList
                 * originates from the data source and not from the
                 * database/cache, which includes information such as idle
                 * energy usage.
                 */
                measurement.setHost(host);
                /**
                 * Update only if a value has not been provided before or
                 * the timestamp value has changed. This keeps the data
                 * written to backing store as clean as possible.
                 */
                if (performDataGathering) {
                    gatherMeasurements(host, measurement,
                            getGeneralPurposeHostsPowerConsumption(generalNodeMeasurements), vmList);
                }
            }
            try {
                //Note: The Zabbix API takes a few seconds to call, so don't call it faster than 3-4 seconds
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(DataGatherer.class.getName()).log(Level.SEVERE,
                        "The data gatherer was interupted.", ex);
            }
            faultCount = (faultCount > 0 ? faultCount - 1 : 0);
        } catch (Exception ex) { //This should always try to gather data from the data source.
            faultCount = faultCount + 1;
            Logger.getLogger(DataGatherer.class.getName()).log(Level.SEVERE,
                    "The data gatherer encountered a fault, Fault Number:" + faultCount, ex);
            if (faultCount > 100) {
                Logger.getLogger(DataGatherer.class.getName()).log(Level.SEVERE,
                        "Many faults were seen in a row the energy modeller is now pausing from gathering data.");
                faultCount = 0;
                try {
                    Thread.sleep(TimeUnit.MINUTES.toMillis(5));
                } catch (InterruptedException e) {
                    Logger.getLogger(DataGatherer.class.getName()).log(Level.SEVERE,
                            "The data gatherer was interupted.", ex);
                }
            }
        }
    }
}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java

protected long runWithTimeout(MutationTestRunnable r) {
    long[] preIds = threadMxBean.getAllThreadIds();
    FutureTask<Object> future = new FutureTask<Object>(Executors.callable(r));
    Thread thread = new Thread(future);
    thread.setDaemon(true);
    logger.debug("Start  test: ");
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();/*from w w  w  .ja  v  a 2  s. c  om*/
    thread.start();
    String exceptionMessage = null;
    Throwable capturedThrowable = null;
    try {
        future.get(timeout, TimeUnit.SECONDS);
        logger.debug("Second timeout");
    } catch (InterruptedException e) {
        capturedThrowable = e;
    } catch (ExecutionException e) {
        capturedThrowable = e;
    } catch (TimeoutException e) {
        exceptionMessage = JavalancheMessages.MUTATION_TIME_LIMIT_MESSAGE + "Mutation causes test timeout";
        capturedThrowable = e;
    } catch (Throwable t) {
        capturedThrowable = t;
    } finally {
        if (capturedThrowable != null) {
            if (exceptionMessage == null) {
                exceptionMessage = "Exception caught during test execution.";
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            capturedThrowable.printStackTrace(new PrintStream(out));
            logger.debug(
                    "Setting test failed. Message: " + exceptionMessage + " Exception " + capturedThrowable);
            r.setFailed(exceptionMessage, capturedThrowable);
        }
    }
    if (!future.isDone()) {
        r.setFailed(JavalancheMessages.MUTATION_TIME_LIMIT_MESSAGE
                + "Mutated Thread is still running after timeout.", null);
        switchOfMutation(future);
    }
    stopWatch.stop();
    if (!checkAllFinished(preIds)) {
        if (configuration.useThreadStop()) {
            stopThreads(preIds);
        } else {
            shutDown(r, stopWatch);
        }
    }
    logger.debug("End timed test, it took " + stopWatch.getTime() + " ms");
    return stopWatch.getTime();
}

From source file:eu.tango.energymodeller.datasourceclient.SlurmDataSourceAdaptor.java

/**
 * This is the generic startup code for the Slurm data source adaptor
 *
 * @param interval The interval at which to take logging data.
 *//* www. jav  a2 s  . co m*/
public final void startup(int interval) {
    String filename = settings.getString("energy.modeller.slurm.scrape.file", "slurm-host-data.log");
    boolean useFileScraper = settings.getBoolean("energy.modeller.slurm.scrape.from.file", false);
    if (useFileScraper) {
        File scrapeFile = new File(filename);
        fileTailer = new SlurmDataSourceAdaptor.SlurmTailer();
        tailer = Tailer.create(scrapeFile, fileTailer, (interval * 1000) / 16, true);
        Thread tailerThread = new Thread(tailer);
        tailerThread.setDaemon(true);
        tailerThread.start();
        System.out.println("Scraping from Slurm output file");
    } else {
        //Parse directly from SLURM
        String hostsList = settings.getString("energy.modeller.slurm.hosts", "ns[52-53]");
        poller = new SlurmPoller(hostsList, interval);
        Thread pollerThread = new Thread(poller);
        pollerThread.setDaemon(true);
        pollerThread.start();
        System.out.println("Reading from SLURM directly");
    }
    if (settings.isChanged()) {
        settings.save("energy-modeller-slurm-config.properties");
    }
}

From source file:com.twitter.common.zookeeper.ZooKeeperClient.java

/**
 * Creates an unconnected client that will lazily attempt to connect on the first call to
 * {@link #get}.  All successful connections will be authenticated with the given
 * {@code credentials}.//from ww  w.ja v  a 2 s  .  c o  m
 *
 * @param sessionTimeout the ZK session timeout
 * @param credentials the credentials to authenticate with
 * @param chrootPath an optional chroot path
 * @param zooKeeperServers the set of servers forming the ZK cluster
 */
public ZooKeeperClient(Amount<Integer, Time> sessionTimeout, Credentials credentials,
        Optional<String> chrootPath, Iterable<InetSocketAddress> zooKeeperServers) {
    this.sessionTimeoutMs = Preconditions.checkNotNull(sessionTimeout).as(Time.MILLISECONDS);
    this.credentials = Preconditions.checkNotNull(credentials);

    if (chrootPath.isPresent()) {
        PathUtils.validatePath(chrootPath.get());
    }

    Preconditions.checkNotNull(zooKeeperServers);
    Preconditions.checkArgument(!Iterables.isEmpty(zooKeeperServers), "Must present at least 1 ZK server");

    Thread watcherProcessor = new Thread("ZookeeperClient-watcherProcessor") {
        @Override
        public void run() {
            while (true) {
                try {
                    WatchedEvent event = eventQueue.take();
                    for (Watcher watcher : watchers) {
                        watcher.process(event);
                    }
                } catch (InterruptedException e) {
                    /* ignore */ }
            }
        }
    };
    watcherProcessor.setDaemon(true);
    watcherProcessor.start();

    Iterable<String> servers = Iterables.transform(ImmutableSet.copyOf(zooKeeperServers),
            InetSocketAddressHelper.INET_TO_STR);
    this.zooKeeperServers = Joiner.on(',').join(servers).concat(chrootPath.or(""));
}

From source file:ws.wamp.jawampa.WampRouter.java

WampRouter(Map<String, RealmConfig> realms) {

    // Populate the realms from the configuration
    this.realms = new HashMap<String, Realm>();
    for (Map.Entry<String, RealmConfig> e : realms.entrySet()) {
        Realm info = new Realm(e.getValue());
        this.realms.put(e.getKey(), info);
    }//from   w  w w.ja v a  2  s  . c  o m

    // Create an eventloop and the RX scheduler on top of it
    this.eventLoop = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "WampRouterEventLoop");
            t.setDaemon(true);
            return t;
        }
    });
    this.scheduler = Schedulers.from(eventLoop);

    idleChannels = new HashSet<IConnectionController>();
}

From source file:com.kurento.kmf.test.client.BrowserClient.java

public void addEventListener(final String eventType, final EventListener eventListener) {
    Thread t = new Thread() {
        public void run() {
            ((JavascriptExecutor) driver)
                    .executeScript("video.addEventListener('" + eventType + "', videoEvent, false);");
            (new WebDriverWait(driver, timeout)).until(new ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver d) {
                    return d.findElement(By.id("status")).getAttribute("value").equalsIgnoreCase(eventType);
                }/*from   ww  w . j  a  v a2  s .com*/
            });
            eventListener.onEvent(eventType);
        }
    };
    callbackThreads.add(t);
    t.setDaemon(true);
    t.start();
}