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:com.hellblazer.process.impl.AbstractManagedProcess.java

/**
 * The actual execution process. Control will not return until the command
 * list execution has finished.//from w w  w  . j  av a2  s .co m
 * 
 * @param commands
 *            - the command list to execute
 * 
 * @throws IOException
 *             - if anything goes wrong during the execution.
 */
protected void primitiveExecute(List<String> commands) throws IOException {
    ProcessBuilder builder = new ProcessBuilder();
    builder.directory(directory);
    if (environment != null) {
        builder.environment().putAll(environment);
    }
    builder.command(commands);
    builder.redirectErrorStream(true); // combine OUT and ERR into one
    // stream
    Process p = builder.start();
    final BufferedReader shellReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    Runnable reader = new Runnable() {
        @Override
        public void run() {
            String line;
            try {
                line = shellReader.readLine();
            } catch (IOException e) {
                if (!"Stream closed".equals(e.getMessage())
                        && !e.getMessage().contains("Bad file descriptor")) {
                    log.log(Level.SEVERE, "Failed reading process output", e);
                }
                return;
            }
            while (line != null) {
                if (log.isLoggable(Level.FINE) && line != null) {
                    log.fine("[" + id + "] " + line);
                }
                try {
                    line = shellReader.readLine();
                } catch (IOException e) {
                    if (!"Stream closed".equals(e.getMessage())) {
                        log.log(Level.SEVERE, "Failed reading process output", e);
                    }
                    return;
                }
            }
        }
    };

    Thread readerThread = new Thread(reader, "Process reader for: " + getCommand());
    readerThread.setDaemon(true);
    readerThread.start();

    try {
        p.waitFor();
    } catch (InterruptedException e) {
        return;
    } finally {
        readerThread.interrupt();
        p.destroy();
    }
}

From source file:com.opendoorlogistics.core.gis.map.background.MapsforgeTileFactory.java

MapsforgeTileFactory(TileFactoryInfo info, String xmlRenderThemeFilename, MapDataStore mapDatabase,
        FadeConfig fadeColour) {//from   w w  w .  java2s.com
    super(info);
    this.fadeColour = fadeColour;
    this.mapDatabase = mapDatabase;

    zoomLevelConverter = new ZoomLevelConverter(info);
    databaseRenderer = new DatabaseRenderer(mapDatabase, AwtGraphicFactory.INSTANCE,
            createDummyTileCacheForMapsforgeLabelPlacementAlgorithm());
    renderTheme = getRenderTheme(xmlRenderThemeFilename);

    model = new DisplayModel();
    model.setFixedTileSize(TILE_SIZE);
    model.setBackgroundColor(backgroundMapColour().getRGB());

    // use single thread at the moment as DatabaseRenderer is probably single threaded
    service = Executors.newFixedThreadPool(1, new ThreadFactory() {
        private int count = 0;

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "mapsforge-tile-pool-" + count++);
            t.setPriority(Thread.MIN_PRIORITY);
            t.setDaemon(true);
            return t;
        }
    });
}

From source file:com.hubcap.task.helpers.DefaultSearchHelper.java

