List of usage examples for java.lang Thread isInterrupted
public boolean isInterrupted()
From source file:org.apache.oozie.coord.CoordELFunctions.java
private static String coord_latestRange_sync(int startOffset, int endOffset) throws Exception { final XLog LOG = XLog.getLog(CoordELFunctions.class); final Thread currentThread = Thread.currentThread(); ELEvaluator eval = ELEvaluator.getCurrent(); String retVal = ""; int datasetFrequency = (int) getDSFrequency();// in minutes TimeUnit dsTimeUnit = getDSTimeUnit(); int[] instCount = new int[1]; boolean useCurrentTime = Services.get().getConf().getBoolean(LATEST_EL_USE_CURRENT_TIME, false); Calendar nominalInstanceCal;/*from w w w . jav a2 s.c o m*/ if (useCurrentTime) { nominalInstanceCal = getCurrentInstance(new Date(), instCount); } else { nominalInstanceCal = getCurrentInstance(getActualTime(), instCount); } StringBuilder resolvedInstances = new StringBuilder(); StringBuilder resolvedURIPaths = new StringBuilder(); if (nominalInstanceCal != null) { Calendar initInstance = getInitialInstanceCal(); SyncCoordDataset ds = (SyncCoordDataset) eval.getVariable(DATASET); if (ds == null) { throw new RuntimeException("Associated Dataset should be defined with key " + DATASET); } String uriTemplate = ds.getUriTemplate(); Configuration conf = (Configuration) eval.getVariable(CONFIGURATION); if (conf == null) { throw new RuntimeException("Associated Configuration should be defined with key " + CONFIGURATION); } int available = 0; boolean resolved = false; String user = ParamChecker.notEmpty((String) eval.getVariable(OozieClient.USER_NAME), OozieClient.USER_NAME); String doneFlag = ds.getDoneFlag(); URIHandlerService uriService = Services.get().get(URIHandlerService.class); URIHandler uriHandler = null; Context uriContext = null; try { while (nominalInstanceCal.compareTo(initInstance) >= 0 && !currentThread.isInterrupted()) { ELEvaluator uriEval = getUriEvaluator(nominalInstanceCal); String uriPath = uriEval.evaluate(uriTemplate, String.class); if (uriHandler == null) { URI uri = new URI(uriPath); uriHandler = uriService.getURIHandler(uri); uriContext = uriHandler.getContext(uri, conf, user, true); } String uriWithDoneFlag = uriHandler.getURIWithDoneFlag(uriPath, doneFlag); if (uriHandler.exists(new URI(uriWithDoneFlag), uriContext)) { XLog.getLog(CoordELFunctions.class) .debug("Found latest(" + available + "): " + uriWithDoneFlag); if (available == startOffset) { LOG.debug("Matched latest(" + available + "): " + uriWithDoneFlag); resolved = true; resolvedInstances.append(DateUtils.formatDateOozieTZ(nominalInstanceCal)); resolvedURIPaths.append(uriPath); retVal = resolvedInstances.toString(); eval.setVariable(CoordELConstants.RESOLVED_PATH, resolvedURIPaths.toString()); break; } else if (available <= endOffset) { LOG.debug("Matched latest(" + available + "): " + uriWithDoneFlag); resolvedInstances.append(DateUtils.formatDateOozieTZ(nominalInstanceCal)) .append(INSTANCE_SEPARATOR); resolvedURIPaths.append(uriPath).append(INSTANCE_SEPARATOR); } available--; } // nominalInstanceCal.add(dsTimeUnit.getCalendarUnit(), -datasetFrequency); nominalInstanceCal = (Calendar) initInstance.clone(); instCount[0]--; nominalInstanceCal.add(dsTimeUnit.getCalendarUnit(), instCount[0] * datasetFrequency); // DateUtils.moveToEnd(nominalInstanceCal, getDSEndOfFlag()); } if (!StringUtils.isEmpty(resolvedURIPaths.toString()) && eval.getVariable(CoordELConstants.RESOLVED_PATH) == null) { eval.setVariable(CoordELConstants.RESOLVED_PATH, resolvedURIPaths.toString()); } } finally { if (uriContext != null) { uriContext.destroy(); } } if (!resolved) { // return unchanged latest function with variable 'is_resolved' // to 'false' eval.setVariable(CoordELConstants.IS_RESOLVED, Boolean.FALSE); if (startOffset == endOffset) { retVal = "${coord:latest(" + startOffset + ")}"; } else { retVal = "${coord:latestRange(" + startOffset + "," + endOffset + ")}"; } } else { eval.setVariable(CoordELConstants.IS_RESOLVED, Boolean.TRUE); } } else {// No feasible nominal time eval.setVariable(CoordELConstants.IS_RESOLVED, Boolean.FALSE); } return retVal; }
From source file:org.apache.cassandra.concurrent.ContinuationsExecutor.java
/** * Checks if a new worker can be added with respect to current pool state * and the given bound (either core or maximum). If so, the worker count is * adjusted accordingly, and, if possible, a new worker is created and * started running firstTask as its first task. This method returns false if * the pool is stopped or eligible to shut down. It also returns false if * the thread factory fails to create a thread when asked, which requires a * backout of workerCount, and a recheck for termination, in case the * existence of this worker was holding up termination. * /* w w w . j a v a 2s. c om*/ * @param firstTask * the task the new thread should run first (or null if none). * Workers are created with an initial first task (in method * execute()) to bypass queuing when there are fewer than * corePoolSize threads (in which case we always start one), or * when the queue is full (in which case we must bypass queue). * Initially idle threads are usually created via * prestartCoreThread or to replace other dying workers. * * @param core * if true use corePoolSize as bound, else maximumPoolSize. (A * boolean indicator is used here rather than a value to ensure * reads of fresh values after checking other pool state). * @return true if successful */ private boolean addWorker(Runnable firstTask, boolean core) { retry: for (;;) { int c = ctl.get(); int rs = runStateOf(c); // Check if queue empty only if necessary. if (rs >= SHUTDOWN && !(rs == SHUTDOWN && firstTask == null && !workQueue.isEmpty())) return false; for (;;) { int wc = workerCountOf(c); if (wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize)) return false; if (compareAndIncrementWorkerCount(c)) break retry; c = ctl.get(); // Re-read ctl if (runStateOf(c) != rs) continue retry; // else CAS failed due to workerCount change; retry inner loop } } Worker w = new Worker(firstTask); Thread t = w.thread; final ReentrantLock mainLock = this.mainLock; mainLock.lock(); try { // Recheck while holding lock. // Back out on ThreadFactory failure or if // shut down before lock acquired. int c = ctl.get(); int rs = runStateOf(c); if (t == null || (rs >= SHUTDOWN && !(rs == SHUTDOWN && firstTask == null))) { decrementWorkerCount(); tryTerminate(); return false; } workers.add(w); int s = workers.size(); if (s > largestPoolSize) largestPoolSize = s; } finally { mainLock.unlock(); } t.start(); // It is possible (but unlikely) for a thread to have been // added to workers, but not yet started, during transition to // STOP, which could result in a rare missed interrupt, // because Thread.interrupt is not guaranteed to have any effect // on a non-yet-started Thread (see Thread#interrupt). if (runStateOf(ctl.get()) == STOP && !t.isInterrupted()) t.interrupt(); return true; }
From source file:org.yccheok.jstock.gui.IndicatorPanel.java
private void simulate(final Stock stock) { JStock m = JStock.instance();//from ww w . j a va2s.com // First, check whether there is a need to get history. final IndicatorDefaultDrawing indicatorDefaultDrawing = (IndicatorDefaultDrawing) this.view.getDrawing(); final OperatorIndicator operatorIndicator = indicatorDefaultDrawing.getOperatorIndicator(); final Duration historyDuration = operatorIndicator.getNeededStockHistoryDuration(); final Thread currentThread = Thread.currentThread(); // When stock is null, this means this indicator needs neither stock real-time information // nor stock history information. if (stock != null && operatorIndicator.isStockHistoryServerNeeded()) { m.setStatusBar(true, MessagesBundle.getString("info_message_stock_history_retrieving_in_progress...")); // Avoid from using old history monitor. Their duration are not the same. final Duration oldDuration = stockHistoryMonitor.getDuration(); if (oldDuration == null || oldDuration.equals(historyDuration) == false) { this.initStockHistoryMonitor(); this.stockHistoryMonitor.setDuration(historyDuration); } // Action! StockHistoryServer stockHistoryServer = this.stockHistoryMonitor.getStockHistoryServer(stock.code); if (stockHistoryServer == null) { final java.util.concurrent.CountDownLatch countDownLatch = new java.util.concurrent.CountDownLatch( 1); final org.yccheok.jstock.engine.Observer<StockHistoryMonitor, StockHistoryMonitor.StockHistoryRunnable> observer = new org.yccheok.jstock.engine.Observer<StockHistoryMonitor, StockHistoryMonitor.StockHistoryRunnable>() { @Override public void update(StockHistoryMonitor monitor, StockHistoryMonitor.StockHistoryRunnable runnable) { if (runnable.getCode().equals(stock.code)) { countDownLatch.countDown(); } } }; this.stockHistoryMonitor.attach(observer); this.stockHistoryMonitor.addStockCode(stock.code); try { countDownLatch.await(); } catch (java.lang.InterruptedException exp) { log.error(null, exp); return; } this.stockHistoryMonitor.dettach(observer); stockHistoryServer = this.stockHistoryMonitor.getStockHistoryServer(stock.code); } if (stockHistoryServer == null) { // Start button. this.jButton4.setEnabled(true); // Stop button. this.jButton6.setEnabled(false); m.setStatusBar(false, MessagesBundle.getString("info_message_history_not_found")); return; } if (currentThread.isInterrupted() || simulationThread != currentThread) { return; } m.setStatusBar(true, MessagesBundle.getString("info_message_stock_history_information_calculation_in_progress...")); operatorIndicator.setStockHistoryServer(stockHistoryServer); } /* if(operatorIndicator.isStockHistoryServerNeeded()) { */ if (currentThread.isInterrupted() || simulationThread != currentThread) { return; } m.setStatusBar(true, MessagesBundle.getString("info_message_real_time_stock_information_calculation_in_progress...")); operatorIndicator.preCalculate(); if (currentThread.isInterrupted() || simulationThread != currentThread) { return; } m.setStatusBar(true, MessagesBundle.getString("info_message_final_calculation...")); long startTime = System.nanoTime(); if (stock != null) { operatorIndicator.setStock(stock); } operatorIndicator.isTriggered(); long estimatedTime = System.nanoTime() - startTime; if (currentThread.isInterrupted() || simulationThread != currentThread) { return; } final String output = MessageFormat.format( MessagesBundle.getString("info_message_simulation_done_with_time_taken_template"), ((double) estimatedTime / (double) 1000000.0)); m.setStatusBar(false, output); // Start button. this.jButton4.setEnabled(true); // Stop button. this.jButton6.setEnabled(false); }
From source file:RhodesService.java
private File downloadPackage(String url) throws IOException { final Context ctx = RhodesActivity.getContext(); final Thread thisThread = Thread.currentThread(); final Runnable cancelAction = new Runnable() { public void run() { thisThread.interrupt();/*w w w . j a v a 2 s.com*/ } }; BroadcastReceiver downloadReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ACTION_ASK_CANCEL_DOWNLOAD)) { AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setMessage("Cancel download?"); AlertDialog dialog = builder.create(); dialog.setButton(AlertDialog.BUTTON_POSITIVE, ctx.getText(android.R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { cancelAction.run(); } }); dialog.setButton(AlertDialog.BUTTON_NEGATIVE, ctx.getText(android.R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Nothing } }); dialog.show(); } else if (action.equals(ACTION_CANCEL_DOWNLOAD)) { cancelAction.run(); } } }; IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_ASK_CANCEL_DOWNLOAD); filter.addAction(ACTION_CANCEL_DOWNLOAD); ctx.registerReceiver(downloadReceiver, filter); File tmpFile = null; InputStream is = null; OutputStream os = null; try { updateDownloadNotification(url, -1, 0); /* List<File> folders = new ArrayList<File>(); folders.add(Environment.getDownloadCacheDirectory()); folders.add(Environment.getDataDirectory()); folders.add(ctx.getCacheDir()); folders.add(ctx.getFilesDir()); try { folders.add(new File(ctx.getPackageManager().getApplicationInfo(ctx.getPackageName(), 0).dataDir)); } catch (NameNotFoundException e1) { // Ignore } folders.add(Environment.getExternalStorageDirectory()); for (File folder : folders) { File tmpRootFolder = new File(folder, "rhodownload"); File tmpFolder = new File(tmpRootFolder, ctx.getPackageName()); if (tmpFolder.exists()) deleteFilesInFolder(tmpFolder.getAbsolutePath()); else tmpFolder.mkdirs(); File of = new File(tmpFolder, UUID.randomUUID().toString() + ".apk"); Logger.D(TAG, "Check path " + of.getAbsolutePath() + "..."); try { os = new FileOutputStream(of); } catch (FileNotFoundException e) { Logger.D(TAG, "Can't open file " + of.getAbsolutePath() + ", check next path"); continue; } Logger.D(TAG, "File " + of.getAbsolutePath() + " succesfully opened for write, start download app"); tmpFile = of; break; } */ tmpFile = ctx.getFileStreamPath(UUID.randomUUID().toString() + ".apk"); os = ctx.openFileOutput(tmpFile.getName(), Context.MODE_WORLD_READABLE); Logger.D(TAG, "Download " + url + " to " + tmpFile.getAbsolutePath() + "..."); URL u = new URL(url); URLConnection conn = u.openConnection(); int totalBytes = -1; if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; totalBytes = httpConn.getContentLength(); } is = conn.getInputStream(); int downloaded = 0; updateDownloadNotification(url, totalBytes, downloaded); long prevProgress = 0; byte[] buf = new byte[65536]; for (;;) { if (thisThread.isInterrupted()) { tmpFile.delete(); Logger.D(TAG, "Download of " + url + " was canceled"); return null; } int nread = is.read(buf); if (nread == -1) break; //Logger.D(TAG, "Downloading " + url + ": got " + nread + " bytes..."); os.write(buf, 0, nread); downloaded += nread; if (totalBytes > 0) { // Update progress view only if current progress is greater than // previous by more than 10%. Otherwise, if update it very frequently, // user will no have chance to click on notification view and cancel if need long progress = downloaded * 10 / totalBytes; if (progress > prevProgress) { updateDownloadNotification(url, totalBytes, downloaded); prevProgress = progress; } } } Logger.D(TAG, "File stored to " + tmpFile.getAbsolutePath()); return tmpFile; } catch (IOException e) { if (tmpFile != null) tmpFile.delete(); throw e; } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (os != null) os.close(); } catch (IOException e) { } mNM.cancel(DOWNLOAD_PACKAGE_ID); ctx.unregisterReceiver(downloadReceiver); } }