List of usage examples for java.lang Thread setDaemon
public final void setDaemon(boolean on)
From source file:de.bayern.gdi.gui.Controller.java
/** * Handle the service selection./* w w w.j a v a 2 s . c o m*/ * * @param event The mouse click event. */ @FXML protected void handleServiceSelect(MouseEvent event) { if (event.getEventType().equals(MouseEvent.MOUSE_CLICKED)) { if (event.getClickCount() == 1) { clearUserNamePassword(); ServiceModel serviceModel = (ServiceModel) this.serviceList.getSelectionModel().getSelectedItems() .get(0); if (serviceModel != null) { serviceSelection.setDisable(true); serviceURL.getScene().setCursor(Cursor.WAIT); setStatusTextUI(I18n.format("status.checking-auth")); Task task = new Task() { protected Integer call() { try { selectService(serviceModel.getItem()); return 0; } finally { serviceSelection.setDisable(false); serviceURL.getScene().setCursor(Cursor.DEFAULT); } } }; Thread th = new Thread(task); th.setDaemon(true); th.start(); } } else if (event.getClickCount() > 1) { clearUserNamePassword(); resetGui(); } } }
From source file:javarestart.WebClassLoader.java
private void preLoadInitial() { preloading = true;//w w w. j a v a2s . c o m Thread thread = new Thread() { @Override public void run() { try { InputStream in = new URL(baseURL.getProtocol(), baseURL.getHost(), baseURL.getPort(), baseURL.getPath() + "?bundle=initial").openStream(); while (true) { int nameLength = Integer.parseInt(Utils.readAsciiLine(in), 16); if (nameLength == 0) { return; } String name = Utils.readAsciiLine(in); //TODO: name can be not Ascii curLoading = name; int resLength = Integer.parseUnsignedInt(Utils.readAsciiLine(in), 16); if (resLength != -1) { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); Utils.copy(in, buffer, resLength); initialBundle.put(name, buffer.toByteArray()); Utils.readAsciiLine(in); } else { initialBundle.put(name, null); } ResourceRequest resourceRequest = WebClassLoader.this.resourceRequest.get(); if ((resourceRequest != null) && isPreLoaded(resourceRequest.getRequest())) { resourceRequest.contentReady(getPreloadResource(resourceRequest.getRequest())); WebClassLoader.this.resourceRequest.compareAndSet(resourceRequest, null); } } } catch (Throwable e) { e.printStackTrace(); } finally { preloading = false; curLoading = null; } } }; thread.setDaemon(true); thread.start(); }
From source file:de.bayern.gdi.gui.Controller.java
/** * Select a service according to service url textfield. * * @param downloadConf Loaded download config, null if a service is chosen * from an URL or the service List//from w ww . j a va 2s . c o m */ protected void doSelectService(DownloadConfig downloadConf) { log.info("Using download config: " + downloadConf); dataBean.resetSelectedService(); serviceSelection.setDisable(true); serviceURL.getScene().setCursor(Cursor.WAIT); serviceURL.setDisable(true); resetGui(); new Thread(() -> { try { ServiceModel serviceModel = (ServiceModel) serviceList.getSelectionModel().getSelectedItems() .get(0); Service service = null; if (serviceModel != null && serviceModel.getUrl().toString().equals(serviceURL.getText())) { if (ServiceChecker.isReachable(serviceModel.getItem().getServiceURL())) { service = serviceModel.getItem(); service.setPassword(servicePW.getText()); service.setUsername(serviceUser.getText()); } } else { URL sURL = new URL(serviceURL.getText()); if (ServiceChecker.isReachable(sURL)) { service = new Service(sURL, "", true, serviceUser.getText(), servicePW.getText()); } } if (service == null) { setStatusTextUI(I18n.format("status.service-timeout")); dataBean.setSelectedService(null); serviceSelection.setDisable(false); serviceURL.setDisable(false); serviceURL.getScene().setCursor(Cursor.DEFAULT); return; } serviceSelection.setDisable(true); serviceURL.getScene().setCursor(Cursor.WAIT); setStatusTextUI(I18n.format("status.checking-auth")); serviceURL.setDisable(true); Service finalService = service; Task task = new Task() { protected Integer call() { try { boolean serviceSelected = selectService(finalService); if (serviceSelected) { chooseSelectedService(downloadConf); } return 0; } finally { serviceSelection.setDisable(false); serviceURL.getScene().setCursor(Cursor.DEFAULT); serviceURL.setDisable(false); validateChainContainerItems(); } } }; Thread th = new Thread(task); th.setDaemon(true); th.start(); } catch (MalformedURLException e) { setStatusTextUI(I18n.format("status.no-url")); log.error(e.getMessage(), e); serviceSelection.setDisable(false); serviceURL.getScene().setCursor(Cursor.DEFAULT); serviceURL.setDisable(false); } }).start(); }
From source file:gtu._work.mvn.MavenRepositoryUI.java
void reloadRepositoryDir() { if (!repositoryDir.exists()) { setTitle("repository not exist! : " + repositoryDir); return;//from w ww . j a va 2s.co m } Thread initThread = new Thread(Thread.currentThread().getThreadGroup(), new Runnable() { public void run() { long startTime = System.currentTimeMillis(); setTitle("loading... " + repositoryDir); List<File> pomList = new ArrayList<File>(); FileUtil.searchFileMatchs(repositoryDir, ".*\\.pom", pomList); pomFileList = new HashSet<PomFile>(); pomFileJarList = new HashSet<PomFile>(); pomFileMap = new HashMap<DependencyKey, PomFile>(); loadPomList(pomList); long endTime = System.currentTimeMillis() - startTime; String message = "load completed! \ntime:" + endTime + ", poms:" + pomFileList.size() + ", jars:" + pomFileJarList.size(); setTitle(message); JOptionPaneUtil.newInstance().iconInformationMessage().showMessageDialog(message, "SCAN COMPLETED"); resetUIStatus(); } }, "reloadRepositoryDir"); initThread.setDaemon(true); initThread.start(); }
From source file:com.limegroup.gnutella.RouterService.java
/** * Starts a manual GC thread.//from ww w .j ava 2 s . co m */ private void startManualGCThread() { Thread t = new ManagedThread(new Runnable() { public void run() { while (true) { try { Thread.sleep(5 * 60 * 1000); } catch (InterruptedException ignored) { } LOG.trace("Running GC"); System.gc(); LOG.trace("GC finished, running finalizers"); System.runFinalization(); LOG.trace("Finalizers finished."); } } }, "ManualGC"); t.setDaemon(true); t.start(); LOG.trace("Started manual GC thread."); }
From source file:de.bayern.gdi.gui.Controller.java
/** * Handle search and filter the service list. * * @param event the event// w ww .jav a 2 s. c o m */ @FXML protected void handleSearch(KeyEvent event) { if (!catalogReachable) { setStatusTextUI(I18n.getMsg("status.catalog-not-available")); } String currentText = this.searchField.getText(); this.serviceList.getItems().clear(); dataBean.resetCatalogLists(); if (currentText == null || currentText.isEmpty()) { this.serviceList.setItems(this.dataBean.getServicesAsList()); } String searchValue = currentText == null ? "" : currentText.toUpperCase(); ObservableList<ServiceModel> subentries = FXCollections.observableArrayList(); ObservableList<ServiceModel> all = this.dataBean.getServicesAsList(); for (ServiceModel entry : all) { boolean match = entry.getName().toUpperCase().contains(searchValue); if (match) { subentries.add(entry); } } if (currentText != null && currentText.length() > 2) { Task task = new Task() { @Override protected Integer call() throws Exception { Platform.runLater(() -> { searchButton.setVisible(false); searchButton.setManaged(false); progressSearch.setVisible(true); progressSearch.setManaged(true); }); if (catalogReachable) { List<Service> catalog = dataBean.getCatalogService().getServicesByFilter(currentText); for (Service entry : catalog) { dataBean.addCatalogServiceToList(entry); } Platform.runLater(() -> { for (Service entry : catalog) { subentries.add(new ServiceModel(entry)); } }); } Platform.runLater(() -> { progressSearch.setVisible(false); progressSearch.setManaged(false); searchButton.setManaged(true); searchButton.setVisible(true); }); return 0; } }; Thread th = new Thread(task); if (catalogReachable) { setStatusTextUI(I18n.getMsg("status.calling-service")); } th.setDaemon(true); th.start(); } this.serviceList.setItems(subentries); }
From source file:de.huxhorn.lilith.swing.MainFrame.java
private static void executeCommand(String[] cmdArray) { final Logger logger = LoggerFactory.getLogger(MainFrame.class); if (cmdArray == null) { return;/*from ww w .j a v a 2 s .c o m*/ } Runtime runtime = Runtime.getRuntime(); String commandString = Arrays.asList(cmdArray).toString(); try { Process process = runtime.exec(cmdArray); ProcessConsumerRunnable consumer = new ProcessConsumerRunnable(process); Thread t = new Thread(consumer, "Consuming command: " + commandString); t.setDaemon(true); t.start(); } catch (IOException e) { if (logger.isWarnEnabled()) logger.warn("Exception while trying to execute command {}!", commandString, e); } }
From source file:neembuu.uploader.NeembuuUploader.java
void checkBoxOperations() { NULogger.getLogger().info("Mapping Checkboxes"); synchronized (map) { map.clear();//from w w w . ja v a2 s. co m } synchronized (allmap) { allmap.clear(); } for (SmallModuleEntry sme : uaepm.getIndex().get(Uploader.class)) { synchronized (allmap) { allmap.put(new JCheckBox(sme.getName()), sme); } try { if (UploaderPlugin.locallyPresent(uaepm.getUpdateLocation(), sme) == UploaderPlugin.LocallyPresent.PRESENT) { UploaderPlugin up = uaepm.load(sme); // this sets activated = true } } catch (IOException ex) { Logger.getLogger(NeembuuUploader.class.getName()).log(Level.SEVERE, null, ex); } } Iterator<JCheckBox> it = UnsyncCopy.unsyncCopyKeys(allmap).iterator(); final ActionListener all = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Thread t = new Thread("allmap_checkBoxAction from ActionListener") { @Override public void run() { allmap_checkBoxAction(); } }; t.setDaemon(true); t.start(); } }; while (it.hasNext()) { it.next().addActionListener(all); } checkBoxOperation_ActivatePlugins(); int size; synchronized (allmap) { size = allmap.size(); } NULogger.getLogger().log(Level.INFO, "{0}: Number of supported sites: {1}", new Object[] { getClass().getName(), size }); }
From source file:com.cloudera.beeswax.BeeswaxServiceImpl.java
/** * Create a new BeeswaxServiceImpl.//w w w .j av a 2 s . c o m * * @param dtHost The Hue host (ip or hostname). * @param dtPort The port Desktop runs on. * @param dtHttps Whether Desktop is running https. * @param queryLifetime The life time of a cached query. */ public BeeswaxServiceImpl(String dtHost, int dtPort, boolean dtHttps, long queryLifetime) { LogContext.initLogCapture(); this.executor = Executors.newCachedThreadPool(new NamingThreadFactory("Beeswax-%d")); this.runningQueries = new ConcurrentHashMap<String, RunningQueryState>(); this.queryLifetime = queryLifetime; if (dtPort == -1) { this.notifyUrl = null; } else { String protocol; if (dtHttps) { try { // Disable SSL verification. HUE cert may be signed by untrusted CA. SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(null, new DummyX509TrustManager[] { new DummyX509TrustManager() }, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory()); } catch (NoSuchAlgorithmException ex) { LOG.warn("Failed to disable SSL certificate check " + ex); } catch (KeyManagementException ex) { LOG.warn("Failed to disable SSL certificate check " + ex); } DummyHostnameVerifier dummy = new DummyHostnameVerifier(); HttpsURLConnection.setDefaultHostnameVerifier(dummy); protocol = "https"; } else { protocol = "http"; } this.notifyUrl = protocol + "://" + dtHost + ":" + dtPort + NOTIFY_URL_BASE; } // A daemon thread that periodically evict stale RunningQueryState objects Thread evicter = new Thread(new Runnable() { @Override public void run() { while (true) { long now = System.currentTimeMillis(); for (Map.Entry<String, RunningQueryState> entry : runningQueries.entrySet()) { RunningQueryState rqState = entry.getValue(); //safe guard against small value of lifetime, only clean FINISHED or EXCEPTION state if ((rqState.state == QueryState.FINISHED || rqState.state == QueryState.EXCEPTION) && rqState.getAtime() + getQueryLifetime() < now) { String id = entry.getKey(); runningQueries.remove(id); LOG.debug("Removed " + rqState.toString()); Thread.yield(); // be nice } } LogContext.garbageCollect(getQueryLifetime()); long wakeup = now + EVICTION_INTERVAL; while (System.currentTimeMillis() < wakeup) { try { Thread.sleep(EVICTION_INTERVAL); } catch (InterruptedException e) { } } } } }, "Evicter"); evicter.setDaemon(true); evicter.start(); }
From source file:gov.sandia.umf.platform.ui.jobs.RunPanel.java
public RunPanel() { root = new NodeBase(); model = new DefaultTreeModel(root); tree = new JTree(model); tree.setRootVisible(false);/*from ww w. ja v a2s. c o m*/ tree.setShowsRootHandles(true); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); tree.setCellRenderer(new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); NodeBase node = (NodeBase) value; Icon icon = node.getIcon(expanded); // A node knows whether it should hold other nodes or not, so don't pass leaf to it. if (icon == null) { if (leaf) icon = getDefaultLeafIcon(); else if (expanded) icon = getDefaultOpenIcon(); else icon = getDefaultClosedIcon(); } setIcon(icon); return this; } }); tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { NodeBase newNode = (NodeBase) tree.getLastSelectedPathComponent(); if (newNode == null) return; if (newNode == displayNode) return; if (displayThread != null) synchronized (displayText) { displayThread.stop = true; } displayNode = newNode; if (displayNode instanceof NodeFile) viewFile(); else if (displayNode instanceof NodeJob) viewJob(); } }); tree.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { int keycode = e.getKeyCode(); if (keycode == KeyEvent.VK_DELETE || keycode == KeyEvent.VK_BACK_SPACE) { delete(); } } }); tree.addTreeWillExpandListener(new TreeWillExpandListener() { public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException { TreePath path = event.getPath(); // TODO: can this ever be null? Object o = path.getLastPathComponent(); if (o instanceof NodeJob) ((NodeJob) o).build(tree); } public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException { } }); tree.addTreeExpansionListener(new TreeExpansionListener() { public void treeExpanded(TreeExpansionEvent event) { Rectangle node = tree.getPathBounds(event.getPath()); Rectangle visible = treePane.getViewport().getViewRect(); visible.height -= node.y - visible.y; visible.y = node.y; tree.repaint(visible); } public void treeCollapsed(TreeExpansionEvent event) { Rectangle node = tree.getPathBounds(event.getPath()); Rectangle visible = treePane.getViewport().getViewRect(); visible.height -= node.y - visible.y; visible.y = node.y; tree.repaint(visible); } }); Thread refreshThread = new Thread() { public void run() { try { // Initial load synchronized (running) { for (MNode n : AppData.runs) running.add(0, new NodeJob(n)); // This should be efficient on a doubly-linked list. for (NodeJob job : running) root.add(job); } EventQueue.invokeLater(new Runnable() { public void run() { model.nodeStructureChanged(root); if (model.getChildCount(root) > 0) tree.setSelectionRow(0); } }); // Periodic refresh to show status of running jobs int shortCycles = 100; // Force full scan on first cycle. while (true) { NodeBase d = displayNode; // Make local copy (atomic action) to prevent it changing from under us if (d instanceof NodeJob) ((NodeJob) d).monitorProgress(RunPanel.this); if (shortCycles++ < 20) { Thread.sleep(1000); continue; } shortCycles = 0; synchronized (running) { Iterator<NodeJob> i = running.iterator(); while (i.hasNext()) { NodeJob job = i.next(); if (job != d) job.monitorProgress(RunPanel.this); if (job.complete >= 1) i.remove(); } } } } catch (InterruptedException e) { } } }; refreshThread.setDaemon(true); refreshThread.start(); displayText = new JTextArea(); displayText.setEditable(false); final JCheckBox chkFixedWidth = new JCheckBox("Fixed-Width Font"); chkFixedWidth.setFocusable(false); chkFixedWidth.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int size = displayText.getFont().getSize(); if (chkFixedWidth.isSelected()) { displayText.setFont(new Font(Font.MONOSPACED, Font.PLAIN, size)); } else { displayText.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, size)); } } }); displayPane.setViewportView(displayText); ActionListener graphListener = new ActionListener() { public void actionPerformed(ActionEvent e) { if (displayNode instanceof NodeFile) { NodeFile nf = (NodeFile) displayNode; if (nf.type == NodeFile.Type.Output || nf.type == NodeFile.Type.Result) { String graphType = e.getActionCommand(); if (displayPane.getViewport().getView() instanceof ChartPanel && displayGraph.equals(graphType)) { viewFile(); displayGraph = ""; } else { if (graphType.equals("Graph")) { Plot plot = new Plot(nf.path.getAbsolutePath()); if (!plot.columns.isEmpty()) displayPane.setViewportView(plot.createGraphPanel()); } else // Raster { Raster raster = new Raster(nf.path.getAbsolutePath(), displayPane.getHeight()); displayPane.setViewportView(raster.createGraphPanel()); } displayGraph = graphType; } } } } }; buttonGraph = new JButton("Graph", ImageUtil.getImage("analysis.gif")); buttonGraph.setFocusable(false); buttonGraph.addActionListener(graphListener); buttonGraph.setActionCommand("Graph"); buttonRaster = new JButton("Raster", ImageUtil.getImage("prnplot.gif")); buttonRaster.setFocusable(false); buttonRaster.addActionListener(graphListener); buttonRaster.setActionCommand("Raster"); Lay.BLtg(this, "C", Lay.SPL(Lay.BL("C", treePane = Lay.sp(tree)), Lay.BL("N", Lay.FL(chkFixedWidth, Lay.FL(buttonGraph, buttonRaster), "hgap=50"), "C", displayPane), "divpixel=250")); setFocusCycleRoot(true); }