@Override
public void run() {

    if (taskModel == null) {
        if (this.listener != null) {
            this.listener.processTaskHelperError(
                    new Exception("No Task Model Provided to DefaultSearchHelper, cannot run!"), false);
        }//ww w.j ava  2 s .c  o  m
        die();
        return;
    }

    CommandLine cmd = taskModel.getCommandLine();

    int cLen = cmd.getArgs().length;
    // default search arguments are in the format
    // orgname (String) count (int)

    if (cLen < 1) {
        if (this.listener != null) {
            this.listener.processTaskHelperError(
                    new Exception("Default Search requires 1 argument, Organization (optional) Count"), false);
        }
        die();
    }

    if (cLen % 2 == 0) {

        // each helper has its own HttpClient
        ProcessModel.instance().updateRateLimitData();

        for (int i = 0; i < cLen; i += 2) {

            String orgName = cmd.getArgs()[i];
            int count = 10;

            try {
                count = Integer.parseInt(cmd.getArgs()[i + 1]);
            } catch (NumberFormatException ex) {
                ErrorUtils.printStackTrace(ex);
            }

            final long remainingRate = ProcessModel.instance().getRateLimitData().rate.remaining;
            final long maxResults = opts.containsKey("maxResults")
                    ? Integer.parseInt((String) opts.get("maxResults"))
                    : (remainingRate - 1);
            int maxPages = 100;
            if (remainingRate >= maxResults) {

                // pound that API until we get what we want!!

                // breaks out of the loop after
                // max pages
                searchHelperId.incrementAndGet();

                if (searchHelperId.get() > maxPages) {
                    break;
                }

                try {
                    synchronized (droneThreads) {

                        Thread t = new Thread(
                                new GitHubOrgScavengerDrone(sewingMachine, this.taskModel, orgName, count));
                        droneThreads.add(t);
                        t.setName("drone" + String.valueOf(owner.getTaskId()) + "-"
                                + String.valueOf(new Date().getTime()));
                        t.setDaemon(false);
                        t.start();
                    }
                } catch (RejectedExecutionException ex) {
                    ErrorUtils.printStackTrace(ex);
                    break;
                }

            } else {
                System.err.println("Your rate limit is exhausted, try again later!");
            }
        }
    }

    if (ProcessModel.instance().getVerbose()) {
        System.out.println("Waiting for Drone Threads: " + droneThreads.size());
    }

    // wait for all threads to complete
    while (droneThreads.size() > 0) {
        Iterator<Thread> it = droneThreads.iterator();
        while (it.hasNext()) {
            Thread currDroneThread = it.next();

            if (currDroneThread.getState() == State.TERMINATED) {

                if (ProcessModel.instance().getVerbose()) {
                    System.err.println("Removing Drone Thread: " + currDroneThread.getName());
                }

                it.remove();
            }
        }

        // sleep and do it again
        if (!ThreadUtils.safeSleep(
                Constants.NEW_THREAD_SPAWN_BREATHING_TIME
                        + Constants.NEW_THREAD_SPAWN_BREATHING_TIME * 1 / SewingMachine.MAX_THREADS_PER_MACHINE,
                ProcessModel.instance().getVerbose())) {
            System.err.println("INTERRUPTED WAIT FOR DRONE THREADS!");
            break;
        }
    }

    System.out.println("No More Drones!");
    // wait a tad

    synchronized (taskModel) {
        Map<String, Object> aggData = taskModel.getAggregateDataMap();

        if (aggData != null) {

            for (String key : aggData.keySet()) {

                Object value = aggData.get(key);

                if (value instanceof ScavengerModel == false) {
                    continue;
                }

                // ask the model to calculate from its current state
                ScavengerModel model = (ScavengerModel) value;
                synchronized (model) {
                    model.calculate();
                }
            }

            listener.processTaskHelperData(taskModel);
        }
    }
    die();
}

From source file:com.quancheng.saluki.core.config.RpcServiceConfig.java

public synchronized void export() {
    Map<GrpcURL, Object> providerUrls = Maps.newHashMap();
    for (RpcServiceSingleConfig<Object> singleServiceConfig : singleServiceConfigs) {
        String serviceName = singleServiceConfig.getServiceName();
        Object serviceRef = singleServiceConfig.getRef();
        Map<String, String> params = Maps.newHashMap();
        this.addGroup(singleServiceConfig, params);
        this.addVersion(singleServiceConfig, params);
        this.addApplication(params);
        this.addInterval(params);
        this.addRegistryRpcPort(params);
        this.addHttpPort(params);
        GrpcURL providerUrl = new GrpcURL(Constants.REMOTE_PROTOCOL, super.getHost(), super.getRealityRpcPort(),
                serviceName, params);//from w  w w. j  a  v a2s  .  c  o  m
        providerUrls.put(providerUrl, serviceRef);
    }
    try {
        internalServer = super.getGrpcEngine().getServer(providerUrls, super.getRealityRpcPort());
        Thread awaitThread = new Thread() {

            @Override
            public void run() {
                try {
                    internalServer.start();
                    internalServer.awaitTermination();
                } catch (InterruptedException e) {
                    throw new IllegalStateException(e.getMessage(), e);
                } catch (IOException e) {
                    throw new IllegalStateException(e.getMessage(), e);
                }
            }

        };
        awaitThread.setDaemon(false);
        awaitThread.start();
    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }

}

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

