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.espertech.esper.timer.TimerServiceImpl.java

private void getScheduledThreadPoolExecutorDaemonThread() {
    timer = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
        // set new thread as daemon thread and name appropriately
        public Thread newThread(Runnable r) {
            String uri = engineURI;
            if (engineURI == null) {
                uri = "default";
            }/*from ww  w .j  ava2s  . c  o m*/
            Thread t = new Thread(r, "com.espertech.esper.Timer-" + uri + "-" + id);
            t.setDaemon(true);
            return t;
        }
    });
    timer.setMaximumPoolSize(timer.getCorePoolSize());
    timer.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    timer.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
}

From source file:com.reactivetechnologies.blaze.throttle.DefaultConsumerThrottler.java

@PostConstruct
public void init() {
    if (enabled) {
        addCommand(new ThrottleCommand());
        List<? extends Command> customCommands = loadCommands();
        if (customCommands != null) {
            for (Command cmd : customCommands)
                addCommand(cmd);/*from   w  ww  .ja  v  a 2  s  .  c om*/
        }

        counter = new AtomicInteger();
        timer = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {

            @Override
            public Thread newThread(Runnable arg0) {
                Thread t = new Thread(arg0, "Throttler-timer-thread");
                t.setDaemon(true);
                return t;
            }
        });
        timer.scheduleWithFixedDelay(new MessageThrottlerTask(), 0, throttlerPeriod, TimeUnit.MILLISECONDS);

        log.info("Throttling enabled with period of " + throttlerPeriod + " millis");
    }
}

From source file:httpscheduler.LateBindingRequestListenerThread.java

@Override
public void run() {
    System.out.println("Listening on port " + this.serversocket.getLocalPort());
    ArrayList<String> workerList = new ArrayList<>();

    // Read list of workers from configuration file
    try (BufferedReader br = new BufferedReader(new FileReader("./config/workers.conf"))) {
        for (String line; (line = br.readLine()) != null;) {
            workerList.add(line);//from  w  ww.jav a 2s.co  m
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(GenericRequestListenerThread.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GenericRequestListenerThread.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Initialize worker manager
    try {
        WorkerManager.useWorkerList(workerList);
    } catch (Exception ex) {
        Logger.getLogger(GenericRequestListenerThread.class.getName()).log(Level.SEVERE, null, ex);
        System.exit(-1);
    }
    WorkerManager.printWorkerMap();

    //jobMap.put(1, new String[1000]);
    Thread workerStatusThread = new UpdateWorkerStatusThread();
    workerStatusThread.start();
    System.out.println("ready for connections");
    while (!Thread.interrupted()) {
        try {
            // Set up HTTP connection
            Socket socket = this.serversocket.accept();
            System.out.println("Incoming connection from " + socket.getInetAddress());
            HttpServerConnection conn = this.connFactory.createConnection(socket);

            // Initialize the pool
            Thread connectionHandler = new ConnectionHandlerThread(this.httpService, conn);

            connectionHandler.setDaemon(false);
            connectionHandlerExecutor.execute(connectionHandler);
            System.out.println("\tConnection Handler Thread created");
        } catch (InterruptedIOException ex) {
            break;
        } catch (IOException e) {
            System.err.println("I/O error initialising connection thread: " + e.getMessage());
            break;
        }
    }
    // when the listener is interupted shutdown the pool
    // and wait for any Connection Handler threads still running
    connectionHandlerExecutor.shutdown();
    while (!connectionHandlerExecutor.isTerminated()) {
    }

    System.out.println("Finished all connection handler threads");
}

From source file:com.github.brandtg.switchboard.TestMysqlReplicationApplier.java

@Test
public void testRestoreFromBinlog() throws Exception {
    MysqlReplicationApplier applier = null;
    try (Connection conn = DriverManager.getConnection(jdbc, "root", "")) {
        // Write some rows, so we have binlog entries
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO simple VALUES(?, ?)");
        for (int i = 0; i < 10; i++) {
            pstmt.setInt(1, i);//  w  w  w  .j a  va  2s  . c o m
            pstmt.setInt(2, i);
            pstmt.execute();
        }

        // Copy the binlog somewhere
        Statement stmt = conn.createStatement();
        ResultSet rset = stmt.executeQuery("SHOW BINARY LOGS");
        rset.next();
        String binlogName = rset.getString("Log_name");
        rset = stmt.executeQuery("SELECT @@datadir");
        rset.next();
        String dataDir = rset.getString("@@datadir");
        File copyFile = new File(System.getProperty("java.io.tmpdir"),
                TestMysqlReplicationApplier.class.getName());
        FileUtils.copyFile(new File(dataDir + binlogName), copyFile);

        // Clear everything in MySQL
        resetMysql();

        // Get input stream, skipping and checking binlog magic number
        InputStream inputStream = new FileInputStream(copyFile);
        byte[] magic = new byte[MySQLConstants.BINLOG_MAGIC.length];
        int bytesRead = inputStream.read(magic);
        Assert.assertEquals(bytesRead, MySQLConstants.BINLOG_MAGIC.length);
        Assert.assertTrue(CodecUtils.equals(magic, MySQLConstants.BINLOG_MAGIC));

        // Restore from binlog
        PoolingDataSource<PoolableConnection> dataSource = getDataSource();
        applier = new MysqlReplicationApplier(inputStream, dataSource);
        ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setDaemon(true);
                return t;
            }
        });
        executorService.submit(applier);

        // Poll until we have restored
        long startTime = System.currentTimeMillis();
        long currentTime = startTime;
        do {
            stmt = conn.createStatement();
            rset = stmt.executeQuery("SELECT COUNT(*) FROM test.simple");
            rset.next();
            long count = rset.getLong(1);
            if (count == 10) {
                return;
            }
            Thread.sleep(1000);
            currentTime = System.currentTimeMillis();
        } while (currentTime - startTime < 10000);
    } finally {
        if (applier != null) {
            applier.shutdown();
        }
    }

    Assert.fail("Timed out when polling");
}

