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.reactivetechnologies.analytics.core.IncrementalClassifierBean.java

@PostConstruct
void init() {/* w w w  . j  a v a 2  s  .  c o m*/
    loadAndInitializeModel();

    log.info((isUpdateable() ? "UPDATEABLE " : "NON-UPDATEABLE ") + "** Weka Classifier loaded [" + clazzifier
            + "] **");
    if (log.isDebugEnabled()) {
        log.debug("weka.classifier.tokenize? " + filterDataset);
        log.debug("weka.classifier.tokenize.options: " + filterOpts);
        log.debug("weka.classifier.build.batchSize: " + instanceBatchSize);
        log.debug("weka.classifier.build.intervalSecs: " + delay);
        log.debug("weka.classifier.build.maxIdleSecs: " + maxIdle);
    }
    worker = Executors.newSingleThreadExecutor(new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "RegressionBean.Worker.Thread");
            return t;
        }
    });
    worker.submit(new EventConsumer());

    timer = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "RegressionBean.Timer.Thread");
            t.setDaemon(true);
            return t;
        }
    });
    ((ScheduledExecutorService) timer).scheduleWithFixedDelay(new EventTimer(), delay, delay, TimeUnit.SECONDS);
}

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

public static void createNewPlaylist(final PlaylistItem[] playlistItems, boolean starred) {
    if (starred) {
        Thread t = new Thread(new Runnable() {
            public void run() {
                Playlist playlist = LibraryMediator.getLibrary().getStarredPlaylist();
                addToPlaylist(playlist, playlistItems, true, -1);
                GUIMediator.safeInvokeLater(new Runnable() {
                    public void run() {
                        DirectoryHolder dh = LibraryMediator.instance().getLibraryExplorer()
                                .getSelectedDirectoryHolder();
                        if (dh instanceof StarredDirectoryHolder) {
                            LibraryMediator.instance().getLibraryExplorer().refreshSelection();
                        } else {
                            LibraryMediator.instance().getLibraryExplorer().selectStarred();
                        }// ww w .  j a v a 2s.  c o m
                    }
                });
            }
        }, "createNewPlaylist");
        t.setDaemon(true);
        t.start();
    } else {
        String playlistName = (String) JOptionPane.showInputDialog(GUIMediator.getAppFrame(),
                I18n.tr("Playlist name"), I18n.tr("Playlist name"), JOptionPane.PLAIN_MESSAGE, null, null,
                calculateName(playlistItems));

        if (playlistName != null && playlistName.length() > 0) {
            final Playlist playlist = LibraryMediator.getLibrary().newPlaylist(playlistName, playlistName);

            Thread t = new Thread(new Runnable() {
                public void run() {
                    try {
                        playlist.save();
                        addToPlaylist(playlist, playlistItems);
                        playlist.save();
                        GUIMediator.safeInvokeLater(new Runnable() {
                            public void run() {
                                LibraryMediator.instance().getLibraryPlaylists().addPlaylist(playlist);
                            }
                        });
                    } finally {
                        asyncAddToPlaylistFinalizer(playlist);
                    }
                }
            }, "createNewPlaylist");
            t.setDaemon(true);
            t.start();
        }
    }
}

From source file:com.intuit.tank.service.impl.v1.report.ReportServiceV1.java

/**
 * @{inheritDoc/*ww w  .j a v  a2  s. co  m*/
 */
@Override
public Response processSummary(final String jobId) {
    ResponseBuilder responseBuilder = Response.ok();
    try {
        Thread t = new Thread(new Runnable() {
            public void run() {
                SummaryReportRunner.generateSummary(jobId);
            }
        });
        t.setDaemon(true);
        t.start();
        responseBuilder.entity("Generating summary data for job " + jobId);
    } catch (RuntimeException e) {
        LOG.error("Error deleting timing data: " + e, e);
        responseBuilder.status(Status.INTERNAL_SERVER_ERROR);
        responseBuilder.entity("An error occurred while deleting the timing data.");
    }
    return responseBuilder.build();
}

From source file:net.dv8tion.jda.entities.impl.PrivateChannelImpl.java

