List of usage examples for java.lang Thread isAlive
public final native boolean isAlive();
From source file:org.apache.jackrabbit.core.integration.InterruptedQueryTest.java
@Test public void testQuery() throws Exception { if (Constants.WINDOWS) { return;// w w w. j av a 2 s .c om } for (int i = 0; i < 100; i++) { session.getRootNode().addNode("node" + i, "nt:unstructured"); } session.save(); final QueryManager qm = session.getWorkspace().getQueryManager(); final AtomicBoolean stop = new AtomicBoolean(false); final List<Exception> exceptions = Collections.synchronizedList(new ArrayList<Exception>()); Thread t = new Thread(new Runnable() { @Override public void run() { while (!stop.get() && exceptions.isEmpty()) { try { // execute query String stmt = "//*[@jcr:primaryType='nt:unstructured']"; qm.createQuery(stmt, Query.XPATH).execute(); } catch (RepositoryException e) { if (Constants.SUN_OS) { // on Solaris it's OK when the root cause // of the exception is an InterruptedIOException // the underlying file is not closed Throwable t = e; while (t.getCause() != null) { t = t.getCause(); } if (!(t instanceof InterruptedIOException)) { exceptions.add(e); } } else { exceptions.add(e); } } } } }); t.start(); for (int i = 0; i < 200 && t.isAlive(); i++) { t.interrupt(); Thread.sleep((long) (100.0 * Math.random())); } stop.set(true); t.join(); if (!exceptions.isEmpty()) { throw exceptions.get(0); } }
From source file:org.apache.hadoop.hdfs.server.namenode.FSImage.java
private void waitForThreads(List<Thread> threads) { for (Thread thread : threads) { while (thread.isAlive()) { try { thread.join();// ww w . j a v a 2 s. c o m } catch (InterruptedException iex) { LOG.error("Caught interrupted exception while waiting for thread " + thread.getName() + " to finish. Retrying join"); } } } }
From source file:uk.ac.gla.terrier.probos.controller.ControllerServer.java
private void closeThread(Thread t) { if (t != null && t.isAlive()) { LOG.info("Stopping " + t.getName()); t.interrupt();// w ww.java2s.com try { t.join(); } catch (InterruptedException ex) { ex.printStackTrace(); } } }
From source file:bixo.fetcher.SimpleHttpFetcherTest.java
@Test public final void testInterruptedFetch() throws Exception { // Need to read in lots of data that we get very slowly Server server = startServer(new RandomResponseHandler(20000, 2 * 1000L), 8089); // Set no response rate, so that doesn't trigger an exception FetcherPolicy policy = new FetcherPolicy(); policy.setMinResponseRate(FetcherPolicy.NO_MIN_RESPONSE_RATE); final BaseFetcher fetcher = new SimpleHttpFetcher(1, policy, ConfigUtils.BIXO_TEST_AGENT); final String[] failMsg = new String[1]; Thread t = new Thread(new Runnable() { @Override/*from w w w.ja va2s. c om*/ public void run() { String url = "http://localhost:8089/test.html"; try { fetcher.get(new ScoredUrlDatum(url)); failMsg[0] = "No exception thrown, should have thrown an aborted by interrupt exception"; } catch (AbortedFetchException e) { if (e.getAbortReason() != AbortedFetchReason.INTERRUPTED) { failMsg[0] = "Wrong abort exception thrown, should have thrown an aborted by interrupt exception"; } } catch (BaseFetchException e) { failMsg[0] = "Wrong exception thrown, should have thrown an aborted by interrupt exception"; } } }); t.start(); t.interrupt(); while (t.isAlive()) { Thread.sleep(100); } server.stop(); if (failMsg[0] != null) { fail(failMsg[0]); } }
From source file:voldemort.tools.DeleteKeysCLI.java
public void deleteKeys() throws Exception { Map<String, Thread> workers = new HashMap<String, Thread>(); Map<String, DeleteKeysTask> tasks = new HashMap<String, DeleteKeysTask>(); BufferedWriter statusWriter = new BufferedWriter(new FileWriter("status.txt", true)); for (String store : this.stores) { DeleteKeysTask task = new DeleteKeysTask(store, storeClients.get(store), this.adminClient, serializerDefs.get(store), this.keyFile, this.qps, this.nodeid, this.deleteAllVersions, this.checkKeysCount); Thread worker = new Thread(task); workers.put(store, worker);/*from w w w . j av a 2s .co m*/ tasks.put(store, task); statusWriter.write("Created thread " + worker.getId() + " for store " + store + "\n"); System.out.println("Created thread " + worker.getId() + " for store " + store); worker.start(); } statusWriter.flush(); boolean isAllCompleted = false; while (isAllCompleted == false) { isAllCompleted = true; for (String store : stores) { Thread worker = workers.get(store); DeleteKeysTask task = tasks.get(store); System.out.print(task.getStatus()); statusWriter.write(task.getStatus()); if (task.isComplete()) { continue; } if (worker.isAlive() == false) { System.out.println("Thread processing it has died " + store); statusWriter.write("Thread processing it has died " + store + "\n"); continue; } isAllCompleted = false; } statusWriter.flush(); if (isAllCompleted == false) { Thread.sleep(1000 * 15); } } statusWriter.close(); }
From source file:eu.stratosphere.nephele.taskmanager.runtime.RuntimeTask.java
/** * Cancels or kills the task.// ww w . j a va 2s . c o m * * @param cancel * <code>true/code> if the task shall be canceled, <code>false</code> if it shall be killed */ private void cancelOrKillExecution(final boolean cancel) { final Thread executingThread = this.environment.getExecutingThread(); if (executingThread == null) { return; } if (this.executionState != ExecutionState.RUNNING && this.executionState != ExecutionState.FINISHING) { return; } LOG.info((cancel ? "Canceling " : "Killing ") + this.environment.getTaskNameWithIndex()); if (cancel) { this.isCanceled = true; // Change state executionStateChanged(ExecutionState.CANCELING, null); // Request user code to shut down try { final AbstractInvokable invokable = this.environment.getInvokable(); if (invokable != null) { invokable.cancel(); } } catch (Throwable e) { LOG.error(StringUtils.stringifyException(e)); } } // Continuously interrupt the user thread until it changed to state CANCELED while (true) { executingThread.interrupt(); if (!executingThread.isAlive()) { break; } try { executingThread.join(1000); } catch (InterruptedException e) { } if (!executingThread.isAlive()) { break; } if (LOG.isDebugEnabled()) { LOG.debug("Sending repeated " + (cancel == true ? "canceling" : "killing") + " signal to " + this.environment.getTaskName() + " with state " + this.executionState); } } }
From source file:eu.stratosphere.nephele.taskmanager.Task.java
/** * Cancels or kills the task.// w ww . j av a 2s .c om * * @param cancel <code>true/code> if the task shall be canceled, <code>false</code> if it shall be killed */ private void cancelOrKillExecution(boolean cancel) { final Thread executingThread = this.environment.getExecutingThread(); if (executingThread == null) { return; } if (this.executionState != ExecutionState.RUNNING && this.executionState != ExecutionState.FINISHING) { return; } LOG.info((cancel ? "Canceling " : "Killing ") + this.environment.getTaskNameWithIndex()); if (cancel) { this.isCanceled = true; // Change state executionStateChanged(ExecutionState.CANCELING, null); // Request user code to shut down try { final AbstractInvokable invokable = this.environment.getInvokable(); if (invokable != null) { invokable.cancel(); } } catch (Throwable e) { LOG.error(StringUtils.stringifyException(e)); } } // Continuously interrupt the user thread until it changed to state CANCELED while (true) { executingThread.interrupt(); if (!executingThread.isAlive()) { break; } try { executingThread.join(1000); } catch (InterruptedException e) { } if (!executingThread.isAlive()) { break; } if (LOG.isDebugEnabled()) { LOG.debug("Sending repeated " + (cancel == true ? "canceling" : "killing") + " signal to " + this.environment.getTaskName() + " with state " + this.executionState); } } }
From source file:org.wandora.application.gui.topicpanels.webview.WebViewPanel.java
public Object executeSynchronizedScript(final String script) { scriptReturn = null;/*w ww. j a v a2 s . c o m*/ if (script != null && script.length() > 0) { Thread runner = new Thread() { @Override public void run() { scriptReturn = webEngine.executeScript(script); } }; Platform.runLater(runner); do { try { Thread.sleep(100); } catch (Exception ex) { } } while (runner.isAlive()); } return scriptReturn; }
From source file:edu.rit.flick.genetics.FastFileDeflator.java
@Override public File deflate(final Configuration configuration, final File fileIn, final File fileOut) { assert fileIn.exists(); try {/*from w ww . j a v a 2s. c o m*/ // Deflate to Directory final String outputDirectoryPath = fileOut.getPath() .replaceAll("." + Files.getFileExtension(fileOut.getPath()), FLICK_FAST_FILE_TMP_DIR_SUFFIX); final File tmpOutputDirectory = new File(outputDirectoryPath); if (tmpOutputDirectory.exists()) FileUtils.deleteDirectory(tmpOutputDirectory); tmpOutputDirectory.mkdirs(); final AtomicReference<Thread> cleanHookAtomic = new AtomicReference<Thread>(); // Deflate Fast file to a temporary directory final Thread deflateToDirectoryThread = new Thread(() -> { try { // Deflate Fast file to a temporary directory deflateToDirectory(fileIn, tmpOutputDirectory); // Remove unused buffer space removeUnusedBufferSpace(outputDirectoryPath); // Compress Directory to a zip file deflateToFile(tmpOutputDirectory, fileOut); Runtime.getRuntime().removeShutdownHook(cleanHookAtomic.get()); } catch (final Exception e) { if (!interrupted) System.err.println(e.getMessage()); } }, "Default_Deflation_Thread"); // Make cleaning hook final Thread cleanHook = new Thread(() -> { interrupted = true; configuration.setFlag(VERBOSE_FLAG, false); configuration.setFlag(DELETE_FLAG, false); try { if (deflateToDirectoryThread.isAlive()) deflateToDirectoryThread.interrupt(); // Remove unused buffer space removeUnusedBufferSpace(outputDirectoryPath); // Delete files that were not able to be processed FileUtils.deleteQuietly(tmpOutputDirectory); System.out.println(); } catch (final IOException | InterruptedException e) { e.printStackTrace(); } }, "Deflation_Cleaning_Thread"); cleanHookAtomic.set(cleanHook); Runtime.getRuntime().addShutdownHook(cleanHook); deflateToDirectoryThread.start(); deflateToDirectoryThread.join(); } catch (final IOException | InterruptedException e) { e.printStackTrace(); } return fileOut; }
From source file:org.hyperic.hq.agent.server.session.AgentSynchronizer.java
private void executeJob(final StatefulAgentDataTransferJob job) throws InterruptedException { final String name = Thread.currentThread().getName() + "-" + executorNum.getAndIncrement(); final Thread thread = new Thread(name) { @Override//from ww w . j a v a 2 s . c om public void run() { job.setLastRuntime(); if (agentIsPingable(job)) { try { job.execute(); } catch (Throwable e) { if (e instanceof InterruptedException) { log.warn("jobdesc=" + job.getJobDescription() + " was interrupted: " + e); log.debug(e, e); } else { log.error(e, e); } } return; } else { log.warn("Could not ping agent in order to run job " + getJobInfo(job)); } } }; thread.start(); thread.join(WAIT_TIME); // if the thread is alive just try to interrupt it and keep going final boolean threadIsAlive = thread.isAlive(); final boolean jobWasSuccessful = job.wasSuccessful(); final AvailabilityManager availabilityManager = ctx.getBean(AvailabilityManager.class); final boolean platformIsAvailable = availabilityManager.platformIsAvailableOrUnknown(job.getAgentId()) || isInRestartState(job.getAgentId()); if (jobWasSuccessful) { // do nothing, this is good! return; } else if (platformIsAvailable) { if (threadIsAlive) { thread.interrupt(); } job.incrementFailures(); if (log.isDebugEnabled()) { log.debug("executeJob, number of failures for execute job=" + getJobInfo(job) + " RuntimeId: " + job.getRuntimeTime() + " " + job.getNumberOfFailures()); } if (job.discardJob()) { job.onFailure( "Too many failures on agent " + job.getAgentId() + " RuntimeId: " + job.getRuntimeTime()); } else { reAddJob(job); if (threadIsAlive) { log.warn("AgentDataTransferJob=" + getJobInfo(job) + " has take more than " + WAIT_TIME / 1000 / 60 + " minutes to run. The agent appears alive so therefore the job was" + " interrupted and requeued. Job threadName={" + thread.getName() + "}"); } else { log.warn("AgentDataTransferJob=" + getJobInfo(job) + " died and was not successful. The agent appears alive and" + " therefore the job was requeued. " + " Job threadName={" + thread.getName() + "}" + " RuntimeId: " + job.getRuntimeTime()); } } } else { if (threadIsAlive) { thread.interrupt(); log.warn("AgentDataTransferJob=" + getJobInfo(job) + " has take more than " + WAIT_TIME / 1000 / 60 + " minutes to run. Discarding job threadName={" + thread.getName() + "}"); } // Can't ping agent and platform availability is down, therefore agent must be down job.onFailure("Platform associated with agent " + job.getAgentId() + " is not available"); } }