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.frostwire.gui.library.LibraryUtils.java

public static void createNewPlaylist(final File[] files, final boolean starred) {

    final StringBuilder plBuilder = new StringBuilder();

    GUIMediator.safeInvokeAndWait(new Runnable() {

        @Override/*from w  w w. j a  v  a  2s .c o  m*/
        public void run() {
            String input = (String) JOptionPane.showInputDialog(GUIMediator.getAppFrame(),
                    I18n.tr("Playlist name"), I18n.tr("Playlist name"), JOptionPane.PLAIN_MESSAGE, null, null,
                    calculateName(files));
            if (!StringUtils.isNullOrEmpty(input, true)) {
                plBuilder.append(input);
            }
        }
    });

    String playlistName = plBuilder.toString();

    if (playlistName != null && playlistName.length() > 0) {
        GUIMediator.instance().setWindow(GUIMediator.Tabs.LIBRARY);
        final Playlist playlist = LibraryMediator.getLibrary().newPlaylist(playlistName, playlistName);
        playlist.save();

        GUIMediator.safeInvokeLater(new Runnable() {

            @Override
            public void run() {
                LibraryMediator.instance().getLibraryPlaylists().addPlaylist(playlist);
                LibraryMediator.instance().getLibraryPlaylists().markBeginImport(playlist);
            }
        });

        Thread t = new Thread(new Runnable() {
            public void run() {
                try {
                    Set<File> ignore = TorrentUtil.getIgnorableFiles();
                    addToPlaylist(playlist, files, starred, ignore);
                    playlist.save();
                } finally {
                    asyncAddToPlaylistFinalizer(playlist);
                }
            }
        }, "createNewPlaylist");
        t.setDaemon(true);
        t.start();
    }
}

From source file:org.nmdp.service.epitope.dropwizard.EpitopeServiceApplication.java

/**
 * Dropwizard service runner.  Application resources are registered here.
 *///from ww w.j  a  va  2  s.c o m
@Override
public void runService(final EpitopeServiceConfiguration configuration, final Environment environment)
        throws Exception {

    Injector injector = Guice.createInjector(
            new ConfigurationModule(ConfigurationBindings.class, configuration), new LocalServiceModule(),
            new ResourceModule(), new AbstractModule() {
                @Override
                protected void configure() {
                    DBI dbi = new DBIFactory().build(environment, configuration.getDataSourceFactory(),
                            "sqlite");
                    bind(DBI.class).toInstance(dbi);
                }
            });

    environment.getObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
            .setSerializationInclusion(Include.NON_NULL)
            .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

    // todo: generalize dependency graph (latches?)
    //Runnable initializers = serial(
    //       parallel(
    //          () -> injector.getInstance(GGroupInitializer.class).loadGGroups(),
    //          () -> injector.getInstance(AlleleCodeInitializer.class).loadAlleleCodes(),
    //          serial(
    //             () -> injector.getInstance(AlleleInitializer.class).loadAlleles()),
    //             () -> injector.getInstance(ImgtImmuneGroupInitializer.class).loadAlleleScores()),
    //       parallel(
    //          () -> injector.getInstance(EpitopeService.class).buildMaps(),
    //          () -> injector.getInstance(FrequencyService.class).buildFrequencyMap(),
    //          () -> injector.getInstance(DbiAlleleCodeResolver.class).buildAlleleCodeMap()));

    Runnable initializers = serial(() -> injector.getInstance(GGroupInitializer.class).loadGGroups(),
            () -> injector.getInstance(AlleleCodeInitializer.class).loadAlleleCodes(),
            () -> injector.getInstance(AlleleInitializer.class).loadAlleles(),
            () -> injector.getInstance(ImmuneGroupInitializer.class).loadImmuneGroups(),
            () -> injector.getInstance(EpitopeService.class).buildAlleleGroupMaps(),
            () -> injector.getInstance(FrequencyService.class).buildFrequencyMap());
    //                 () -> injector.getInstance(DbiAlleleCodeResolver.class).buildAlleleCodeMap());

    long refreshMillis = injector.getInstance(Key.get(Long.class, RefreshMillis.class));

    environment.lifecycle().manage(new Managed() {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, r -> {
            Thread t = new Thread(r, "InitializerThread");
            t.setDaemon(true);
            return t;
        });

        @Override
        public void stop() throws Exception {
            scheduler.shutdownNow();
        }

        @Override
        public void start() throws Exception {
            Future<?> init = scheduler.submit(initializers);
            init.get();
            scheduler.scheduleAtFixedRate(initializers, refreshMillis, refreshMillis, MILLISECONDS);
        }
    });

    final AlleleResource alleleResource = injector.getInstance(AlleleResource.class);
    environment.jersey().register(alleleResource);

    final GroupResource groupResource = injector.getInstance(GroupResource.class);
    environment.jersey().register(groupResource);

    final MatchResource matchResource = injector.getInstance(MatchResource.class);
    environment.jersey().register(matchResource);

    environment.jersey().register(new org.nmdp.service.epitope.resource.impl.ExceptionMapper());

    // eriktodo: multibinder for health checks
    final GlClientHealthCheck glClientHealthCheck = injector.getInstance(GlClientHealthCheck.class);
    environment.healthChecks().register("glClient", glClientHealthCheck);
}