/**
 *
 * @param path          directory to clean
 * @param keepAliveHour any file/directory having last modified time longer than keepAliveHour will be deleted
 * @param namePrefix    file name prefix
 *///  w w w  . j  av a  2 s  . c om
public static void cleanDirectory(final String path, final float keepAliveHour, final String namePrefix) {
    final long intervalMillis = 3600000;
    final File dir = new File(path);
    if (!dir.exists()) {
        return;
    }
    Thread thread = new Thread() {
        @Override
        public void run() {
            while (true) {
                long lastModifiedMillis = (long) (System.currentTimeMillis() - keepAliveHour * 3600000);
                Collection<File> files = FileUtils.listFiles(dir, null, true);
                for (File file : files) {
                    if (file.lastModified() < lastModifiedMillis && file.getName().startsWith(namePrefix)) {
                        LOG.debug("Delete {}", file);
                        if (!FileUtils.deleteQuietly(file)) {
                            LOG.debug("Cannot delete {}", file);
                        }
                    }
                }
                try {
                    LOG.debug("Waiting for next cleanup...");
                    Thread.sleep(intervalMillis);
                } catch (InterruptedException ex) {
                    LOG.warn(ex.getMessage());
                    return;
                }
            }
        }
    };
    thread.setName(Thread.currentThread().getName() + "-cleaning-" + thread.hashCode());
    thread.setDaemon(true);
    LOG.info(
            "Starting directory cleaning thread (scanning hourly), all files/directories in {} and older than {} "
                    + "hour(s) and starts with {} will be deleted",
            dir, keepAliveHour, namePrefix);
    thread.start();
}

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

/**
 * This is the generic startup code for the WattsUp data source adaptor
 *
 * @param port The port to connect to//from  w  w w .ja  va  2s . c  o m
 * @param duration The duration to connect for (< 0 means forever) 
 * @param interval The interval at which to take logging data.
 */
