List of usage examples for java.lang Thread setDaemon
public final void setDaemon(boolean on)
From source file:com.google.dart.compiler.metrics.Tracer.java
private BlockingQueue<TraceEvent> openLogWriter(final Writer writer, final String fileName) { try {//from w ww . j a v a2 s . c o m if (outputFormat.equals(Format.HTML)) { writer.write("<HTML isdump=\"true\"><body>" + "<style>body {font-family:Helvetica; margin-left:15px;}</style>" + "<h2>Performance dump from GWT</h2>" + "<div>This file contains data that can be viewed with the " + "<a href=\"http://code.google.com/speedtracer\">SpeedTracer</a> " + "extension under the <a href=\"http://chrome.google.com/\">" + "Chrome</a> browser.</div><p><span id=\"info\">" + "(You must install the SpeedTracer extension to open this file)</span></p>" + "<div style=\"display: none\" id=\"traceData\" version=\"0.17\">\n"); } } catch (IOException e) { System.err .println("Unable to write to dart.speedtracerlog '" + (fileName == null ? "" : fileName) + "'"); e.printStackTrace(); return null; } final BlockingQueue<TraceEvent> eventQueue = new LinkedBlockingQueue<TraceEvent>(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { // Wait for the other thread to drain the queue. eventQueue.add(shutDownSentinel); shutDownLatch.await(); } catch (InterruptedException e) { // Ignored } } }); // Background thread to write SpeedTracer events to log Thread logWriterWorker = new LogWriterThread(writer, fileName, eventQueue); // Lower than normal priority. logWriterWorker.setPriority((Thread.MIN_PRIORITY + Thread.NORM_PRIORITY) / 2); /* * This thread must be daemon, otherwise shutdown hooks would never begin to * run, and an app wouldn't finish. */ logWriterWorker.setDaemon(true); logWriterWorker.setName("SpeedTracerLogger writer"); logWriterWorker.start(); return eventQueue; }
From source file:com.raddle.tools.ClipboardTransferMain.java
public ClipboardTransferMain() { super();/*from w w w . jav a 2 s .c om*/ initGUI(); //// ?? Properties p = new Properties(); File pf = new File(System.getProperty("user.home") + "/clip-trans/conf.properties"); if (pf.exists()) { try { p.load(new FileInputStream(pf)); serverAddrTxt.setText(StringUtils.defaultString(p.getProperty("server.addr"))); portTxt.setText(StringUtils.defaultString(p.getProperty("local.port"))); modifyClipChk.setSelected("true".equals(p.getProperty("allow.modify.local.clip"))); autoChk.setSelected("true".equals(p.getProperty("auto.modify.remote.clip"))); } catch (Exception e) { updateMessage(e.getMessage()); } } m.addListener(new ClipboardListener() { @Override public void contentChanged(Clipboard clipboard) { setRemoteClipboard(false); } }); m.setEnabled(autoChk.isSelected()); // try { pasteImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/clipboard_paste.png")); grayImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/clipboard_gray.png")); sendImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/mail-send.png")); BufferedImage taskImage = ImageIO.read(ClipboardTransferMain.class.getResourceAsStream("/taskbar.png")); setIconImage(taskImage); SystemTray systemTray = SystemTray.getSystemTray(); trayIcon = new TrayIcon(grayImage, "??"); systemTray.add(trayIcon); //// trayIcon.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) {// ??? if (ClipboardTransferMain.this.isVisible()) { ClipboardTransferMain.this.setState(ICONIFIED); } else { ClipboardTransferMain.this.setVisible(true); ClipboardTransferMain.this.setState(NORMAL); } } } }); ////// event this.addWindowListener(new WindowAdapter() { @Override public void windowIconified(WindowEvent e) { ClipboardTransferMain.this.setVisible(false); super.windowIconified(e); } @Override public void windowClosing(WindowEvent e) { File pf = new File(System.getProperty("user.home") + "/clip-trans/conf.properties"); pf.getParentFile().mkdirs(); try { Properties op = new Properties(); op.setProperty("server.addr", serverAddrTxt.getText()); op.setProperty("local.port", portTxt.getText()); op.setProperty("allow.modify.local.clip", modifyClipChk.isSelected() + ""); op.setProperty("auto.modify.remote.clip", autoChk.isSelected() + ""); FileOutputStream os = new FileOutputStream(pf); op.store(os, "clip-trans"); os.flush(); os.close(); } catch (Exception e1) { } shutdown(); super.windowClosing(e); } }); } catch (Exception e) { updateMessage(e.getMessage()); } Thread thread = new Thread() { @Override public void run() { while (true) { try { String poll = iconQueue.take(); if ("send".equals(poll)) { trayIcon.setImage(grayImage); } else if ("paste".equals(poll)) { Thread.sleep(20); trayIcon.setImage(grayImage); } } catch (InterruptedException e1) { return; } } } }; thread.setDaemon(true); thread.start(); }
From source file:com.hubcap.task.TaskRunner.java
/** * Processes the 'START' state//from w w w . j a v a 2 s . com */ protected void processStateStart() { if (this.taskState == TaskRunnerState.START) { if (helperPool == null) { // get a stable thread count up to MAX_HELPER_THREADS based on // CPU LOAD per helper int maxHelpers = ThreadUtils.getStableThreadCount(CPU_LOAD_TRH, CPU_WAIT_TRH, CPU_COMPUTE_TRH, Constants.MAX_HELPER_THREADS); if (this.helperFactory == null) { this.helperFactory = new ThreadFactory() { @Override public Thread newThread(Runnable r) { if (helpers.contains(r)) { throw new IllegalStateException("Cannot add duplicate runnable to running tasks"); } Thread thread = new Thread(r); thread.setDaemon(false); thread.setName("TaskRunnerHelper-" + helperCount.getAndIncrement()); taskThreads.add(thread); return thread; } }; } // create the pool but don't fire up any helpers helperPool = Executors.newFixedThreadPool(maxHelpers, TaskRunner.taskRunnerThreadFactory); } TaskRunnerListener[] list = listeners.toArray(new TaskRunnerListener[listeners.size()]); for (int i = 0; i < list.length; i++) { TaskRunnerListener listener = list[i]; listener.onTaskStart(this); } try { // create the task model using the input arguments setTaskState(TaskRunnerState.ACTIVE); this.taskModel = CLIOptionBuilder.buildInputOptionsModel(this.taskArgs); synchronized (sharedResource_resultModel) { sharedResource_resultModel.addTaskModel(taskModel); } } catch (ParseException e) { ErrorUtils.printStackTrace(e); setTaskState(TaskRunnerState.ERROR); this.canRecoverFromError = true; this.errorMessage = "Inputs were malformed, please try again"; } } else { System.err.println("Can't Start...Task State is: " + this.taskState); } }
From source file:gtu.jpa.hibernate.Rcdf002eDBUI.java
private void executeBtnActionPerformed(ActionEvent evt) { try {//from w ww .j av a 2s . c om final JdbcFastQuery exe = new JdbcFastQuery(); JdbcFastQuery.debugMode = isDebug.isSelected(); Log.Setting.NORMAL.apply(); exe.setOut(new PrintStream(new PrintStreamAdapter("big5") { @Override public void println(String message) { Log.debug(message); if (StringUtils.length(logArea.getText()) > 500) { logArea.setText(""); } logArea.append(message + "\n"); } })); setTitle("......."); Thread thread = new Thread(Thread.currentThread().getThreadGroup(), new Runnable() { @Override public void run() { try { long current = System.currentTimeMillis(); exe.execute(); current = System.currentTimeMillis() - current; setTitle("xml : ?"); JCommonUtil._jOptionPane_showMessageDialog_info( "xml : ?, :" + current + "\n?!"); xmlFileText.setText(getBulkFile().getAbsolutePath()); } catch (Exception ex) { setTitle(":" + ex.getMessage()); JCommonUtil.handleException(ex); } } }, "xxxxxxxxxxxxxxxxxcxccx"); thread.setDaemon(true); thread.start(); } catch (Exception ex) { setTitle(":" + ex.getMessage()); JCommonUtil.handleException(ex); } }
From source file:ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository.java
/** * Callback for the preview renderer to indicate a finished rendering * operation.//from w ww . jav a 2 s. c o m * * @param resource * the resource */ void previewCreated(Resource<?> resource) { synchronized (currentPreviewOperations) { // Do the cleanup for (Iterator<PreviewOperation> i = currentPreviewOperations.iterator(); i.hasNext();) { PreviewOperation op = i.next(); Resource<?> r = op.getResource(); if (r.equals(resource)) { logger.debug("Preview creation of {} finished", r.getURI()); i.remove(); PreviewOperation o = previews.get(r.getURI()); // In the meantime, someone may have canceled this operation and // created a new one if (op == o) previews.remove(r.getURI()); break; } } // Is there more work to do? if (!previewOperations.isEmpty() && currentPreviewOperations.size() < maxPreviewOperations) { // Get the next operation and do the bookkeeping PreviewOperation op = previewOperations.remove(); Resource<?> r = op.getResource(); currentPreviewOperations.add(op); // Finally start the generation PreviewGeneratorWorker previewWorker = new PreviewGeneratorWorker(this, r, environment, op.getLanguages(), op.getStyles(), op.getFormat()); op.setWorker(previewWorker); Thread t = new Thread(previewWorker); t.setPriority(Thread.MIN_PRIORITY); t.setDaemon(true); logger.debug("Starting creation of preview of {}", r.getURI()); logger.trace("There are {} more preview operations waiting", previewOperations.size()); logger.trace("Currently using {} out of {} preview creation slots", currentPreviewOperations.size(), maxPreviewOperations); t.start(); } else { logger.debug("No more resources queued for preview creation"); } } }
From source file:org.smartfrog.services.anubis.Node.java
public void start() { Thread daemon = new Thread(new Runnable() { @Override// w w w . ja v a2s . c o m public void run() { try { startLatch.countDown(); startLatch.await(); Thread.sleep(500); } catch (InterruptedException e1) { return; } for (int counter = 0; counter < messagesToSend; counter++) { try { Thread.sleep(RANDOM.nextInt(maxSleep)); } catch (InterruptedException e) { return; } SendHistory sent = new SendHistory(System.currentTimeMillis(), counter); send(counter); sendHistory.add(sent); } try { for (CountDownLatch latch : msgReceivedLatches.values()) { latch.await(); } endLatch.countDown(); endLatch.await(); Thread.sleep(500); } catch (InterruptedException e) { return; } } }, "Run Thread for: " + context.getBean(Identity.class).toString()); daemon.setDaemon(true); daemon.start(); }
From source file:UniqueInstance.java
/** * Essaye de dmarrer le gestionnaire d'instance unique. Si l'initialisation a russi, c'est que l'instance est * unique. Sinon, c'est qu'une autre instance de l'application est dj lance. L'appel de cette mthode prvient * l'application dj lance qu'une autre vient d'essayer de se connecter. * * @return {@code true} si l'instance de l'application est unique. *///from w ww .j a va 2s . co m public boolean launch() { /* Indique si l'instance du programme est unique. */ boolean unique; try { /* On cre une socket sur le port dfini. */ final ServerSocket server = new ServerSocket(port); /* Si la cration de la socket russit, c'est que l'instance du programme est unique, aucune autre n'existe. */ unique = true; /* Si il y a des actions faire lorsqu'une autre instance essaye de dmarrer... */ if (runOnReceive != null) { /* On lance un Thread d'coute sur ce port. */ Thread portListenerThread = new Thread() { @Override public void run() { /* Tant que l'application est lance... */ while (true) { try { /* On attend qu'une socket se connecte sur le serveur. */ final Socket socket = server.accept(); /* Si une socket est connecte, on coute le message envoy dans un nouveau Thread. */ new Thread() { @Override public void run() { receive(socket); } }.start(); } catch (IOException e) { Logger.getLogger("UniqueInstance") .warning("Attente de connexion de socket choue."); } } } }; /* Le Thread d'coute de port est dmon. */ portListenerThread.setDaemon(true); /* On dmarre le Thread. */ portListenerThread.start(); } } catch (IOException e) { /* Si la cration de la socket choue, c'est que l'instance de n'est pas unique, une autre n'existe. */ unique = false; /* Si des actions sont prvues par l'instance dj lance... */ if (runOnReceive != null) { /* * Dans ce cas, on envoie un message l'autre instance de l'application pour lui demander d'avoir le * focus (par exemple). */ send(); } } return unique; }
From source file:ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository.java
/** * Creates the previews for this resource in all languages and for all known * image styles. The implementation ensures that there is only one preview * renderer running per resource./*from w ww. j ava 2 s . c om*/ * * @param resource * the resource * @param languages * the languages to build the previews for */ protected void createPreviews(final Resource<?> resource, Language... languages) { ResourceURI uri = resource.getURI(); // Compile the full list of image styles if (imageStyleTracker == null) { logger.info("Skipping preview generation for {}: image styles are unavailable", uri); return; } final List<ImageStyle> previewStyles = new ArrayList<ImageStyle>(); // Add the global image styles that have the preview flag turned on for (ImageStyle s : imageStyleTracker.getImageStyles()) { if (s.isPreview()) { previewStyles.add(s); logger.debug("Preview images will be generated for {}", s); } else { logger.debug("Preview image generation will be skipped for {}", s); } } // Add the site's preview image styles as well as for (Module m : getSite().getModules()) { for (ImageStyle s : m.getImageStyles()) { if (s.isPreview()) { previewStyles.add(s); logger.debug("Preview images will be generated for {}", s); } else { logger.debug("Preview image generation will be skipped for {}", s); } } } // If no language has been specified, we create the preview for all // languages if (languages == null || languages.length == 0) { languages = uri.getSite().getLanguages(); } // Create the previews PreviewOperation previewOp = null; synchronized (currentPreviewOperations) { // is there an existing operation for this resource? If so, simply update // it and be done. previewOp = previews.get(uri); if (previewOp != null) { PreviewGeneratorWorker worker = previewOp.getWorker(); if (worker != null) { logger.info("Canceling current preview generation for {} in favor of more recent data", uri); worker.cancel(); } } // Otherwise, a new preview generator needs to be started. previewOp = new PreviewOperation(resource, Arrays.asList(languages), previewStyles, ImageStyleUtils.DEFAULT_PREVIEW_FORMAT); // Make sure nobody is working on the same resource at the moment if (currentPreviewOperations.contains(previewOp)) { logger.debug("Queing concurring creation of preview for {}", uri); previews.put(uri, previewOp); previewOperations.add(previewOp); return; } // If there is enough being worked on already, there is nothing we can do // right now, the work will be picked up later on if (currentPreviewOperations.size() >= maxPreviewOperations) { logger.debug("Queing creation of preview for {}", uri); previews.put(uri, previewOp); previewOperations.add(previewOp); logger.debug("Preview generation queue now contains {} resources", previews.size()); return; } // It seems like it is safe to start the preview generation currentPreviewOperations.add(previewOp); PreviewGeneratorWorker previewWorker = new PreviewGeneratorWorker(this, previewOp.getResource(), environment, previewOp.getLanguages(), previewOp.getStyles(), previewOp.getFormat()); previewOp.setWorker(previewWorker); Thread t = new Thread(previewWorker); t.setPriority(Thread.MIN_PRIORITY); t.setDaemon(true); logger.debug("Creating preview of {}", uri); t.start(); } }
From source file:com.runwaysdk.mobile.IdConversionTest.java
public void testConvertGlobalAndLocalIds() { mobileIdToSessionId = new DualHashBidiMap(); // Maps a session to a bi-directional hash map BidiMap<globalId, localId> final HashMap<String, BidiMap> idMap = new HashMap<String, BidiMap>(); // Log all our threads in, and map the session ids to our mobile ids. // Do it twice so that we can ensure we can update an existing sessionId mapping with no problem. for (int i = 0; i < 2; ++i) { lock = new CountDownLatch(mobileIds.length); for (final String mobileId : mobileIds) { Thread t = new Thread() { public void run() { idConverter = IdConverter.getInstance(); ClientSession clientSession = ClientSession.createUserSession("default", customUsernameAndPassword, customUsernameAndPassword, new Locale[] { CommonProperties.getDefaultLocale() }); mobileIdToSessionId.put(mobileId, clientSession.getSessionId()); idConverter.mapSessionIdToMobileId(clientSession.getSessionId(), mobileId); onThreadStart(mobileId); onThreadEnd();/*from ww w. j a v a2 s . c om*/ clientSession.logout(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); } System.out.println("Session ids mapped to mobile ids."); // Generate a bunch of local ids lock = new CountDownLatch(mobileIds.length); for (final String mobileId : mobileIds) { Thread t = new Thread() { public void run() { onThreadStart(mobileId); BidiMap globalIdToLocalIdMap = new DualHashBidiMap(); idMap.put(mobileId, globalIdToLocalIdMap); for (String globalId : globalIds) { String localId = idConverter.generateLocalIdFromGlobalId(mobileId, globalId); globalIdToLocalIdMap.put(globalId, localId); //System.out.println(mobileId + "\n" + globalId + "\n" + localId + "\n\n"); } onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("localIds generated and mapped to globalIds"); // Assert that we can get the globalId back from the localId lock = new CountDownLatch(mobileIds.length); for (final String mobileId : mobileIds) { Thread t = new Thread() { @SuppressWarnings("unchecked") public void run() { onThreadStart(mobileId); BidiMap globalIdToLocalIdMap = idMap.get(mobileId); Collection<String> localIds = globalIdToLocalIdMap.values(); for (String localId : localIds) { String globalId = idConverter.getGlobalIdFromLocalId(mobileId, localId); assertEquals((String) globalIdToLocalIdMap.getKey(localId), globalId); } onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("globalIds retrieved from localIds."); // Generate local ids from the same mobile ids again and make sure we got the same local ids lock = new CountDownLatch(mobileIds.length); for (final String mobileId : mobileIds) { Thread t = new Thread() { public void run() { onThreadStart(mobileId); BidiMap globalIdToLocalIdMap = idMap.get(mobileId); for (String globalId : globalIds) { String localId = idConverter.generateLocalIdFromGlobalId(mobileId, globalId); assertEquals(localId, (String) globalIdToLocalIdMap.get(globalId)); } onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("Generated local ids from the same mobile ids."); // Delete all the global ids idConverter = IdConverter.getInstance(); lock = new CountDownLatch(globalIds.length); for (final String globalId : globalIds) { Thread t = new Thread() { public void run() { waitRandomAmount(); //System.out.println("Invalidating globalId " + globalId); idConverter.invalidateGlobalId(globalId); onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("Deleted all global ids."); // Try to retrieve them and assert that they're null. lock = new CountDownLatch(mobileIds.length); for (final String mobileId : mobileIds) { Thread t = new Thread() { public void run() { onThreadStart(mobileId); BidiMap globalIdToLocalIdMap = idMap.get(mobileId); for (String globalId : globalIds) { try { String retval = idConverter.getGlobalIdFromLocalId(mobileId, (String) globalIdToLocalIdMap.get(globalId)); fail("The globalId is still mapped. globalId = " + retval); } catch (IdConversionException e) { } } onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("Tried to retrieve previously deleted global ids."); // Generate more localIds, just to flex the stacks lock = new CountDownLatch(mobileIds.length); for (final String mobileId : mobileIds) { Thread t = new Thread() { public void run() { onThreadStart(mobileId); BidiMap globalIdToLocalIdMap = new DualHashBidiMap(); idMap.put(mobileId, globalIdToLocalIdMap); for (String globalId : globalIds) { String localId = idConverter.generateLocalIdFromGlobalId(mobileId, globalId); globalIdToLocalIdMap.put(globalId, localId); } onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("Generated more localIds, to flex the stacks."); // Assert that we can get the globalId back from the localId lock = new CountDownLatch(mobileIds.length); for (final String mobileId : mobileIds) { Thread t = new Thread() { @SuppressWarnings("unchecked") public void run() { onThreadStart(mobileId); BidiMap globalIdToLocalIdMap = idMap.get(mobileId); Collection<String> localIds = globalIdToLocalIdMap.values(); for (String localId : localIds) { String globalId = idConverter.getGlobalIdFromLocalId(mobileId, localId); assertEquals((String) globalIdToLocalIdMap.getKey(localId), globalId); } onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("globalids retrieved from localids."); // Delete all the global ids idConverter = IdConverter.getInstance(); lock = new CountDownLatch(globalIds.length); for (final String globalId : globalIds) { Thread t = new Thread() { public void run() { waitRandomAmount(); //System.out.println("Invalidating globalId " + globalId); idConverter.invalidateGlobalId(globalId); onThreadEnd(); } }; t.setDaemon(true); t.start(); } waitOnThreads(); System.out.println("Deleted all global id, test complete."); }
From source file:gtu.jpa.hibernate.Rcdf002eDBUI.java
private JButton getMakeExcelBtn() { if (makeExcelBtn == null) { makeExcelBtn = new JButton(); makeExcelBtn.setText("\u7522\u751fexcel"); makeExcelBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { try { File file = JCommonUtil.filePathCheck(srcDirText.getText(), "", true); final Rcdf002eExcelMaker exe = new Rcdf002eExcelMaker(); exe.setBaseDir(file); Log.Setting.NORMAL.apply(); exe.setOut(new PrintStream(new PrintStreamAdapter("big5") { @Override public void println(String message) { Log.debug(message); if (StringUtils.length(logArea.getText()) > 500) { logArea.setText(""); }// w w w .j a v a 2 s. c o m logArea.append(message + "\n"); } })); setTitle("......."); Thread thread = new Thread(Thread.currentThread().getThreadGroup(), new Runnable() { @Override public void run() { try { long current = System.currentTimeMillis(); exe.execute(); current = System.currentTimeMillis() - current; setTitle("excel?"); JCommonUtil._jOptionPane_showMessageDialog_info( "excel : ?,:" + current + "\n?!"); } catch (Exception ex) { setTitle(":" + ex.getMessage()); JCommonUtil.handleException(ex); } } }, "xxxxxxxxxxxxxxxxxcxccx"); thread.setDaemon(true); thread.start(); } catch (Exception ex) { setTitle(":" + ex.getMessage()); JCommonUtil.handleException(ex); } } }); } return makeExcelBtn; }