@Override
public void sendFileAsync(File file, Message message, Consumer<Message> callback) {
    Thread thread = new Thread(() -> {
        Message messageReturn;/*from   w  ww .j a va  2  s .c  o m*/
        try {
            messageReturn = sendFile(file, message);
        } catch (RateLimitedException e) {
            JDAImpl.LOG.warn("Got ratelimited when trying to upload file. Providing null to callback.");
            messageReturn = null;
        }

        if (callback != null)
            callback.accept(messageReturn);
    });
    thread.setName("PrivateChannelImpl SendFileAsync Channel: " + id);
    thread.setDaemon(true);
    thread.start();
}

From source file:com.eislab.af.translator.spokes.HttpServer_spoke.java

public HttpServer_spoke(String ipaddress, String path) throws IOException, InterruptedException {

    address = ipaddress;//ww w.  j av  a  2s . co m
    // HTTP parameters for the server
    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SOCKET_TIMEOUT)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, SOCKET_BUFFER_SIZE)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, SERVER_NAME);

    // Create HTTP protocol processing chain
    // Use standard server-side protocol interceptors
    HttpRequestInterceptor[] requestInterceptors = new HttpRequestInterceptor[] { new RequestAcceptEncoding() };
    HttpResponseInterceptor[] responseInterceptors = new HttpResponseInterceptor[] { new ResponseAllowCORS(),
            new ResponseContentEncoding(), new ResponseDate(), new ResponseServer(), new ResponseContent(),
            new ResponseConnControl() };
    HttpProcessor httpProcessor = new ImmutableHttpProcessor(requestInterceptors, responseInterceptors);

    // Create request handler registry
    HttpAsyncRequestHandlerRegistry registry = new HttpAsyncRequestHandlerRegistry();

    // register the handler that will reply to the proxy requests

    registry.register(path, new RequestHandler("", true));

    // Create server-side HTTP protocol handler
    HttpAsyncService protocolHandler = new HttpAsyncService(httpProcessor, new DefaultConnectionReuseStrategy(),
            registry, params);

    // Create HTTP connection factory
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory = new DefaultNHttpServerConnectionFactory(
            params);

    // Create server-side I/O event dispatch
    final IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);

    try {
        // Create server-side I/O reactor
        ioReactor = new DefaultListeningIOReactor();
        // Listen of the given port

        InetSocketAddress socketAddress = new InetSocketAddress(ipaddress, 0);
        ListenerEndpoint endpoint1 = ioReactor.listen(socketAddress);

        // create the listener thread
        Thread listener = new Thread("Http listener") {

            @Override
            public void run() {
                try {
                    ioReactor.execute(ioEventDispatch);

                } catch (IOException e) {
                    //                     LOGGER.severe("I/O Exception: " + e.getMessage());
                }

            }
        };

        listener.setDaemon(false);
        listener.start();

        endpoint1.waitFor();

        if (address.contains(":")) {
            if (!address.startsWith("[")) {
                address = "[" + address + "]";
            }
        }

        address = address + ":" + Integer.toString(((InetSocketAddress) endpoint1.getAddress()).getPort())
                + "/";
        System.out.println(address);

    } catch (IOException e) {
        //            LOGGER.severe("I/O error: " + e.getMessage());
    }
}

From source file:com.chicm.cmraft.core.NodeConnectionManager.java

public void collectVote(long term, long lastLogIndex, long lastLogTerm) {
    int nServers = getRemoteServers().size();
    if (nServers <= 0) {
        return;/* w  w  w. ja  v a 2 s.  c  o  m*/
    }
    ExecutorService executor = Executors.newFixedThreadPool(nServers, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(getRaftNode().getName() + "-AsyncRpcCaller" + (byte) System.currentTimeMillis());
            return t;
        }
    });

    for (ServerInfo server : getRemoteServers()) {
        NodeConnection conn = connections.get(server);
        LOG.debug(getRaftNode().getName() + ": SENDING COLLECTVOTE Request TO: " + server);
        Thread t = new Thread(new AsynchronousVoteWorker(getRaftNode(), conn, getRaftNode().getServerInfo(),
                term, lastLogIndex, lastLogTerm));
        t.setDaemon(true);
        executor.execute(t);
    }
}

From source file:com.owera.xaps.spp.TFTPServer.java