From source file:com.heliosapm.tsdblite.json.JSON.java

/**
 * Serializes the passed object and pipes back the results in an InputStream to read it back.
 * Spawns a thread to run the pipe out so the calling thread only needs to read the returned input stream.
 * If the serialization fails, the worker thread will close the inoput stream to signal the failure.
 * @param obj The object to serialize/*from  w  w  w .  ja v  a2s  .  c o m*/
 * @return an InputStream to read back the JSON serialized object 
 */
public static InputStream serializeLoopBack(final Object obj) {
    if (obj == null)
        throw new IllegalArgumentException("The passed object was null");
    try {
        final PipedInputStream pin = new PipedInputStream(2048);
        final PipedOutputStream pout = new PipedOutputStream(pin);
        final Thread t = new Thread("serializeLoopBackThread") {
            @Override
            public void run() {
                try {
                    serialize(obj, pout);
                } catch (Exception ex) {
                    try {
                        pin.close();
                    } catch (Exception x) {
                        /* No Op */}
                }
            }
        };
        t.setDaemon(true);
        t.start();
        return pin;
    } catch (Exception ex) {
        throw new RuntimeException("Failed to pipe serialized object", ex);
    }
}

From source file:client.gui.ConnectionDialog.java

public void actionPerformed(final ActionEvent event) {

    String nick = null;/*from   w  ww .  jav a 2 s.co m*/
    String host = null;
    int port = 0;

    if (event.getSource() == connect) {
        nick = this.nick.getText();
        host = this.host.getText();
        try {
            port = Integer.parseInt(this.port.getText());
        } catch (NumberFormatException e1) {
            new MyDialog("Port number must be integer").setVisible(true);
            return;
        }
    } else if (event.getSource() == connectDev) {
        nick = generateNick();
        host = "localhost";
        port = 5555;
    } else if (event.getSource() == connectSame) {
        nick = "a";
        host = "localhost";
        port = 5555;
    }

    if (port <= 0) {
        new MyDialog("Port number must be bigger than 0").setVisible(true);
        return;
    }

    Socket socket;
    BufferedReader in;

    try {
        socket = new Socket(host, port);
        GlobalVariables.out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (java.net.UnknownHostException e2) {
        new MyDialog("Unknown host").setVisible(true);
        return;
    } catch (IOException e3) {
        new MyDialog("Connection unsuccessful").setVisible(true);
        GlobalVariables.connected = false;
        return;
    } catch (java.lang.IllegalArgumentException e4) {
        new MyDialog("Port number is too big").setVisible(true);
        return;
    }

    System.out.println("Nick: " + nick);

    final JSONArray toSend = new JSONArray();
    try {
        toSend.put(new JSONObject().put("action", "first_connection"));
        toSend.put(new JSONObject().put("nick", nick));
    } catch (JSONException e1) {
        e1.printStackTrace();
    }

    GlobalVariables.daemon = true;
    GlobalVariables.me.setNick(nick);
    GlobalVariables.connect.setEnabled(false);
    GlobalVariables.connected = true;
    setVisible(false);
    GlobalVariables.out.println(toSend);
    Thread thread;
    thread = new ReceivingData(in);
    thread.setDaemon(true);
    thread.start();
}

From source file:com.orange.mmp.module.osgi.MMPOSGiContainer.java

@Override
public void initialize() throws MMPException {
    if (!this.isRunning) {
        //Initialize parent (Felix container)
        super.initialize();

        this.runningModules = new Module[0];
        this.isRunning = true;
        try {//from w ww  .  j  av  a  2  s  .c  o m
            Thread m4mThread = new Thread(this);
            m4mThread.setDaemon(true);
            m4mThread.start();
        } catch (IllegalStateException ise) {
            throw new MMPRuntimeException("Failed to start WidgetManager daemon", ise);
        }

    }
}

From source file:arena.fileupload.transform.ExternalProcessFileTransform.java

public void transform(File in, File out) throws IOException {
    String[] resizeCmdArgs = buildParsedCommandLine(in, out);
    if (System.getProperty("os.name", "").toUpperCase().startsWith("WINDOWS")) {
        String winPrefix[] = new String[resizeCmdArgs.length + 2];
        winPrefix[0] = "cmd.exe";
        winPrefix[1] = "/C";
        System.arraycopy(resizeCmdArgs, 0, winPrefix, 2, resizeCmdArgs.length);
        resizeCmdArgs = winPrefix;//from  ww  w .ja v a  2s  . c om
    }
    log.debug("Launching external process: " + Arrays.asList(resizeCmdArgs)); //comment out
    Process p = Runtime.getRuntime().exec(resizeCmdArgs);
    Thread thStdOut = new Thread(new LoggingStreamConsumer(p.getInputStream(), logEncoding));
    Thread thStdErr = new Thread(new LoggingStreamConsumer(p.getErrorStream(), logEncoding));
    thStdOut.setDaemon(true);
    thStdOut.start();
    thStdErr.setDaemon(true);
    thStdErr.start();
    try {
        int result = p.waitFor();
        log.info(getClass().getName() + " process completed with exit code " + result);
    } catch (InterruptedException err) {
        log.error("Timeout waiting for " + getClass().getName() + " process", err);
    }
}

From source file:com.larvalabs.megamap.MegaMap.java

private void init(CacheManager manager, boolean persistent) throws CacheException {
    cacheQueue = new UnboundedFifoBuffer();
    softMap = new ReferenceMap();
    keySet = new HashSet();
    cache = new Cache(storeName, 1, true, true, 0L, 0L, persistent, 2147483647L);
    manager.addCache(cache);//  www  .j a va2 s  .c o  m
    running = true;
    Thread thread = new Thread(this, "MegaMap-" + storeName);
    thread.setDaemon(false);
    thread.start();
}

From source file:com.all.download.manager.ScheduledExecutorServiceSingleton.java

@Override
public Thread newThread(Runnable runnable) {
    StringBuilder sb = new StringBuilder();
    sb.append("download-thread-");
    sb.append(threadNumber.incrementAndGet());

    Thread thread = new Thread(runnable, sb.toString());
    thread.setDaemon(true);

    return thread;
}

From source file:com.facebook.stetho.server.LocalSocketHttpServer.java

private void listenOnAddress(String address) throws IOException {
    mServerSocket = bindToSocket(address);
    LogUtil.i("Listening on @" + address);

    HttpParams params = null;//from  w w w . j av  a  2 s.c o m
    HttpService service = null;

    while (!Thread.interrupted()) {
        LocalSocketHttpServerConnection connection = new LocalSocketHttpServerConnection();
        try {
            // Use previously accepted socket the first time around, otherwise wait to
            // accept another.
            LocalSocket socket = mServerSocket.accept();

            if (params == null) {
                params = createParams();
            }
            if (service == null) {
                service = createService(params);
            }
            connection.bind(socket, params);

            // Start worker thread
            Thread t = new WorkerThread(service, connection);
            t.setDaemon(true);
            t.start();
        } catch (SocketException se) {
            // ignore exception if interrupting the thread
            if (!Thread.interrupted()) {
                LogUtil.w(se, "I/O error");
            }
        } catch (InterruptedIOException ex) {
            break;
        } catch (IOException e) {
            LogUtil.w(e, "I/O error initialising connection thread");
            break;
        }
    }
}

From source file:LessonSaver.ServerBridge.java

public ServerBridge() {
    // ?    ? ? ? 
    if (new File("frameQueue.dat").exists()) //?  ?? ?   ?     
    {/*  w w  w . j  av a2 s. c o m*/
        try {
            FileInputStream FIS = new FileInputStream("frameQueue.dat");
            try {
                ObjectInputStream OIS = new ObjectInputStream(FIS);
                try {
                    this.frameQueue = (ConcurrentLinkedQueue<ServerBridge.Frame>) OIS.readObject();
                } catch (ClassNotFoundException ex) {
                }
                OIS.close();
            } catch (IOException ex) {
            }
        } catch (FileNotFoundException ex) {
        }
    } else //?  ??  ?  
    {
        this.frameQueue = new ConcurrentLinkedQueue<>();
    }

    this.bridge = new Bridge();
    Thread T = new Thread(this.bridge);
    T.setDaemon(true);
    T.start();
}