List of usage examples for java.lang Thread interrupt
public void interrupt()
From source file:edu.illinois.imunit.examples.apache.collections.TestBlockingBuffer.java
/** * Tests interrupted {@link BlockingBuffer#get()}. */// www . ja va 2s . c o m @Test @Schedules({ @Schedule(name = "InterruptedGet", value = "[beforeGet:afterGet]@readThread->beforeInterrupt@main," + "finishAddException@readThread->afterInterrupt@main") }) public void testInterruptedGet() throws InterruptedException { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj = new Object(); // spawn a read thread to wait on the empty buffer ArrayList exceptionList = new ArrayList(); Thread thread = new ReadThread(blockingBuffer, obj, exceptionList, "InterruptedGet", "readThread"); thread.start(); try { //Thread.sleep(100); //INS-SLEEP } catch (Exception e1) { e1.printStackTrace(); } // Interrupting the thread should cause it to throw BufferUnderflowException fireEvent("beforeInterrupt"); thread.interrupt(); // Chill, so thread can throw and add message to exceptionList // Thread.sleep(100); fireEvent("afterInterrupt"); assertTrue("InterruptedGet", exceptionList.contains("BufferUnderFlow")); // assertFalse("InterruptedGet", thread.isAlive()); // if( thread.isAlive() ) { // fail( "Read thread has hung." ); // } }
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 *//*from w w w .j ava2s.c o m*/ 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:com.microsoft.tfs.client.common.ui.teambuild.teamexplorer.sections.TeamExplorerBuildsMyBuildsSection.java
@Override public Composite getSectionContent(final FormToolkit toolkit, final Composite parent, final int style, final TeamExplorerContext context) { this.toolkit = toolkit; composite = toolkit.createComposite(parent); // Form-style border painting not enabled (0 pixel margins OK) because // no applicable controls in this composite SWTUtil.gridLayout(composite, 1, true, 0, 5); if (!context.isConnected()) { createDisconnectedContent(toolkit, composite); return composite; } else if (buildItems.length == 0) { createEmptyLabel(toolkit, composite); } else {/*from w w w .j a va2 s .c o m*/ createTableViewer(toolkit, composite); } // Create a background worker thread that will perform an automatic // refresh for this section. final Thread refreshThread = new Thread(new MyBuildsRefreshWorker()); refreshThread.setName("My Builds Auto Refresh"); //$NON-NLS-1$ refreshThread.start(); // Add build changes listeners to allow refresh updates in the UI. BuildHelpers.getBuildManager().addBuildManagerListener(buildManagerListener); // Handle disposal of this control. composite.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(final DisposeEvent e) { refreshThreadStop = true; refreshThread.interrupt(); imageHelper.dispose(); BuildHelpers.getBuildManager().removeBuildManagerListener(buildManagerListener); } }); return composite; }
From source file:org.kurento.test.browser.WebPage.java
@SuppressWarnings("deprecation") public long getLatency() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final long[] out = new long[1]; Thread t = new Thread() { @Override// w w w . j a va2 s. c o m public void run() { Object latency = browser.executeScript("return kurentoTest.getLatency();"); if (latency != null) { out[0] = (Long) latency; } else { out[0] = Long.MIN_VALUE; } latch.countDown(); } }; t.start(); if (!latch.await(browser.getTimeout(), TimeUnit.SECONDS)) { t.interrupt(); t.stop(); throw new LatencyException("Timeout getting latency (" + browser.getTimeout() + " seconds)"); } return out[0]; }
From source file:com.legalsoft.generic.gtc.controller.TimerBooleanController.java
/** * Mtodo para ejecutar este controller./*from w w w .j a v a 2 s . com*/ */ @Override public void run() { // Cambiar el nombre del thread. Thread thread = Thread.currentThread(); thread.setName("TIMER"); logger.info("Ejecutando el hilo del Timer @{}", Main.get_TS()); // ejecutar en un bloque controlado. try { while (!thread.isInterrupted()) { // obtener el delay... en un bloque sincronizado. long cicleDelay; synchronized (delay) { cicleDelay = delay[0]; } // ahora, una espera con este delay. Thread.sleep(cicleDelay); // Luego, llamar a los listeners. // el clculo del resultado es sincronizado. boolean result = calculateResult(); fireTimerEvent(result); } } catch (InterruptedException exception) { logger.error("Ejecucin interrumpida: {}", exception); // terminando.... thread.interrupt(); } logger.info("Terminada la ejecucion del Timer @{}", Main.get_TS()); }
From source file:edu.illinois.imunit.examples.apache.collections.TestBlockingBuffer.java
/** * Tests interrupted remove.//from ww w . j av a2 s . c om */ @Test @Schedules({ @Schedule(name = "InterruptedRemove", value = "[beforeRemove: afterRemove]@readThread->beforeInterrupt@main," + "finishAddException@readThread->afterInterrupt@main") }) public void testInterruptedRemove() throws InterruptedException { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj = new Object(); // spawn a read thread to wait on the empty buffer ArrayList exceptionList = new ArrayList(); Thread thread = new ReadThread(blockingBuffer, obj, exceptionList, "remove", "InterruptedRemove", "readThread"); thread.start(); try { //Thread.sleep(100); //INS-SLEEP } catch (Exception e1) { e1.printStackTrace(); } // Interrupting the thread should cause it to throw BufferUnderflowException fireEvent("beforeInterrupt"); thread.interrupt(); // Chill, so thread can throw and add message to exceptionList // Thread.sleep(100); fireEvent("afterInterrupt"); assertTrue("InterruptedRemove", exceptionList.contains("BufferUnderFlow")); //assertFalse("InterruptedRemove",thread.isAlive()); //if( thread.isAlive() ) { //fail( "Read thread has hung." ); //} }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java
@Test public void shouldInterruptWhile() throws Exception { final Map<String, List<Object>> compilerCustomizerConfig = new HashMap<>(); compilerCustomizerConfig.put(ThreadInterruptCustomizerProvider.class.getName(), new ArrayList<>()); final Map<String, Object> config = new HashMap<>(); config.put("compilerCustomizerProviders", compilerCustomizerConfig); final GremlinExecutor gremlinExecutor = GremlinExecutor.build() .addEngineSettings("gremlin-groovy", Collections.emptyList(), Collections.emptyList(), Arrays.asList(PATHS.get("GremlinExecutorInit.groovy")), config) .create();/*from w ww . j a v a 2s . c o m*/ final AtomicBoolean asserted = new AtomicBoolean(false); final Thread t = new Thread(() -> { try { gremlinExecutor .eval("s = System.currentTimeMillis();\nwhile((System.currentTimeMillis() - s) < 10000) {}") .get(); } catch (Exception se) { asserted.set(se instanceof InterruptedException); } }); t.start(); Thread.sleep(100); t.interrupt(); while (t.isAlive()) { } assertTrue(asserted.get()); }
From source file:com.tascape.qa.th.Utils.java
/** * Executes command, and waits for the expected pass/fail phrase in console printout within timeout, * * @param command command line/*w ww . j a va2s.c om*/ * @param pass skip checking if null * @param fail skip checking if null * @param timeout set 0 for not to check the output message, otherwise, waiting for timeout * @param workingDir working directory * * @return console output as a list of strings * * @throws IOException for command error * @throws InterruptedException when interrupted */ public static List<String> cmd(String[] command, final String pass, final String fail, final long timeout, final String workingDir) throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder(command); if (workingDir != null) { pb.directory(new File(workingDir)); } pb.redirectErrorStream(true); LOG.debug("Running command: " + pb.command().toString().replace(",", "")); final Process p = pb.start(); Thread thread; final List<String> output = new ArrayList<>(); if (timeout == 0) { LOG.debug("This is a start-and-exit command"); output.add(PASS); return output; } else { thread = new Thread() { @Override public void run() { try { LOG.debug("Command timeouts in {} ms", timeout); Thread.sleep(timeout); try { p.exitValue(); } catch (IllegalThreadStateException ex) { LOG.debug("killing subprocess {} - {}", p, ex.getMessage()); p.destroy(); } } catch (InterruptedException ex) { LOG.warn(ex.getMessage()); } } }; thread.setName(Thread.currentThread().getName() + "-" + p.hashCode()); thread.setDaemon(true); thread.start(); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String c = p + " - "; for (String line = stdIn.readLine(); line != null;) { LOG.trace("{}{}", c, line); output.add(line); try { line = stdIn.readLine(); } catch (IOException ex) { LOG.warn(ex.getMessage()); break; } } LOG.debug("Command exit code {}", p.waitFor()); thread.interrupt(); try { stdIn.close(); } catch (IOException ex) { LOG.warn("", ex); } for (String s : output) { if (pass != null && (s.contains(pass) || s.matches(pass))) { output.add(PASS); break; } else if (fail != null && s.contains(fail)) { output.add(FAIL); break; } } return output; }
From source file:org.apache.hadoop.hive.ql.TestTxnCommands.java
/** * Writing UTs that need multiple threads is challenging since Derby chokes on concurrent access. * This tests that "AND WAIT" actually blocks and responds to interrupt * @throws Exception//ww w . j a v a2s.co m */ @Test public void testCompactionBlocking() throws Exception { Timer cancelCompact = new Timer("CancelCompactionTimer", false); final Thread threadToInterrupt = Thread.currentThread(); cancelCompact.schedule(new TimerTask() { @Override public void run() { threadToInterrupt.interrupt(); } }, 5000); long start = System.currentTimeMillis(); runStatementOnDriver("alter table " + TestTxnCommands2.Table.ACIDTBL + " compact 'major' AND WAIT"); //no Worker so it stays in initiated state //w/o AND WAIT the above alter table retunrs almost immediately, so the test here to check that //> 2 seconds pass, i.e. that the command in Driver actually blocks before cancel is fired Assert.assertTrue(System.currentTimeMillis() > start + 2); }
From source file:edu.illinois.enforcemop.examples.apache.collections.TestBlockingBuffer.java
/** * Tests interrupted {@link BlockingBuffer#get()}. *//* w ww .j a v a 2 s . co m*/ @Test // @Schedules({ // @Schedule(name = "InterruptedGet", sequence = "[beforeGet:afterGet]@readThread->beforeInterrupt@main," + // "finishAddException@readThread->afterInterrupt@main") }) public void testInterruptedGet() throws InterruptedException { Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer()); Object obj = new Object(); // spawn a read thread to wait on the empty buffer ArrayList exceptionList = new ArrayList(); Thread thread = new ReadThread(blockingBuffer, obj, exceptionList, "InterruptedGet", "readThread"); thread.start(); try { Thread.sleep(100); //INS-SLEEP } catch (Exception e1) { e1.printStackTrace(); } // Interrupting the thread should cause it to throw BufferUnderflowException /* @Event("beforeInterrupt")*/ thread.interrupt(); // Chill, so thread can throw and add message to exceptionList Thread.sleep(100); /* @Event("afterInterrupt")*/ assertTrue("InterruptedGet", exceptionList.contains("BufferUnderFlow")); // assertFalse("InterruptedGet", thread.isAlive()); // if( thread.isAlive() ) { // fail( "Read thread has hung." ); // } }