public void run() {
    try {//from w  w  w  . j  ava2s  . c o m
        while (!shutdownServer) {
            TFTPPacket tftpPacket;

            tftpPacket = serverTftp_.receive();
            if (tftpPacket == null)
                continue; // server is going down
            String msg = "TFTP request received: type=" + tftpPacket.getType();
            msg += ", from=" + tftpPacket.getAddress() + ":" + tftpPacket.getPort();
            Log.debug(TFTPServer.class, msg);

            TFTPTransfer tt = new TFTPTransfer(tftpPacket);
            synchronized (transfers_) {
                transfers_.add(tt);
            }

            Thread thread = new Thread(tt);
            thread.setDaemon(true);
            thread.start();
        }
    } catch (Exception e) {
        if (!shutdownServer) {
            serverException = e;
            Log.fatal(TFTPServer.class, "Unexpected Error in TFTP Server - Server shut down!", e);
        }
    } finally {
        shutdownServer = true; // set this to true, so the launching thread can
                               // check to see if it started.
        if (serverTftp_ != null && serverTftp_.isOpen()) {
            serverTftp_.close();
        }
    }
}

From source file:cc.arduino.Compiler.java

private void exec(String[] command) throws RunnerException {
    // eliminate any empty array entries
    List<String> stringList = new ArrayList<>();
    for (String string : command) {
        string = string.trim();/* w w w  .ja va  2s .c  om*/
        if (string.length() != 0)
            stringList.add(string);
    }
    command = stringList.toArray(new String[stringList.size()]);
    if (command.length == 0)
        return;

    if (verbose) {
        for (String c : command)
            System.out.print(c + " ");
        System.out.println();
    }

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler() {

        @Override
        protected Thread createPump(InputStream is, OutputStream os, boolean closeWhenExhausted) {
            final Thread result = new Thread(new MyStreamPumper(is, Compiler.this));
            result.setName("MyStreamPumper Thread");
            result.setDaemon(true);
            return result;

        }
    });

    CommandLine commandLine = new DoubleQuotedArgumentsOnWindowsCommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        commandLine.addArgument(command[i], false);
    }

    int result;
    executor.setExitValues(null);
    try {
        result = executor.execute(commandLine);
    } catch (IOException e) {
        RunnerException re = new RunnerException(e.getMessage());
        re.hideStackTrace();
        throw re;
    }
    executor.setExitValues(new int[0]);

    // an error was queued up by message(), barf this back to compile(),
    // which will barf it back to Editor. if you're having trouble
    // discerning the imagery, consider how cows regurgitate their food
    // to digest it, and the fact that they have five stomaches.
    //
    //System.out.println("throwing up " + exception);
    if (exception != null)
        throw exception;

    if (result > 1) {
        // a failure in the tool (e.g. unable to locate a sub-executable)
        System.err.println(I18n.format(tr("{0} returned {1}"), command[0], result));
    }

    if (result != 0) {
        RunnerException re = new RunnerException(tr("Error compiling."));
        re.hideStackTrace();
        throw re;
    }
}

From source file:backup.namenode.NameNodeBackupBlockCheckProcessor.java

public void runReport(boolean debug) {
    Thread thread = new Thread(() -> {
        try {/*from ww w. ja  v a  2 s . c  om*/
            runBlockCheck(debug);
        } catch (Exception e) {
            LOG.error("Unknown error", e);
        }
    });
    thread.setDaemon(true);
    thread.start();
}

From source file:com.runwaysdk.dataaccess.database.general.ProcessReader.java

/**
 * Consumes the /*w  w  w .j a va  2 s .c  o  m*/
 * @param reader
 * @param buffer
 */
private void consumeError(final InputStream inputStream, final StringBuffer buffer) {
    final BufferedReader out = new BufferedReader(new InputStreamReader(inputStream));

    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                String line = new String();

                while ((line = out.readLine()) != null) {
                    buffer.append(line);
                }
            } catch (Throwable t) {
                String msg = "Error when consuming the error stream.";
                throw new ProgrammingErrorException(msg, t);
            }
        }
    }, ERROR_THREAD);

    t.setUncaughtExceptionHandler(this);
    t.setDaemon(true);
    t.start();
}