public final void startup(String port, int duration, int interval) {
    if (port.equalsIgnoreCase("file")) {
        String filename = settings.getString("energy.modeller.wattsup.scrape.file", "testnodex-wattsup.log");
        if (settings.isChanged()) {
            settings.save("energy-modeller-watts-up-meter.properties");
        }
        File scrapeFile = new File(filename);
        fileTailer = new WattsUpTailer();
        tailer = Tailer.create(scrapeFile, fileTailer, (interval * 1000) / 16, true);
        Thread tailerThread = new Thread(tailer);
        tailerThread.setDaemon(true);
        tailerThread.start();
        System.out.println("Scraping from WattsUp meter file");
    } else {
        try {
            WattsUpConfig config = new WattsUpConfig().withPort(port).scheduleDuration(duration)
                    .withInternalLoggingInterval(interval).withExternalLoggingInterval(interval);
            meter = new WattsUp(config);
            System.out.println("WattsUp Meter Created");
            registerEventListeners(meter);
            System.out.println("WattsUp Meter Connecting");
            meter.connect(false);
            meter.setLoggingModeSerial(1);
            System.out.println("WattsUp Meter Connected " + meter.isConnected());
        } catch (IOException ex) {
            Logger.getLogger(WattsUpMeterDataSourceAdaptor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:barrysw19.calculon.icc.ICCInterface.java

public void connect() throws IOException {
    connection = new Socket("chessclub.com", 23);
    doLogin();/*from  w  w  w  .  j  av  a2 s.  c o  m*/
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    out = new PrintStream(connection.getOutputStream());

    send("set level1 1");
    send("set style 12");
    if (!StringUtils.isBlank(iccConfig.getFormula())) {
        send("set formula " + iccConfig.getFormula());
    }
    receiveLevel2(DgCommand.DG_MY_GAME_STARTED, DgCommand.DG_MY_GAME_RESULT, DgCommand.DG_SEND_MOVES,
            DgCommand.DG_MOVE_ALGEBRAIC, DgCommand.DG_MOVE_SMITH, DgCommand.DG_MOVE_TIME,
            DgCommand.DG_MOVE_CLOCK, DgCommand.DG_MSEC);

    setStatus();
    if (iccConfig.isReseek()) {
        reseek();
    }

    Runnable keepAlive = () -> {
        while (alive) {
            send("games *r-e-B-o-M-f-K-w-L-d-z");
            try {
                Thread.sleep(60000);
            } catch (InterruptedException x) {
                // Ignore
            }
        }
    };
    Thread keepAliveThread = new Thread(keepAlive);
    keepAliveThread.setDaemon(true);
    keepAliveThread.start();

    StringBuilder line = new StringBuilder();
    int c;
    try {
        while ((c = reader.read()) != -1) {
            lv1BlockHandler.add((char) c);

            // Ignore CTRL-M, CTRL-G
            if (c == ('M' & 0x1F) || c == ('G' & 0x1F)) {
                continue;
            }
            line.append((char) c);
            if (c == '\n') {
                fireDataReceived(line.toString());
                line.setLength(0);
                continue;
            }
            if (line.length() >= 2 && line.charAt(line.length() - 2) == ('Y' & 0x1F)
                    && line.charAt(line.length() - 1) == ']') {
                fireDataReceived(line.toString());
                line.setLength(0);
            }
        }
    } finally {
        alive = false;
        try {
            reader.close();
            out.close();
        } catch (Exception x) {
            // ignore
        }
    }
}

From source file:de.chaosfisch.google.youtube.upload.Uploader.java

public void run() {
    if (uploadService.getRunning()) {
        return;/*from ww w . j  a  v a2  s .  c o m*/
    }
    uploadService.setRunning(true);

    final Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (canAddJob() && hasJobs()) {
                enqueueUpload();

                try {
                    Thread.sleep(ENQUEUE_WAIT_TIME);
                } catch (final InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }, "Enqueue-Thread");
    thread.setDaemon(true);
    thread.start();
}

From source file:com.baidu.asynchttpclient.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from  w  ww.j  a  va2 s.  c o m*/
 */
public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));
    HttpProtocolParams.setUseExpectContinue(httpParams, false);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool(new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r) {

            Thread t = new Thread(r, "AsyncHttpClient #" + mCount.getAndIncrement());
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != (Thread.NORM_PRIORITY - 1))
                t.setPriority((Thread.NORM_PRIORITY - 1));
            return t;
        }
    });

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:com.baifendian.swordfish.execserver.runner.flow.FlowRunnerManager.java

public FlowRunnerManager(Configuration conf) {
    this.flowDao = DaoFactory.getDaoInstance(FlowDao.class);

    int flowThreads = conf.getInt(Constants.EXECUTOR_FLOWRUNNER_THREADS, Constants.defaultFlowRunnerThreadNum);
    ThreadFactory flowThreadFactory = new ThreadFactoryBuilder().setNameFormat("Exec-Worker-FlowRunner")
            .build();//ww w . ja v a2 s.  co  m
    flowExecutorService = Executors.newFixedThreadPool(flowThreads, flowThreadFactory);

    int nodeThreads = conf.getInt(Constants.EXECUTOR_NODERUNNER_THREADS, Constants.defaultNodeRunnerThreadNum);
    ThreadFactory nodeThreadFactory = new ThreadFactoryBuilder().setNameFormat("Exec-Worker-NodeRunner")
            .build();
    nodeExecutorService = Executors.newFixedThreadPool(nodeThreads, nodeThreadFactory);

    // ?? runningFlows ??
    Thread cleanThread = new Thread(() -> {
        while (true) {
            try {
                cleanFinishedFlows();
            } catch (Exception e) {
                logger.error("clean thread error ", e);
            } finally {
                try {
                    Thread.sleep(Constants.defaultCleanFinishFlowInterval);
                } catch (InterruptedException e) {
                }
            }
        }
    });

    cleanThread.setDaemon(true);
    cleanThread.setName("finishedFlowClean");
    cleanThread.start();
}