From source file:me.j360.trace.autoconfiguration.collector.kafka.ZipkinKafkaCollectorAutoConfiguration.java

/**
 * This launches a thread to run start. This prevents a several second hang, or worse crash if
 * zookeeper isn't running, yet.//from  w  ww. ja va  2s.  c  o  m
 */
@Bean
KafkaCollector kafka(ZipkinKafkaCollectorProperties kafka, CollectorSampler sampler, CollectorMetrics metrics,
        StorageComponent storage) {
    final KafkaCollector result = kafka.toBuilder().sampler(sampler).metrics(metrics).storage(storage).build();

    // don't use @Bean(initMethod = "start") as it can crash the process if zookeeper is down
    Thread start = new Thread("start " + result.getClass().getSimpleName()) {
        @Override
        public void run() {
            result.start();
        }
    };
    start.setDaemon(true);
    start.start();

    return result;
}

From source file:com.offbynull.portmapper.common.UdpCommunicator.java

@Override
protected Executor executor() {
    return new Executor() {
        @Override//from  www. j  a v  a2s .  com
        public void execute(Runnable command) {
            Thread thread = new Thread(command);
            thread.setDaemon(true);
            thread.start();
        }
    };
}

From source file:com.streamsets.datacollector.websockets.LogMessageWebSocket.java

@Override
public void onWebSocketConnect(final Session session) {
    super.onWebSocketConnect(session);

    synchronized (LogMessageWebSocket.class) {
        int maxClients = config.get(MAX_LOGTAIL_CONCURRENT_REQUESTS_KEY,
                MAX_LOGTAIL_CONCURRENT_REQUESTS_DEFAULT);
        if (logTailClients < maxClients) {
            logTailClients++;/* w w  w .jav  a2  s.  c  om*/
        } else {
            session.close(StatusCode.NORMAL, "Maximum concurrent connections reached");
            return;
        }
    }

    TailerListener listener = new TailerListenerAdapter() {
        @Override
        public void handle(String line) {
            try {
                Map<String, String> namedGroupToValuesMap = logFileGrok.extractNamedGroups(line);

                if (namedGroupToValuesMap == null) {
                    namedGroupToValuesMap = new HashMap<>();
                    namedGroupToValuesMap.put("exceptionMessagePart", line);
                }

                ObjectMapper objectMapper = ObjectMapperFactory.get();
                String logDataJson = objectMapper.writer().writeValueAsString(namedGroupToValuesMap);
                session.getRemote().sendString(logDataJson);

            } catch (IOException ex) {
                LOG.warn("Error while sending log line through WebSocket message, {}", ex.toString(), ex);
            }
        }

        @Override
        public void fileNotFound() {
            LOG.warn("Log file '{}' does not exist", logFile);
        }

        @Override
        public void handle(Exception ex) {
            LOG.warn("Error while trying to read log file '{}': {}", logFile, ex.toString(), ex);
        }
    };

    //TODO send -20K of logFile to session, separator line, then tailer

    tailer = new Tailer(new File(logFile), listener, 100, true, true);
    Thread thread = new Thread(tailer, "LogMessageWebSocket-tailLog");
    thread.setDaemon(true);
    thread.start();
}

From source file:com.tjhruska.spring.jesque.JesqueContainer.java

/**
 * Spin through to attempt to replace any dead/missing workers. WorkerFactory
 * is not required to return a worker. (This is mostly useful when the workers
 * are tied to limited resources.)// w w  w .j av a 2 s.c o  m
 */
public void checkWorkers() {
    for (int i = 0; i < maxWorkerCount; i++) {
        if (!paused && (workerThreads[i] == null || !workerThreads[i].isAlive())) {
            Worker worker;
            try {
                worker = workerFactory.call();
            } catch (Exception e) {
                throw new RuntimeException("Failed to get a worker from the workerFactory", e);
            }
            if (worker != null) {
                log.info(beanName + " started worker(s) of type '{}' with queues: '{}'", worker.getName(),
                        worker.getQueues());

                Thread workerThread = new Thread(worker);
                workerThread.setDaemon(false);
                workerThread.start();

                workers[i] = worker;
                workerThreads[i] = workerThread;
            }
        }
    }
}

From source file:org.jasig.cas.web.support.ThrottledSubmissionByIpAddressHandlerInterceptorAdapter.java

public void afterPropertiesSet() throws Exception {

    final Thread thread = new ExpirationThread(this.restrictedIpAddressMaps, this.failureTimeout);
    thread.setDaemon(true);//from  w  w w  .j  a  va2 s  . c  o  m
    thread.start();
}

From source file:com.frostwire.gui.library.LibraryUtils.java

public static void asyncAddToPlaylist(final Playlist playlist, final PlaylistItem[] playlistItems,
        final int index) {
    Thread t = new Thread(new Runnable() {
        public void run() {
            addToPlaylist(playlist, playlistItems, index);
            playlist.save();/*from   w w  w  . j  av  a2s.c  o m*/
            GUIMediator.safeInvokeLater(new Runnable() {
                public void run() {
                    LibraryMediator.instance().getLibraryPlaylists().refreshSelection();
                }
            });
        }
    }, "asyncAddToPlaylist");
    t.setDaemon(true);
    t.start();
}