List of usage examples for java.lang Thread isAlive
public final native boolean isAlive();
From source file:Main.java
public static String runScript(String script) { String sRet = ""; try {// ww w .j a v a2s .com final Process m_process = Runtime.getRuntime().exec(script); final StringBuilder sbread = new StringBuilder(); Thread tout = new Thread(new Runnable() { public void run() { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(m_process.getInputStream()), 8192); String ls_1 = null; try { while ((ls_1 = bufferedReader.readLine()) != null) { sbread.append(ls_1).append("\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } }); tout.start(); final StringBuilder sberr = new StringBuilder(); Thread terr = new Thread(new Runnable() { public void run() { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(m_process.getErrorStream()), 8192); String ls_1 = null; try { while ((ls_1 = bufferedReader.readLine()) != null) { sberr.append(ls_1).append("\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } }); terr.start(); // int retvalue = m_process.waitFor(); while (tout.isAlive()) { Thread.sleep(50); } if (terr.isAlive()) terr.interrupt(); String stdout = sbread.toString(); String stderr = sberr.toString(); sRet = stdout + stderr; } catch (Exception e) { e.printStackTrace(); return null; } return sRet; }
From source file:Main.java
public static String runScript(String script) { String sRet = ""; try {/*from www. j a va2 s. c om*/ final Process m_process = Runtime.getRuntime().exec(script); final StringBuilder sbread = new StringBuilder(); Thread tout = new Thread(new Runnable() { public void run() { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(m_process.getInputStream()), 8192); String ls_1 = null; try { while ((ls_1 = bufferedReader.readLine()) != null) { sbread.append(ls_1).append("\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } }); tout.start(); final StringBuilder sberr = new StringBuilder(); Thread terr = new Thread(new Runnable() { public void run() { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(m_process.getErrorStream()), 8192); String ls_1 = null; try { while ((ls_1 = bufferedReader.readLine()) != null) { sberr.append(ls_1).append("\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } }); terr.start(); int retvalue = m_process.waitFor(); while (tout.isAlive()) { Thread.sleep(50); } if (terr.isAlive()) terr.interrupt(); String stdout = sbread.toString(); String stderr = sberr.toString(); sRet = stdout + stderr; } catch (Exception e) { e.printStackTrace(); return null; } return sRet; }
From source file:i2p.bote.I2PBote.java
private void printRunningThreads() { List<Thread> runningThreads = new ArrayList<Thread>(); for (Thread thread : backgroundThreads) if (thread.isAlive()) runningThreads.add(thread);/*from w ww . ja va 2 s .c o m*/ log.debug(runningThreads.size() + " threads still running 5 seconds after interrupt()" + (runningThreads.isEmpty() ? '.' : ':')); for (Thread thread : runningThreads) log.debug(" " + thread.getName()); if (imapService != null && imapService.isStarted()) log.debug("IMAP service still running"); if (smtpService != null && smtpService.isRunning()) log.debug("SMTP service still running"); }
From source file:org.lsc.AbstractSynchronize.java
public final boolean isAsynchronousTaskRunning(final String syncName) { Thread asyncThread = asynchronousThreads.get(syncName); if (asyncThread != null) { if (asyncThread.isAlive()) { return true; } else {/*from w ww . j av a2s. c o m*/ asynchronousThreads.remove(syncName); mapSTasks.remove(syncName); return false; } } else { return false; } }
From source file:org.codelibs.fess.servlet.Tomcat6ConfigServlet.java
@SuppressWarnings("deprecation") private void cleanupAllThreads() { final Thread[] threads = getThreads(); final ClassLoader cl = this.getClass().getClassLoader(); try {/*from w w w .j a v a2 s .c o m*/ cl.getResource(null); } catch (final Exception e) { } final List<String> jvmThreadGroupList = new ArrayList<String>(); jvmThreadGroupList.add("system"); jvmThreadGroupList.add("RMI Runtime"); // Iterate over the set of threads for (final Thread thread : threads) { if (thread != null) { final ClassLoader ccl = thread.getContextClassLoader(); if (ccl != null && ccl.equals(cl)) { // Don't warn about this thread if (thread == Thread.currentThread()) { continue; } // Don't warn about JVM controlled threads final ThreadGroup tg = thread.getThreadGroup(); if (tg != null && jvmThreadGroupList.contains(tg.getName())) { continue; } waitThread(thread); // Skip threads that have already died if (!thread.isAlive()) { continue; } if (logger.isInfoEnabled()) { logger.info("Interrupting a thread [" + thread.getName() + "]..."); } thread.interrupt(); waitThread(thread); // Skip threads that have already died if (!thread.isAlive()) { continue; } if (logger.isInfoEnabled()) { logger.info("Stopping a thread [" + thread.getName() + "]..."); } thread.stop(); } } } Field threadLocalsField = null; Field inheritableThreadLocalsField = null; Field tableField = null; try { threadLocalsField = Thread.class.getDeclaredField("threadLocals"); threadLocalsField.setAccessible(true); inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals"); inheritableThreadLocalsField.setAccessible(true); // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects // accessible final Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap"); tableField = tlmClass.getDeclaredField("table"); tableField.setAccessible(true); } catch (final Exception e) { // ignore } for (final Thread thread : threads) { if (thread != null) { Object threadLocalMap; try { // Clear the first map threadLocalMap = threadLocalsField.get(thread); clearThreadLocalMap(cl, threadLocalMap, tableField); } catch (final Exception e) { // ignore } try { // Clear the second map threadLocalMap = inheritableThreadLocalsField.get(thread); clearThreadLocalMap(cl, threadLocalMap, tableField); } catch (final Exception e) { // ignore } } } }
From source file:org.apache.hadoop.yarn.server.nodemanager.TestLinuxContainerExecutor.java
@Test public void testContainerKill() throws Exception { Assume.assumeTrue(shouldRun());/*w w w .ja v a 2 s.com*/ final ContainerId sleepId = getNextContainerId(); Thread t = new Thread() { public void run() { try { runAndBlock(sleepId, "sleep", "100"); } catch (IOException e) { LOG.warn("Caught exception while running sleep", e); } }; }; t.setDaemon(true); // If it does not exit we shouldn't block the test. t.start(); assertTrue(t.isAlive()); String pid = null; int count = 10; while ((pid = exec.getProcessId(sleepId)) == null && count > 0) { LOG.info("Sleeping for 200 ms before checking for pid "); Thread.sleep(200); count--; } assertNotNull(pid); LOG.info("Going to killing the process."); exec.signalContainer(new ContainerSignalContext.Builder().setUser(appSubmitter).setPid(pid) .setSignal(Signal.TERM).build()); LOG.info("sleeping for 100ms to let the sleep be killed"); Thread.sleep(100); assertFalse(t.isAlive()); cleanupAppFiles(appSubmitter); }
From source file:com.headswilllol.basiclauncher.Launcher.java
public void actionPerformed(ActionEvent e) { // button was pressed if (e.getActionCommand().equals("play")) { // play button was pressed // clear dem buttons this.remove(play); this.remove(force); this.remove(noUpdate); this.remove(quit); File dir = new File(appData(), FOLDER_NAME + File.separator + "resources"); if (!downloadDir.isEmpty()) // -d flag was used dir = new File(downloadDir, FOLDER_NAME + File.separator + "resources"); dir.mkdir();// w w w.j a v a 2s. c o m try { progress = "Downloading JSON file list..."; paintImmediately(0, 0, width, height); Downloader jsonDl = new Downloader(new URL(JSON_LOCATION), dir.getPath() + File.separator + "resources.json", "JSON file list", true); Thread jsonT = new Thread(jsonDl); // download in a separate thread so the GUI will continue to update jsonT.start(); while (jsonT.isAlive()) { } // no need for a progress bar; it's tiny JSONArray files = (JSONArray) ((JSONObject) new JSONParser().parse(new InputStreamReader( new File(dir.getPath(), "resources.json").toURI().toURL().openStream()))).get("resources"); List<String> paths = new ArrayList<String>(); for (Object obj : files) { // iterate the entries in the JSON file JSONObject jFile = (JSONObject) obj; String launch = ((String) jFile.get("launch")); // if true, resource will be used as main binary if (launch != null && launch.equals("true")) main = new File(dir, ((String) jFile.get("localPath")).replace("/", File.separator)); paths.add(((String) jFile.get("localPath")).replace("/", File.separator)); File file = new File(dir, ((String) jFile.get("localPath")).replace("/", File.separator)); boolean reacquire = false; if (!file.exists() || // files doesn't exist (allowReacquire && // allow files to be reacquired (update || // update forced // mismatch between local and remote file !jFile.get("md5").equals(md5(file.getPath()))))) { reacquire = true; if (update) System.out.println( "Update forced, so file " + jFile.get("localPath") + " must be updated"); else if (!file.exists()) System.out.println("Cannot find local copy of file " + jFile.get("localPath")); else System.out.println("MD5 checksum for file " + jFile.get("localPath") + " does not match expected value"); System.out.println("Attempting to reacquire..."); file.delete(); file.getParentFile().mkdirs(); file.createNewFile(); progress = "Downloading " + jFile.get("id"); // update the GUI paintImmediately(0, 0, width, height); Downloader dl = new Downloader(new URL((String) jFile.get("location")), dir + File.separator + ((String) jFile.get("localPath")).replace("/", File.separator), (String) jFile.get("id"), !jFile.containsKey("doNotSpoofUserAgent") || !Boolean.parseBoolean((String) jFile.get("doNotSpoofUserAgent"))); Thread th = new Thread(dl); th.start(); eSize = getFileSize(new URL((String) jFile.get("location"))) / 8; // expected file size speed = 0; // stores the current download speed lastSize = 0; // stores the size of the downloaded file the last time the GUI was updated while (th.isAlive()) { // wait but don't hang the main thread aSize = file.length() / 8; if (lastTime != -1) { // wait so the GUI isn't constantly updating if (System.currentTimeMillis() - lastTime >= SPEED_UPDATE_INTERVAL) { speed = (aSize - lastSize) / ((System.currentTimeMillis() - lastTime) / 1000) * 8; // calculate new speed lastTime = System.currentTimeMillis(); lastSize = aSize; // update the downloaded file's size } } else { speed = 0; // reset the download speed lastTime = System.currentTimeMillis(); // and the last time } paintImmediately(0, 0, width, height); } eSize = -1; aSize = -1; } if (jFile.containsKey("extract")) { // file should be unzipped HashMap<String, JSONObject> elements = new HashMap<String, JSONObject>(); for (Object ex : (JSONArray) jFile.get("extract")) { elements.put((String) ((JSONObject) ex).get("path"), (JSONObject) ex); paths.add(((String) ((JSONObject) ex).get("localPath")).replace("/", File.separator)); File f = new File(dir, ((String) ((JSONObject) ex).get("localPath")).replace("/", File.separator)); if (!f.exists() || // file doesn't exist // file isn't directory and has checksum (!f.isDirectory() && ((JSONObject) ex).get("md5") != null && // mismatch between local and remote file !md5(f.getPath()).equals((((JSONObject) ex).get("md5"))))) reacquire = true; if (((JSONObject) ex).get("id").equals("natives")) // specific to LWJGL launching natives = new File(dir, ((String) ((JSONObject) ex).get("localPath")).replace("/", File.separator)); } if (reacquire) { try { ZipFile zip = new ZipFile(new File(dir, ((String) jFile.get("localPath")).replace("/", File.separator))); @SuppressWarnings("rawtypes") Enumeration en = zip.entries(); List<String> dirs = new ArrayList<String>(); while (en.hasMoreElements()) { // iterate entries in ZIP file ZipEntry entry = (ZipEntry) en.nextElement(); boolean extract = false; // whether the entry should be extracted String parentDir = ""; if (elements.containsKey(entry.getName())) // entry is in list of files to extract extract = true; else for (String d : dirs) if (entry.getName().contains(d)) { extract = true; parentDir = d; } if (extract) { progress = "Extracting " + (elements.containsKey(entry.getName()) ? elements.get(entry.getName()).get("id") : entry.getName() .substring(entry.getName().indexOf(parentDir), entry.getName().length()) .replace("/", File.separator)); // update the GUI paintImmediately(0, 0, width, height); if (entry.isDirectory()) { if (parentDir.equals("")) dirs.add((String) elements.get(entry.getName()).get("localPath")); } else { File path = new File(dir, (parentDir.equals("")) ? ((String) elements.get(entry.getName()).get("localPath")) .replace("/", File.separator) : entry.getName() .substring(entry.getName().indexOf(parentDir), entry.getName().length()) .replace("/", File.separator)); // path to extract to if (path.exists()) path.delete(); unzip(zip, entry, path); // *zziiiip* } } } } catch (Exception ex) { ex.printStackTrace(); createExceptionLog(ex); progress = "Failed to extract files from " + jFile.get("id"); fail = "Errors occurred; see log file for details"; launcher.paintImmediately(0, 0, width, height); } } } } checkFile(dir, dir, paths); } catch (Exception ex) { // can't open resource list ex.printStackTrace(); createExceptionLog(ex); progress = "Failed to read JSON file list"; fail = "Errors occurred; see log file for details"; launcher.paintImmediately(0, 0, width, height); } launch(); } else if (e.getActionCommand().equals("force")) { force.setActionCommand("noForce"); force.setText("Will Force!"); update = true; // reset do not reacquire button noUpdate.setActionCommand("noReacquire"); noUpdate.setText("Do Not Reacquire"); allowReacquire = true; } else if (e.getActionCommand().equals("noForce")) { force.setActionCommand("force"); force.setText("Force Update"); update = false; } else if (e.getActionCommand().equals("noReacquire")) { noUpdate.setActionCommand("yesReacquire"); noUpdate.setText("Will Not Reacquire!"); allowReacquire = false; // reset force update button force.setActionCommand("force"); force.setText("Force Update"); update = false; } else if (e.getActionCommand().equals("yesReacquire")) { noUpdate.setActionCommand("noReacquire"); noUpdate.setText("Do Not Reacquire"); allowReacquire = true; } else if (e.getActionCommand().equals("quit")) { pullThePlug(); } else if (e.getActionCommand().equals("kill")) gameProcess.destroyForcibly(); }
From source file:org.broadinstitute.gatk.engine.phonehome.GATKRunReport.java
/** * Post this GATK report to the AWS s3 GATK_Run_Report log * * @return the s3Object pointing to our pushed report, or null if we failed to push */// w ww . j a v a 2 s . c om protected S3Object postReportToAWSS3() { // modifying example code from http://jets3t.s3.amazonaws.com/toolkit/code-samples.html this.hostName = Utils.resolveHostname(); // we want to fill in the host name final String key = getReportFileName(); logger.debug("Generating GATK report to AWS S3 with key " + key); try { // create an byte output stream so we can capture the output as a byte[] final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(8096); final OutputStream outputStream = new GZIPOutputStream(byteStream); postReportToStream(outputStream); outputStream.close(); final byte[] report = byteStream.toByteArray(); // stop us from printing the annoying, and meaningless, mime types warning final Logger mimeTypeLogger = Logger.getLogger(org.jets3t.service.utils.Mimetypes.class); mimeTypeLogger.setLevel(Level.FATAL); // Set the S3 upload on its own thread with timeout: final S3PutRunnable s3run = new S3PutRunnable(key, report); final Thread s3thread = new Thread(s3run); s3thread.setDaemon(true); s3thread.setName("S3Put-Thread"); s3thread.start(); s3thread.join(s3PutTimeOutInMilliseconds); if (s3thread.isAlive()) { s3thread.interrupt(); exceptDuringRunReport("Run statistics report upload to AWS S3 timed-out"); } else if (s3run.isSuccess.get()) { logger.info("Uploaded run statistics report to AWS S3"); logger.debug("Uploaded to AWS: " + s3run.s3Object); return s3run.s3Object; } else { // an exception occurred, the thread should have already invoked the exceptDuringRunReport function } } catch (IOException e) { exceptDuringRunReport("Couldn't read report file", e); } catch (InterruptedException e) { exceptDuringRunReport("Run statistics report upload interrupted", e); } return null; }
From source file:de.bwravencl.controllerbuddy.gui.Main.java
private static void waitForThreadToFinish(final Thread thread) { while (thread != null && thread.isAlive()) try {// w w w. j ava 2 s .co m Thread.sleep(100L); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } }
From source file:com.baidu.jprotobuf.mojo.PreCompileMojo.java
private void joinThread(Thread thread, long timeoutMsecs) { try {//from w ww .j av a 2 s .co m getLog().debug("joining on thread " + thread); thread.join(timeoutMsecs); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // good practice if don't throw getLog().warn("interrupted while joining against thread " + thread, e); // not expected! } if (thread.isAlive()) // generally abnormal { getLog().warn("thread " + thread + " was interrupted but is still alive after waiting at least " + timeoutMsecs + "msecs"); } }