List of usage examples for java.lang Thread interrupt
public void interrupt()
From source file:edu.illinois.enforcemop.examples.apache.collections.TestBlockingBuffer.java
/** * Tests interrupted remove.//from w w w. jav a 2s. c om */ @Test // @Schedules({ // @Schedule(name = "InterruptedRemove", sequence = "[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 /* @Event("beforeInterrupt")*/ thread.interrupt(); // Chill, so thread can throw and add message to exceptionList Thread.sleep(100); /* @Event("afterInterrupt")*/ assertTrue("InterruptedRemove", exceptionList.contains("BufferUnderFlow")); //assertFalse("InterruptedRemove",thread.isAlive()); //if( thread.isAlive() ) { //fail( "Read thread has hung." ); //} }
From source file:org.kchine.rpf.PoolUtils.java
public static void callBack(final ServantCreationListener servantCreationListener, final ManagedServant servant, final RemoteException exception) { try {/*from www . ja v a 2 s .c o m*/ final Object[] resultHolder = new Object[1]; Runnable setServantStubRunnable = new Runnable() { public void run() { try { if (servant != null) { servantCreationListener.setServantStub(servant); } else { servantCreationListener.setRemoteException(exception); } resultHolder[0] = PoolUtils.SET_SERVANT_STUB_DONE; } catch (Exception e) { final boolean wasInterrupted = Thread.interrupted(); if (wasInterrupted) { resultHolder[0] = new RmiCallInterrupted(); } else { resultHolder[0] = e; } } } }; Thread setServantStubThread = InterruptibleRMIThreadFactory.getInstance() .newThread(setServantStubRunnable); setServantStubThread.start(); long t1 = System.currentTimeMillis(); while (resultHolder[0] == null) { if ((System.currentTimeMillis() - t1) > PoolUtils.SET_SERVANT_STUB_TIMEOUT_MILLISEC) { setServantStubThread.interrupt(); resultHolder[0] = new RmiCallTimeout(); break; } try { Thread.sleep(10); } catch (Exception e) { } } if (resultHolder[0] instanceof Throwable) { throw (RemoteException) resultHolder[0]; } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.bookkeeper.bookie.LedgerCacheTest.java
/** * Race where a flush would fail because a garbage collection occurred at * the wrong time.//from w w w .j av a2 s. c o m * {@link https://issues.apache.org/jira/browse/BOOKKEEPER-604} */ @Test(timeout = 60000) public void testFlushDeleteRace() throws Exception { newLedgerCache(); final AtomicInteger rc = new AtomicInteger(0); final LinkedBlockingQueue<Long> ledgerQ = new LinkedBlockingQueue<Long>(1); final byte[] masterKey = "masterKey".getBytes(); Thread newLedgerThread = new Thread() { public void run() { try { for (int i = 0; i < 1000 && rc.get() == 0; i++) { ledgerCache.setMasterKey(i, masterKey); ledgerQ.put((long) i); } } catch (Exception e) { rc.set(-1); LOG.error("Exception in new ledger thread", e); } } }; newLedgerThread.start(); Thread flushThread = new Thread() { public void run() { try { while (true) { Long id = ledgerQ.peek(); if (id == null) { continue; } LOG.info("Put entry for {}", id); try { ledgerCache.putEntryOffset((long) id, 1, 0); } catch (Bookie.NoLedgerException nle) { //ignore } ledgerCache.flushLedger(true); } } catch (Exception e) { rc.set(-1); LOG.error("Exception in flush thread", e); } } }; flushThread.start(); Thread deleteThread = new Thread() { public void run() { try { while (true) { long id = ledgerQ.take(); LOG.info("Deleting {}", id); ledgerCache.deleteLedger(id); } } catch (Exception e) { rc.set(-1); LOG.error("Exception in delete thread", e); } } }; deleteThread.start(); newLedgerThread.join(); assertEquals("Should have been no errors", rc.get(), 0); deleteThread.interrupt(); flushThread.interrupt(); }
From source file:Animations.java
public Animations() { shell.setLayout(new FillLayout()); ImageLoader imageLoader = new ImageLoader(); final ImageData[] imageDatas = imageLoader.load("java2s.gif"); final Image image = new Image(display, imageDatas[0].width, imageDatas[0].height); final Canvas canvas = new Canvas(shell, SWT.NULL); canvas.addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { e.gc.drawImage(image, 0, 0); }/*w w w. j ava 2s. co m*/ }); final GC gc = new GC(image); final Thread thread = new Thread() { int frameIndex = 0; public void run() { while (!isInterrupted()) { frameIndex %= imageDatas.length; final ImageData frameData = imageDatas[frameIndex]; display.asyncExec(new Runnable() { public void run() { Image frame = new Image(display, frameData); gc.drawImage(frame, frameData.x, frameData.y); frame.dispose(); canvas.redraw(); } }); try { // delay Thread.sleep(imageDatas[frameIndex].delayTime * 10); } catch (InterruptedException e) { return; } frameIndex += 1; } } }; shell.addShellListener(new ShellAdapter() { public void shellClosed(ShellEvent e) { thread.interrupt(); } }); shell.setSize(400, 200); shell.open(); thread.start(); // Set up the event loop. while (!shell.isDisposed()) { if (!display.readAndDispatch()) { // If no more entries in event queue display.sleep(); } } display.dispose(); }
From source file:net.pms.PMS.java
/** * Executes a new Process and creates a fork that waits for its results. * TODO Extend explanation on where this is being used. * @param name Symbolic name for the process to be launched, only used in the trace log * @param error (boolean) Set to true if you want PMS to add error messages to the trace pane * @param workDir (File) optional working directory to run the process in * @param params (array of Strings) array containing the command to call and its arguments * @return Returns true if the command exited as expected * @throws Exception TODO: Check which exceptions to use *//*from w w w . j a v a 2 s. com*/ private boolean checkProcessExistence(String name, boolean error, File workDir, String... params) throws Exception { logger.debug("launching: " + params[0]); try { ProcessBuilder pb = new ProcessBuilder(params); if (workDir != null) { pb.directory(workDir); } final Process process = pb.start(); OutputTextConsumer stderrConsumer = new OutputTextConsumer(process.getErrorStream(), false); stderrConsumer.start(); OutputTextConsumer outConsumer = new OutputTextConsumer(process.getInputStream(), false); outConsumer.start(); Runnable r = new Runnable() { public void run() { ProcessUtil.waitFor(process); } }; Thread checkThread = new Thread(r, "PMS Checker"); checkThread.start(); checkThread.join(60000); checkThread.interrupt(); checkThread = null; // XXX no longer used if (params[0].equals("vlc") && stderrConsumer.getResults().get(0).startsWith("VLC")) { return true; } // XXX no longer used if (params[0].equals("ffmpeg") && stderrConsumer.getResults().get(0).startsWith("FF")) { return true; } int exit = process.exitValue(); if (exit != 0) { if (error) { logger.info("[" + exit + "] Cannot launch " + name + " / Check the presence of " + params[0] + " ..."); } return false; } return true; } catch (Exception e) { if (error) { logger.error("Cannot launch " + name + " / Check the presence of " + params[0] + " ...", e); } return false; } }
From source file:org.apache.directory.studio.connection.core.io.api.DirectoryApiConnectionWrapper.java
/** * {@inheritDoc}//from w w w . j av a2 s .com */ public void disconnect() { if (jobThread != null) { Thread t = jobThread; jobThread = null; t.interrupt(); } if (ldapConnection != null) { try { ldapConnection.close(); } catch (Exception e) { // ignore } ldapConnection = null; binaryAttributeDetector = null; } isConnected = false; }
From source file:jp.terasoluna.fw.web.thin.LimitedLock.java
/** * ?bN?B//ww w. j av a2 s .c om * <p> * ?Xbh?bN?AXbh?Xbh??s?A?Xbh@?B<br> * ?Xbh?bN???A?\bhA?B<br> * Xbh?Xbh??s???AInterruptedExceptionX??[?A?Xbh?Xe?[^XNA?B<br> * (?ANXO????A?Xe?[^Xs?B) * </p> * <p> * ?L?AX?[p?[NX?Bg|Cg?B<br> * <ul> * <li>?bNXbh?l??\bh?s?A?bNO?AlXbh?A?bNXbhf?B<br> * ?bNXbh?\bh?s(??bN)?A?bNXbh??AXbhf?s?B</li> * </ul> * </p> * @throws InterruptedException ?Xbh????(NX@\?A?bNf??) * @see java.util.concurrent.locks.ReentrantLock#lockInterruptibly() */ @Override public void lockInterruptibly() throws InterruptedException { boolean successToLock = false; // ?bNXbh????A // ?VXbh?bNv??A // ?bNXbh??B // (?bN?Xbh?AI?bN(??bN)|???A // ?bNXbh??B) if (getOwner() != Thread.currentThread()) { synchronized (lock) { // u?bN???Asuper.unlock();?s?A?bNXbh?bN?B // Xbh?bN???A // ?bNXbh?bN?A // Xbh?A?J?A?bN?oR?bN??A // ?bN?\bhXbh?A??Xbh?B // ?AXbh?bN??A // ?Au?bN?Asuper.lockInterruptibly();?sOXbh????A // Xbh?Au?bN???A?????? // (?bNXbh???AXbh?A??)?A // Xbh?bN??A?bNv?Xbh?l??A // ??@?Ax??B int queueLength = getQueueLength(); if (queueLength > threshold) { HashSet<Thread> oldWaitingThreadSet = null; synchronized (waitingThreadList) { List<Thread> oldWaitingThreadList = waitingThreadList.subList(0, queueLength - threshold); oldWaitingThreadSet = new HashSet<Thread>(oldWaitingThreadList); } // waitingThreadListXbh?A // ??bNXbh?A // ??bNXbhXg?A // oldWaitingThreadListoldWaitingThreadSet?AgetQueuedThreads()?B for (Thread queuedThread : getQueuedThreads()) { if (oldWaitingThreadSet.contains(queuedThread)) { if (log.isDebugEnabled()) { log.debug("interrupt thread '" + queuedThread + "'."); } synchronized (waitingThreadList) { // ?waitingThreadList.remove?A?XbhfinallyO?A?s? // ?XbhremoveO?AXbh?f?s\??A // f??Xbh??A // remove?B waitingThreadList.remove(queuedThread); queuedThread.interrupt(); // ??A // Xbh?bNL?[?o^CO?A // Xbh?A???getQueueLength()?s?A // getQueueLength()?AwaitingThreadList??A // waitingThreadList.subLists(ListsubLists)?A // (synchronized (lock))?AXbh?bNL?[?o?B while (getQueuedThreads().contains(queuedThread)) { Thread.yield(); } } } } } } } try { synchronized (waitingThreadList) { waitingThreadList.add(Thread.currentThread()); } super.lockInterruptibly(); successToLock = true; } finally { // O??A // NX?(?s)???s?? // NX?(/?s)???I // ???sKv?A // locktB?[h?bN?B synchronized (lock) { synchronized (waitingThreadList) { waitingThreadList.remove(Thread.currentThread()); // O?remove?Aremove if (!successToLock) { // O?NX????A // ?Xe?[^Xc?A // ?Xe?[^XNA?B // ?bN??AreturnO????A // ?Xe?[^XNAreturn?B Thread.interrupted(); } } } } }
From source file:org.apache.hadoop.hbase.client.TestAsyncProcess.java
@Test public void testMaxTask() throws Exception { final AsyncProcess ap = new MyAsyncProcess(createHConnection(), conf, false); for (int i = 0; i < 1000; i++) { ap.incTaskCounters(Arrays.asList("dummy".getBytes()), sn); }//from ww w . j av a 2 s . c o m final Thread myThread = Thread.currentThread(); Thread t = new Thread() { @Override public void run() { Threads.sleep(2000); myThread.interrupt(); } }; List<Put> puts = new ArrayList<Put>(); puts.add(createPut(1, true)); t.start(); try { ap.submit(DUMMY_TABLE, puts, false, null, false); Assert.fail("We should have been interrupted."); } catch (InterruptedIOException expected) { } final long sleepTime = 2000; Thread t2 = new Thread() { @Override public void run() { Threads.sleep(sleepTime); while (ap.tasksInProgress.get() > 0) { ap.decTaskCounters(Arrays.asList("dummy".getBytes()), sn); } } }; t2.start(); long start = System.currentTimeMillis(); ap.submit(DUMMY_TABLE, new ArrayList<Row>(), false, null, false); long end = System.currentTimeMillis(); //Adds 100 to secure us against approximate timing. Assert.assertTrue(start + 100L + sleepTime > end); }
From source file:fm.smart.r1.activity.CreateSoundActivity.java
public void onClick(View v) { String threegpfile_name = "test.3gp_amr"; String amrfile_name = "test.amr"; File dir = this.getDir("sounds", MODE_WORLD_READABLE); final File threegpfile = new File(dir, threegpfile_name); File amrfile = new File(dir, amrfile_name); String path = threegpfile.getAbsolutePath(); Log.d("CreateSoundActivity", path); Log.d("CreateSoundActivity", (String) button.getText()); if (button.getText().equals("Start")) { try {//w w w. j a v a 2 s . com recorder = new MediaRecorder(); // ContentValues values = new ContentValues(3); // // values.put(MediaStore.MediaColumns.TITLE, "test"); // values.put(MediaStore.MediaColumns.DATE_ADDED, // System.currentTimeMillis()); // values.put(MediaStore.MediaColumns.MIME_TYPE, // MediaRecorder.OutputFormat.THREE_GPP); // // ContentResolver contentResolver = new ContentResolver(this); // // Uri base = MediaStore.Audio.INTERNAL_CONTENT_URI; // Uri newUri = contentResolver.insert(base, values); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setOutputFile(path); recorder.prepare(); button.setText("Stop"); recorder.start(); } catch (Exception e) { Log.w(TAG, e); } } else { FileOutputStream os = null; FileInputStream is = null; try { recorder.stop(); recorder.release(); // Now the object cannot be reused button.setEnabled(false); // ThreegpReader tr = new ThreegpReader(threegpfile); // os = new FileOutputStream(amrfile); // tr.extractAmr(os); is = new FileInputStream(threegpfile); playSound(is.getFD()); final String media_entity = "http://test.com/test.mp3"; final String author = "tansaku"; final String author_url = "http://smart.fm/users/tansaku"; if (Main.isNotLoggedIn(this)) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setClassName(this, LoginActivity.class.getName()); intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); LoginActivity.return_to = CreateSoundActivity.class.getName(); LoginActivity.params = new HashMap<String, String>(); LoginActivity.params.put("item_id", item_id); LoginActivity.params.put("list_id", list_id); LoginActivity.params.put("id", id); LoginActivity.params.put("to_record", to_record); LoginActivity.params.put("sound_type", sound_type); startActivity(intent); } else { final ProgressDialog myOtherProgressDialog = new ProgressDialog(this); myOtherProgressDialog.setTitle("Please Wait ..."); myOtherProgressDialog.setMessage("Creating Sound ..."); myOtherProgressDialog.setIndeterminate(true); myOtherProgressDialog.setCancelable(true); final Thread create_sound = new Thread() { public void run() { // TODO make this interruptable .../*if // (!this.isInterrupted())*/ CreateSoundActivity.create_sound_result = createSound(threegpfile, media_entity, author, author_url, "1", id); myOtherProgressDialog.dismiss(); } }; myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { create_sound.interrupt(); } }); OnCancelListener ocl = new OnCancelListener() { public void onCancel(DialogInterface arg0) { create_sound.interrupt(); } }; myOtherProgressDialog.setOnCancelListener(ocl); myOtherProgressDialog.show(); create_sound.start(); } } catch (Exception e) { Log.w(TAG, e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (is != null) { try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
From source file:fr.gael.dhus.util.stream.ProductDownloadStreamFactory.java
@Override public synchronized InputStream generateInputStream(ProductInfo productInfo, Source source, SynchronizerRules rules, long skip) { // generate HTTP client int timeout = rules.getTimeout().intValue(); InterruptibleHttpClient client = new InterruptibleHttpClient( new BasicAuthHttpClientProducer(source.getUsername(), source.getPassword(), timeout)); // generate download url String url = productInfo.getDownloadUrl(source.getUrl()); // generate stream boolean canResume; String etag;/* www . j a v a 2s .com*/ HttpResponse headers; Thread downloadThread = null; try { headers = client.interruptibleHead(url); // check availability of content if (headers.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { return null; } // retrieve content information if (headers.containsHeader(HTTP_HEADER_ETAG)) { etag = headers.getFirstHeader(HTTP_HEADER_ETAG).getValue(); canResume = headers.containsHeader(HTTP_HEADER_ACCEPT_RANGE); } else { etag = null; canResume = false; } Pipe pipe = Pipe.open(); DownloadTask downloadTask = new DownloadTask(pipe, client, url, etag, skip, productInfo.getSize(), rules.getAttempts(), canResume); downloadThread = new Thread(downloadTask, THREAD_NAME); downloadThread.start(); return Channels.newInputStream(pipe.source()); } catch (InterruptedException | IOException e) { if (downloadThread != null) { downloadThread.interrupt(); } return null; } }