List of usage examples for java.lang Thread interrupt
public void interrupt()
From source file:org.talend.commons.utils.threading.Locker.java
/** * Method "waitForLock". Lock now if possible with the provided key, else wait for unlocked to lock. * // w ww . java2s . c o m * It allows by default reentrant locks from the first locker thread. If you don't want reentrant lock, you have to * set <code>allowReentrantLockFromLockerThread</code> = <code>false</code> from the <code>Locker</code> * constructor. * * @param key * @param waitTimeMax the maximum time to wait in milliseconds. * @return true if thread has wait a time, else false. * @throws InterruptedException * @throws IllegalArgumentException if bean is null * @deprecated use instead {@link org.talend.commons.utils.threading.lockerbykey.LockerByKey#lockInterruptibly(KP)} * or {@link org.talend.commons.utils.threading.lockerbykey.LockerByKey#tryLock(Object, long)} according the case * (without or with timeout) */ @Deprecated public boolean waitForLock(KP key, final Long waitTimeMax, String contextInfo) throws InterruptedException { check(key); if (!lockIfUnlocked(key, contextInfo)) { waitingThreadsByKey.put(key, Thread.currentThread()); try { if (log.isTraceEnabled()) { log.trace(StringUtils.replacePrms("Waiting for unlocked ({0}) key={1}, contextInfo={2}...", //$NON-NLS-1$ Thread.currentThread().getName(), key, contextInfo)); } final Thread mainThread = Thread.currentThread(); if (waitTimeMax != null) { if (treadsPool == null) { initThreadsPool(); } final Thread[] threadInterruptor = new Thread[1]; final boolean[] threadAlreadyNotified = new boolean[1]; treadsPool.execute(new Runnable() { @Override public void run() { Thread internalThread = Thread.currentThread(); threadInterruptor[0] = internalThread; synchronized (Thread.currentThread()) { try { Thread.currentThread().wait(waitTimeMax); if (!threadAlreadyNotified[0]) { mainThread.interrupt(); } } catch (InterruptedException e) { } } } }); try { synchronized (mainThread) { mainThread.wait(); if (threadInterruptor[0] != null) { threadInterruptor[0].interrupt(); } } } catch (InterruptedException e) { throw e; } finally { threadAlreadyNotified[0] = true; } } else { synchronized (mainThread) { mainThread.wait(); } } if (log.isTraceEnabled()) { log.trace(StringUtils.replacePrms("Waiting ended ({0}) key={1}, contextInfo={2}...", //$NON-NLS-1$ Thread.currentThread().getName(), key, contextInfo)); } waitForLock(key, contextInfo); } catch (InterruptedException e) { throw e; } finally { waitingThreadsByKey.removeValue(key, Thread.currentThread()); } return true; } return false; }
From source file:eu.stratosphere.nephele.checkpointing.ReplayTask.java
/** * Cancels or kills the task./*from w ww . j a va2 s . c o m*/ * * @param cancel * <code>true/code> if the task shall be cancelled, <code>false</code> if it shall be killed */ private void cancelOrKillExecution(final boolean cancel) { final Thread replayThread = this.environment.getExecutingThread(); Thread encapsulatedThread = null; if (this.encapsulatedTask != null) { encapsulatedThread = this.encapsulatedTask.getRuntimeEnvironment().getExecutingThread(); } if (replayThread == null && encapsulatedThread == null) { return; } if (cancel) { this.isCanceled = true; this.replayTaskExecutionState = ExecutionState.CANCELING; if (this.encapsulatedExecutionState != null) { this.encapsulatedExecutionState = ExecutionState.CANCELING; } reportExecutionStateChange(true, null); // Request user code to shut down if (this.encapsulatedTask != null) { try { final AbstractInvokable invokable = this.encapsulatedTask.getRuntimeEnvironment() .getInvokable(); if (invokable != null) { invokable.cancel(); } } catch (Throwable e) { LOG.error(StringUtils.stringifyException(e)); } } } // Continuously interrupt the threads until it changed to state CANCELED while (true) { replayThread.interrupt(); if (encapsulatedThread != null) { encapsulatedThread.interrupt(); } if (cancel) { if (this.overallExecutionState.get() == ExecutionState.CANCELED) { break; } } else { if (this.overallExecutionState.get() == ExecutionState.FAILED) { break; } } try { Thread.sleep(100); } catch (InterruptedException e) { break; } } }
From source file:de.willuhn.jameica.hbci.passports.pintan.ChipTANDialog.java
/** * @see de.willuhn.jameica.gui.dialogs.PasswordDialog#paint(org.eclipse.swt.widgets.Composite) *//*from w w w . j a va 2 s . c om*/ protected void paint(final Composite parent) throws Exception { Container container = new SimpleContainer(parent); if (this.usb) { Application.getMessagingFactory().sendMessage(new StatusBarMessage( i18n.tr("Legen Sie die bitte Chipkarte ein."), StatusBarMessage.TYPE_INFO)); this.setShowPassword(true); // Bei ChipTAN USB immer die TAN anzeigen, damit der User vergleichen kann. container.addHeadline(i18n.tr("ChipTAN USB")); container.addText(i18n.tr( "Legen Sie die Chipkarte ein und folgen Sie den Anweisungen des Kartenlesers. Klicken Sie auf \"OK\", wenn die TAN korrekt bertragen wurde."), true); ProgressBar progress = new ProgressBar(container.getComposite(), SWT.INDETERMINATE); final GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; progress.setLayoutData(gd); final AtomicBoolean cancelled = new AtomicBoolean(false); final Thread usbThread = new Thread() { public void run() { try { Logger.info("trying to get TAN using USB cardreader"); String s = StringUtils.trimToNull(service.getTan(code)); if (s != null && !cancelled.get()) { setPassword(s, parent); } else { throw new Exception(i18n.tr("Keine TAN bertragen")); } } catch (Exception e) { if (!cancelled.get()) { Logger.error("unable to get tan from chipcard", e); setErrorText(i18n.tr("Fehler bei TAN-Ermittlung: {0}", e.getMessage())); } } } }; usbThread.start(); parent.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { cancelled.set(true); // Nur fuer den Fall, dass der Thread noch laeuft. try { if (usbThread != null) usbThread.interrupt(); } catch (Throwable th) { Logger.error("unable to interrupt USB thread", th); } } }); } else { container.addHeadline(i18n.tr(this.usb ? "ChipTAN USB" : "Flicker-Grafik")); container.addText(i18n.tr("Klicken Sie \"-\" bzw. \"+\", um die Breite anzupassen."), true); FlickerPart flicker = new FlickerPart(this.code); flicker.paint(parent); } // Hier stehen dann noch die Anweisungen von der Bank drin super.paint(parent); if (!this.usb) { // Wir muessen das Fenster wenigstens gross genug machen, damit der Flickercode reinpasst, falls // der User den recht verbreitert hat int width = settings.getInt("width", -1); if (width > 0) width += 10; // Wenigstens noch 10 Pixel Rand hinzufuegen. // Wir nehmen den groesseren von beiden Werten getShell().setMinimumSize(getShell().computeSize(width > WINDOW_WIDTH ? width : WINDOW_WIDTH, smallDisplay ? 520 : SWT.DEFAULT)); } }
From source file:org.apache.hadoop.hdfs.TestFileConcurrentReader.java
@Test public void testImmediateReadOfNewFile() throws IOException { final int blockSize = 64 * 1024; final int writeSize = 10 * blockSize; Configuration conf = new Configuration(); conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, blockSize); init(conf);/*from ww w .j a v a 2s.c o m*/ final int requiredSuccessfulOpens = 100; final Path file = new Path("/file1"); final AtomicBoolean openerDone = new AtomicBoolean(false); final AtomicReference<String> errorMessage = new AtomicReference<>(); final FSDataOutputStream out = fileSystem.create(file); final Thread writer = new Thread(new Runnable() { @Override public void run() { try { while (!openerDone.get()) { out.write(DFSTestUtil.generateSequentialBytes(0, writeSize)); out.hflush(); } } catch (IOException e) { LOG.warn("error in writer", e); } finally { try { out.close(); } catch (IOException e) { LOG.error("unable to close file"); } } } }); Thread opener = new Thread(new Runnable() { @Override public void run() { try { for (int i = 0; i < requiredSuccessfulOpens; i++) { fileSystem.open(file).close(); } openerDone.set(true); } catch (IOException e) { openerDone.set(true); errorMessage.set(String.format("got exception : %s", StringUtils.stringifyException(e))); } catch (Exception e) { openerDone.set(true); errorMessage.set(String.format("got exception : %s", StringUtils.stringifyException(e))); writer.interrupt(); fail("here"); } } }); writer.start(); opener.start(); try { writer.join(); opener.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } assertNull(errorMessage.get(), errorMessage.get()); }
From source file:org.apache.hadoop.hdfs.notifier.server.ServerCore.java
@Override public void run() { LOG.info("Starting server ..."); LOG.info("Max heap size: " + Runtime.getRuntime().maxMemory()); // Setup the Thrift server TProtocolFactory protocolFactory = new TBinaryProtocol.Factory(); TTransportFactory transportFactory = new TFramedTransport.Factory(); TNonblockingServerTransport serverTransport; ServerHandler.Processor<ServerHandler.Iface> processor = new ServerHandler.Processor<ServerHandler.Iface>( handler);// w w w. j av a 2 s .c o m try { serverTransport = new TNonblockingServerSocket(listeningPort); } catch (TTransportException e) { LOG.error("Failed to setup the Thrift server.", e); return; } TNonblockingServer.Args serverArgs = new TNonblockingServer.Args(serverTransport); serverArgs.processor(processor).transportFactory(transportFactory).protocolFactory(protocolFactory); tserver = new TNonblockingServer(serverArgs); // Start the worker threads threads.add(new Thread(serverHistory, "Thread-ServerHistory")); threads.add(new Thread(dispatcher, "Thread-Dispatcher")); threads.add(new Thread(logReader, "Thread-LogReader")); threads.add(new Thread(new ThriftServerRunnable(), "Thread-ThriftServer")); LOG.info("Starting thrift server on port " + listeningPort); for (Thread t : threads) { t.start(); } started = true; try { while (!shutdownPending()) { // Read a notification NamespaceNotification notification = logReader.getNamespaceNotification(); if (notification != null) { handleNotification(notification); continue; } } } catch (Exception e) { LOG.error("Failed fetching transaction log data", e); } finally { shutdown(); } long shuttingDownStart = System.currentTimeMillis(); for (Thread t : threads) { long remaining = SHUTDOWN_TIMEOUT + System.currentTimeMillis() - shuttingDownStart; try { if (remaining > 0) { t.join(remaining); } } catch (InterruptedException e) { LOG.error("Interrupted when closing threads at the end"); } if (t.isAlive()) { t.interrupt(); } } LOG.info("Shutdown"); }
From source file:com.att.android.arodatacollector.utils.AROCollectorUtils.java
/** * Executes the specified linux command on the device shell. * /*from ww w . j a v a2 s .c o m*/ * @param shellCommand * A linux native shell command. * * @return The output from the linux native shell command. */ public String runCommand(String shellCommand) { String stdout; String sRet = ""; String stderr; try { final Process m_process = Runtime.getRuntime().exec(shellCommand); final StringBuilder sbread = new StringBuilder(); final 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) { AROLogger.e(TAG, "IOException in runCommand" + e); } finally { try { bufferedReader.close(); } catch (IOException e) { AROLogger.e(TAG, "Exception in runCommand bufferedReader.close()" + e); } } } }); tout.start(); final StringBuilder sberr = new StringBuilder(); final Thread terr = new Thread(new Runnable() { public void run() { final 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) { AROLogger.e(TAG, "Exception in runCommand" + e); } finally { try { bufferedReader.close(); } catch (IOException e) { AROLogger.e(TAG, "Exception in runCommand bufferedReader.close()" + e); } } } }); terr.start(); while (tout.isAlive()) { Thread.sleep(50); } if (terr.isAlive()) terr.interrupt(); stdout = sbread.toString(); stderr = sberr.toString(); sRet = stdout + stderr; } catch (java.io.IOException ee) { AROLogger.e(TAG, "Exception in runCommand" + ee); return null; } catch (InterruptedException ie) { AROLogger.e(TAG, "Exception in runCommand" + ie); return null; } return sRet; }
From source file:org.apache.tajo.cli.tsql.TestTajoCli.java
License:asdf
@Test public void testRunWhenError() throws Exception { Thread t = new Thread() { public void run() { try { PipedOutputStream po = new PipedOutputStream(); InputStream is = new PipedInputStream(po); ByteArrayOutputStream out = new ByteArrayOutputStream(); TajoConf tajoConf = new TajoConf(); setVar(tajoCli, SessionVars.CLI_FORMATTER_CLASS, TajoCliOutputTestFormatter.class.getName()); Properties connParams = new Properties(); connParams.setProperty(ClientParameters.RETRY, "3"); TajoCli tc = new TajoCli(tajoConf, new String[] {}, connParams, is, out, err); tc.executeMetaCommand("\\set ON_ERROR_STOP false"); assertSessionVar(tc, SessionVars.ON_ERROR_STOP.keyname(), "false"); po.write(new String("asdf;\nqwe;\nzxcv;\n").getBytes()); tc.runShell();//from www . j a va2 s. c om } catch (Exception e) { throw new RuntimeException("Cannot run thread in testRunWhenError", e); } } }; t.start(); Thread.sleep(1000); if (!t.isAlive()) { fail("TSQL should be alive"); } else { t.interrupt(); t.join(); } }
From source file:fm.smart.r1.ItemActivity.java
public void addToList(final String item_id) { final ProgressDialog myOtherProgressDialog = new ProgressDialog(this); myOtherProgressDialog.setTitle("Please Wait ..."); myOtherProgressDialog.setMessage("Adding item to study goal ..."); myOtherProgressDialog.setIndeterminate(true); myOtherProgressDialog.setCancelable(true); final Thread add = new Thread() { public void run() { ItemActivity.add_item_result = new AddItemResult( Main.lookup.addItemToGoal(Main.transport, Main.default_study_goal_id, item_id, null)); myOtherProgressDialog.dismiss(); ItemActivity.this.runOnUiThread(new Thread() { public void run() { final AlertDialog dialog = new AlertDialog.Builder(ItemActivity.this).create(); dialog.setTitle(ItemActivity.add_item_result.getTitle()); dialog.setMessage(ItemActivity.add_item_result.getMessage()); ItemActivity.add_item_result = null; dialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { }//from w w w . j av a2 s . c om }); dialog.show(); } }); } }; myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { add.interrupt(); } }); OnCancelListener ocl = new OnCancelListener() { public void onCancel(DialogInterface arg0) { add.interrupt(); } }; myOtherProgressDialog.setOnCancelListener(ocl); closeMenu(); myOtherProgressDialog.show(); add.start(); }
From source file:fm.smart.r1.activity.CreateExampleActivity.java
public void onClick(View v) { EditText exampleInput = (EditText) findViewById(R.id.create_example_sentence); EditText translationInput = (EditText) findViewById(R.id.create_example_translation); EditText exampleTransliterationInput = (EditText) findViewById(R.id.sentence_transliteration); EditText translationTransliterationInput = (EditText) findViewById(R.id.translation_transliteration); final String example = exampleInput.getText().toString(); final String translation = translationInput.getText().toString(); if (TextUtils.isEmpty(example) || TextUtils.isEmpty(translation)) { Toast t = Toast.makeText(this, "Example and translation are required fields", 150); t.setGravity(Gravity.CENTER, 0, 0); t.show();/* w w w. jav a 2 s .co m*/ } else { final String example_language_code = Utils.LANGUAGE_MAP.get(example_language); final String translation_language_code = Utils.LANGUAGE_MAP.get(translation_language); final String example_transliteration = exampleTransliterationInput.getText().toString(); final String translation_transliteration = translationTransliterationInput.getText().toString(); if (Main.isNotLoggedIn(this)) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setClassName(this, LoginActivity.class.getName()); intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); // avoid // navigation // back to this? LoginActivity.return_to = CreateExampleActivity.class.getName(); LoginActivity.params = new HashMap<String, String>(); LoginActivity.params.put("list_id", list_id); LoginActivity.params.put("item_id", item_id); LoginActivity.params.put("example", example); LoginActivity.params.put("translation", translation); LoginActivity.params.put("example_language", example_language); LoginActivity.params.put("translation_language", translation_language); LoginActivity.params.put("example_transliteration", example_transliteration); LoginActivity.params.put("translation_transliteration", translation_transliteration); startActivity(intent); } else { final ProgressDialog myOtherProgressDialog = new ProgressDialog(this); myOtherProgressDialog.setTitle("Please Wait ..."); myOtherProgressDialog.setMessage("Creating Example ..."); myOtherProgressDialog.setIndeterminate(true); myOtherProgressDialog.setCancelable(true); final Thread create_example = new Thread() { public void run() { // TODO make this interruptable .../*if // (!this.isInterrupted())*/ try { // TODO failures here could derail all ... CreateExampleActivity.add_item_list_result = ItemActivity.addItemToList(list_id, item_id, CreateExampleActivity.this); CreateExampleActivity.create_example_result = createExample(example, example_language_code, example_transliteration, translation, translation_language_code, translation_transliteration, item_id, list_id); CreateExampleActivity.add_sentence_list_result = ItemActivity.addSentenceToList( CreateExampleActivity.create_example_result.http_response, item_id, list_id, CreateExampleActivity.this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } myOtherProgressDialog.dismiss(); } }; myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { create_example.interrupt(); } }); OnCancelListener ocl = new OnCancelListener() { public void onCancel(DialogInterface arg0) { create_example.interrupt(); } }; myOtherProgressDialog.setOnCancelListener(ocl); myOtherProgressDialog.show(); create_example.start(); } } }
From source file:org.jitsi.sphinx4http.server.Session.java
/** * transcribe the given audio file and send each retrieved word back * immediately. The word will be a JSON object with values, word, start, * end, filler'./*www .j a v a 2s .co m*/ * @param audioFile the audio file to transcribe * @param out the outputstream to write each word results to immediately * @return JSON array with every uttered word in the audio file */ public JSONArray chunkedTranscribe(File audioFile, PrintWriter out) throws IOException { logger.trace("started chunked transcribing of " + "audio file with id : {}", id); try (InputStream in = new FileInputStream(audioFile)) { // create a thread to immediately get the word result out // of the synchronousQueue final SynchronousQueue<WordResult> results = new SynchronousQueue<>(); final ArrayList<WordResult> storedResults = new ArrayList<>(); //make sure the printwriter does not close because it's needed //else where to finish the object final PrintWriter printWriter = new PrintWriter(out); Thread queueManager = new Thread(new Runnable() { @Override public void run() { //listen for the first word outside of the loop //to prevent a trailing "," at the end of the transcription //json array try { WordResult word = results.take(); logger.trace("retrieved word outside loop\"{}\"", word.toString()); storedResults.add(word); JSONObject toSend = builder.buildWordObject(word); printWriter.write("," + toSend.toJSONString()); printWriter.flush(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } while (!Thread.currentThread().isInterrupted()) { try { //blocks until result is retrieved WordResult word = results.take(); logger.trace("retrieved word \"{}\"", word.toString()); storedResults.add(word); JSONObject toSend = builder.buildWordObject(word); printWriter.write("," + toSend.toJSONString()); printWriter.flush(); } catch (InterruptedException e) { //make sure the thread ends Thread.currentThread().interrupt(); } } } }); queueManager.start(); transcriber.transcribeSynchronous(in, results); //stop the thread as the transcribing is done queueManager.interrupt(); return builder.buildSpeechToTextResult(storedResults); } }