List of usage examples for java.util.concurrent Future isDone
boolean isDone();
From source file:de.javakaffee.web.msm.integration.NonStickySessionsIntegrationTest.java
/** * Tests that for auto locking mode requests that are found to be readonly don't lock * the session//from w w w . j a va2 s .c om */ @Test public void testReadOnlyRequestsDontLockSessionForAutoLocking() throws IOException, InterruptedException, HttpException, ExecutionException { setLockingMode(LockingMode.AUTO, null); final String key1 = "k1"; final String value1 = "v1"; final String sessionId = post(_httpClient, TC_PORT_1, null, key1, value1).getSessionId(); assertNotNull(sessionId); // perform a readonly request without waiting, we perform this one later again final String path = "/mypath"; final Map<String, String> params = asMap("foo", "bar"); final Response response0 = get(_httpClient, TC_PORT_1, path, sessionId, params); assertEquals(response0.getSessionId(), sessionId); // perform a readonly, waiting request that we can perform again later final long timeToWaitInMillis = 500; final Map<String, String> paramsWait = asMap(PARAM_MILLIS, String.valueOf(timeToWaitInMillis)); final Response response1 = get(_httpClient, TC_PORT_1, PATH_WAIT, sessionId, paramsWait); assertEquals(response1.getSessionId(), sessionId); // now do it again, now in the background, and in parallel start another readonly request, // both should not block each other final long start = System.currentTimeMillis(); final Future<Response> response2 = _executor.submit(new Callable<Response>() { @Override public Response call() throws Exception { return get(_httpClient, TC_PORT_1, PATH_WAIT, sessionId, paramsWait); } }); final Future<Response> response3 = _executor.submit(new Callable<Response>() { @Override public Response call() throws Exception { return get(_httpClient, TC_PORT_1, PATH_WAIT, sessionId, paramsWait); } }); response2.get(); response3.get(); assertTrue((System.currentTimeMillis() - start) < (2 * timeToWaitInMillis), "The time for both requests should be less than 2 * the wait time if they don't block each other."); assertEquals(response2.get().getSessionId(), sessionId); assertEquals(response3.get().getSessionId(), sessionId); // now perform a modifying request and a readonly in parallel which should not be blocked final Future<Response> response4 = _executor.submit(new Callable<Response>() { @Override public Response call() throws Exception { return post(_httpClient, TC_PORT_1, PATH_WAIT, sessionId, asMap(PARAM_MILLIS, "500", "foo", "bar")); } }); Thread.sleep(50); final Response response5 = get(_httpClient, TC_PORT_1, path, sessionId, params); assertEquals(response5.getSessionId(), sessionId); assertFalse(response4.isDone(), "The readonly request should return before the long, session locking one"); assertEquals(response4.get().getSessionId(), sessionId); }
From source file:org.apache.gobblin.scheduler.JobScheduler.java
/** * Schedule a job immediately./*from ww w .j a v a2 s. c o m*/ * * <p> * This method calls the Quartz scheduler to scheduler the job. * </p> * * @param jobProps Job configuration properties * @param jobListener {@link JobListener} used for callback, * can be <em>null</em> if no callback is needed. * @throws JobException when there is anything wrong * with scheduling the job */ public Future<?> scheduleJobImmediately(Properties jobProps, JobListener jobListener, JobLauncher jobLauncher) { Callable<Void> callable = new Callable<Void>() { @Override public Void call() throws JobException { try { runJob(jobProps, jobListener, jobLauncher); } catch (JobException je) { LOG.error("Failed to run job " + jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY), je); throw je; } return null; } }; final Future<?> future = this.jobExecutor.submit(callable); return new Future() { @Override public boolean cancel(boolean mayInterruptIfRunning) { if (!cancelRequested) { return false; } boolean result = true; try { jobLauncher.cancelJob(jobListener); } catch (JobException e) { LOG.error("Failed to cancel job " + jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY), e); result = false; } if (mayInterruptIfRunning) { result &= future.cancel(true); } return result; } @Override public boolean isCancelled() { return future.isCancelled(); } @Override public boolean isDone() { return future.isDone(); } @Override public Object get() throws InterruptedException, ExecutionException { return future.get(); } @Override public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return future.get(timeout, unit); } }; }
From source file:com.mobilyzer.MeasurementScheduler.java
private void uploadResults() { Vector<MeasurementResult> finishedTasks = new Vector<MeasurementResult>(); MeasurementResult[] results;/* ww w. j a va 2 s . co m*/ Future<MeasurementResult[]> future; Logger.d("pendingTasks: " + pendingTasks.size()); synchronized (this.pendingTasks) { try { for (MeasurementTask task : this.pendingTasks.keySet()) { future = this.pendingTasks.get(task); if (future != null) { if (future.isDone()) { this.pendingTasks.remove(task); if (future.isCancelled()) { Logger.e("Task execution was canceled"); results = MeasurementResult.getFailureResult(task, new CancellationException("Task cancelled")); for (MeasurementResult r : results) { finishedTasks.add(r); } } } } } } catch (ConcurrentModificationException e) { /* * keySet is a synchronized view of the keys. However, changes during iteration will throw * ConcurrentModificationException. Since we have synchronized all changes to pendingTasks * this should not happen. */ Logger.e("Pending tasks is changed during measurement upload"); } } Logger.i("A total of " + finishedTasks.size() + " from pendingTasks is uploaded"); Logger.i("A total of " + this.pendingTasks.size() + " is in pendingTasks"); try { for (MeasurementResult r : finishedTasks) { r.getMeasurementDesc().parameters = null; } this.checkin.uploadMeasurementResult(finishedTasks, resourceCapManager); } catch (IOException e) { Logger.e("Error when uploading message"); } }
From source file:org.openconcerto.sql.PropsConfiguration.java
public PropsConfiguration(final Properties props) { this.props = props; // ShowAs is thread-safe this.showAs = new Addable<ShowAs>() { @GuardedBy("this") private DirectoryListener directoryListener; @Override//from w w w.jav a 2 s . com protected ShowAs create() { final ShowAs res = createShowAs(); final SQLElementDirectory dir = getDirectory(); synchronized (this) { assert this.directoryListener == null; this.directoryListener = new DirectoryListener() { @Override public void elementRemoved(final SQLElement elem) { res.removeTable(elem.getTable()); } @Override public void elementAdded(final SQLElement elem) { final CollectionMap<String, String> sa = elem.getShowAs(); if (sa != null) { for (final Entry<String, Collection<String>> e : sa.entrySet()) { try { if (e.getKey() == null) res.show(elem.getTable(), (List<String>) e.getValue()); else res.show(elem.getTable().getField(e.getKey()), (List<String>) e.getValue()); } catch (RuntimeException exn) { throw new IllegalStateException( "Couldn't add showAs for " + elem + " : " + e, exn); } } } } }; // ATTN SQLElementDirectory cannot access ShowAs otherwise deadlock synchronized (dir) { for (final SQLElement elem : dir.getElements()) { this.directoryListener.elementAdded(elem); } dir.addListener(this.directoryListener); } } return res; } @Override protected void destroy(Future<ShowAs> future) { // don't cancel future, just wait it out. Prevent other callers from getting an // exception. try { future.get(); } catch (Exception e) { // don't care about the result, we just want it to finish } assert future.isDone(); final DirectoryListener l; synchronized (this) { l = this.directoryListener; } // create() might have thrown an exception before completing if (l != null) { getDirectory().removeListener(l); } super.destroy(future); } @Override protected void add(ShowAs obj, Configuration conf) { obj.putAll(conf.getShowAs()); } }; // SQLElementDirectory is thread-safe this.directory = new Addable<SQLElementDirectory>() { @Override protected SQLElementDirectory create() { return createDirectory(); } @Override protected void add(SQLElementDirectory obj, Configuration conf) { obj.putAll(conf.getDirectory()); } }; // SQLFieldTranslator is thread-safe this.translator = new Addable<SQLFieldTranslator>() { @Override protected SQLFieldTranslator create() { return createTranslator(); } @Override protected void add(SQLFieldTranslator obj, Configuration conf) { obj.putAll(conf.getTranslator()); } }; this.setUp(); }
From source file:com.imaginary.home.controller.HomeController.java
private void processCommands() { synchronized (commandQueue) { running = true;/*from ww w. java2 s . c o m*/ } while (true) { synchronized (commandQueue) { if (!running) { return; } } CommandList cmdList; do { synchronized (commandQueue) { if (!commandQueue.isEmpty()) { cmdList = commandQueue.poll(); } else { cmdList = null; } } if (cmdList != null) { CloudService service = getService(cmdList.getServiceId()); if (service == null) { continue; } ArrayList<Future<Boolean>> results = new ArrayList<Future<Boolean>>(); boolean[] completions = new boolean[results.size()]; for (JSONObject cmd : cmdList) { try { Command c = new Command(cmd); results.add(c.start()); } catch (JSONException e) { results.add(null); } } boolean done; do { done = true; for (int i = 0; i < completions.length; i++) { if (!completions[i]) { Future<Boolean> f = results.get(i); JSONObject cmd = cmdList.get(i); if (f == null) { try { service.postResult(cmd.getString("id"), false, new JSONException("Invalid JSON in command")); } catch (Throwable t) { t.printStackTrace(); } finally { completions[i] = true; } } else if (f.isDone()) { Throwable failure = null; boolean result = false; try { result = f.get(); } catch (Throwable t) { failure = t; } try { service.postResult(cmd.getString("id"), result, failure); } catch (Throwable t) { t.printStackTrace(); } finally { completions[i] = true; } } else { done = false; } } } } while (!done); } } while (cmdList != null); synchronized (commandQueue) { try { commandQueue.wait(30000L); } catch (InterruptedException ignore) { } } } }
From source file:com.hygenics.parser.GetImages.java
private void getImages() { // controls the web process from a removed method log.info("Setting Up Pull"); String[] proxyarr = (proxies == null) ? null : proxies.split(","); // cleanup/*from www . j a v a2 s.c om*/ if (cleanup) { cleanupDir(fpath); } // image grab CookieManager cm = new CookieManager(); cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL); CookieHandler.setDefault(cm); int numimages = 0; InputStream is; byte[] bytes; int iter = 0; int found = 0; // set proxy if needed if (proxyuser != null) { proxy(proxyhost, proxyport, https, proxyuser, proxypass); } int i = 0; ArrayList<String> postImages = new ArrayList<String>(); ForkJoinPool fjp = new ForkJoinPool(Runtime.getRuntime().availableProcessors()); Set<Callable<String>> pulls = new HashSet<Callable<String>>(); Set<Callable<ArrayList<String>>> sqls = new HashSet<Callable<ArrayList<String>>>(); List<Future<String>> imageFutures; ArrayList<String> images; int chunksize = (int) Math.ceil(commitsize / numqueries); log.info("Chunksize: " + chunksize); if (baseurl != null || baseurlcolumn != null) { do { log.info("Offset: " + offset); log.info("Getting Images"); images = new ArrayList<String>(commitsize); log.info("Getting Columns"); for (int n = 0; n < numqueries; n++) { String tempsql = sql + " WHERE " + idString + " >= " + offset + " AND " + idString + " < " + (offset + chunksize); if (conditions != null) { tempsql += conditions; } sqls.add(new QueryDatabase( ((extracondition != null) ? tempsql + " " + extracondition : tempsql))); offset += chunksize; } List<Future<ArrayList<String>>> futures = fjp.invokeAll(sqls); int w = 0; while (fjp.isQuiescent() && fjp.getActiveThreadCount() > 0) { w++; } for (Future<ArrayList<String>> f : futures) { try { ArrayList<String> fjson; fjson = f.get(); if (fjson.size() > 0) { images.addAll(fjson); } if (f.isDone() == false) { f.cancel(true); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } log.info(Integer.toString(images.size()) + " image links found. Pulling."); ArrayList<String> tempproxies = new ArrayList<String>(); if (proxyarr != null) { for (String proxy : proxyarr) { tempproxies.add(proxy.trim()); } } if (maxproxies > 0) { maxproxies -= 1;// 0 and 1 should be equivalent conditions // --num is not like most 0 based still due // to >= } // get images for (int num = 0; num < images.size(); num++) { String icols = images.get(num); int proxnum = (int) Math.random() * (tempproxies.size() - 1); String proxy = (tempproxies.size() == 0) ? null : tempproxies.get(proxnum); // add grab pulls.add(new ImageGrabber(icols, proxy)); if (proxy != null) { tempproxies.remove(proxy); } // check for execution if (num + 1 == images.size() || pulls.size() >= commitsize || tempproxies.size() == 0) { if (tempproxies.size() == 0 && proxies != null) { tempproxies = new ArrayList<String>(proxyarr.length); for (String p : proxyarr) { tempproxies.add(p.trim()); } } imageFutures = fjp.invokeAll(pulls); w = 0; while (fjp.isQuiescent() == false && fjp.getActiveThreadCount() > 0) { w++; } for (Future<String> f : imageFutures) { String add; try { add = f.get(); if (add != null) { postImages.add(add); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } imageFutures = null;// garbage collect elligible pulls = new HashSet<Callable<String>>(commitsize); } if (postImages.size() >= commitsize && addtoDB == true) { if (addtoDB) { log.info("Posting to Database"); log.info("Found " + postImages.size() + " images"); numimages += postImages.size(); int size = (int) Math.floor(postImages.size() / numqueries); for (int n = 0; n < numqueries; n++) { if (((n + 1) * size) < postImages.size() && (n + 1) < numqueries) { fjp.execute(new ImagePost(postImages.subList(n * size, (n + 1) * size))); } else { fjp.execute(new ImagePost(postImages.subList(n * size, postImages.size() - 1))); } } w = 0; while (fjp.isQuiescent() && fjp.getActiveThreadCount() > 0) { w++; } } found += postImages.size(); postImages.clear(); } } if (postImages.size() > 0 && addtoDB == true) { log.info("Posting to Database"); numimages += postImages.size(); int size = (int) Math.floor(postImages.size() / numqueries); for (int n = 0; n < numqueries; n++) { if (((n + 1) * size) < postImages.size()) { fjp.execute(new ImagePost(postImages.subList(n * size, (n + 1) * size))); } else { fjp.execute(new ImagePost(postImages.subList(n * size, postImages.size()))); } } w = 0; while (fjp.isQuiescent() && fjp.getActiveThreadCount() > 0) { w++; } found += postImages.size(); postImages.clear(); } // handle iterations specs iter += 1; log.info("Iteration: " + iter); if ((iter < iterations && found < images.size()) || tillfound == true) { log.info("Not All Images Obtained Trying Iteration " + iter + " of " + iterations); offset -= commitsize; } else if ((iter < iterations && found >= images.size()) && tillfound == false) { log.info("Images Obtained in " + iter + " iterations. Continuing."); iter = 0; } else { // precautionary log.info("Images Obtained in " + iter + " iterations. Continuing"); iter = 0; } } while (images.size() > 0 && iter < iterations); if (fjp.isShutdown()) { fjp.shutdownNow(); } } log.info("Complete. Check for Errors \n " + numimages + " Images Found"); }
From source file:com.imaginary.home.controller.HomeController.java
private void checkScheduler() { while (true) { synchronized (commandQueue) { if (!running) { return; }//w ww . j av a 2 s . com } ScheduledCommandList cmdList; do { synchronized (commandQueue) { if (!scheduler.isEmpty()) { cmdList = scheduler.iterator().next(); scheduler.remove(cmdList); try { saveSchedule(); } catch (Throwable t) { t.printStackTrace(); } } else { cmdList = null; } } if (cmdList != null && cmdList.getExecuteAfter() <= System.currentTimeMillis()) { ArrayList<Future<Boolean>> results = new ArrayList<Future<Boolean>>(); boolean[] completions = new boolean[results.size()]; CloudService service = getService(cmdList.getServiceId()); if (service == null) { continue; } for (JSONObject cmd : cmdList) { try { Command c = new Command(cmd); results.add(c.start()); } catch (JSONException e) { results.add(null); } } boolean done; do { done = true; for (int i = 0; i < completions.length; i++) { if (!completions[i]) { Future<Boolean> f = results.get(i); JSONObject cmd = cmdList.get(i); if (f == null) { try { service.postResult(cmd.getString("id"), false, new JSONException("Invalid JSON in command")); } catch (Throwable t) { t.printStackTrace(); } finally { completions[i] = true; } } if (f.isDone()) { Throwable failure = null; boolean result = false; try { result = f.get(); } catch (Throwable t) { failure = t; } try { service.postResult(cmd.getString("id"), result, failure); } catch (Throwable t) { t.printStackTrace(); } finally { completions[i] = true; } } else { done = false; } } } } while (!done); } } while (cmdList != null); synchronized (commandQueue) { try { commandQueue.wait(60000L); } catch (InterruptedException ignore) { } } } }
From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessMutexBase.java
@Test public void test2Clients() throws Exception { CuratorFramework client1 = null;/*w ww . ja va 2 s . c o m*/ CuratorFramework client2 = null; try { client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client1.start(); client2.start(); final InterProcessLock mutexForClient1 = makeLock(client1); final InterProcessLock mutexForClient2 = makeLock(client2); final CountDownLatch latchForClient1 = new CountDownLatch(1); final CountDownLatch latchForClient2 = new CountDownLatch(1); final CountDownLatch acquiredLatchForClient1 = new CountDownLatch(1); final CountDownLatch acquiredLatchForClient2 = new CountDownLatch(1); final AtomicReference<Exception> exceptionRef = new AtomicReference<Exception>(); ExecutorService service = Executors.newCachedThreadPool(); Future<Object> future1 = service.submit(new Callable<Object>() { @Override public Object call() throws Exception { try { mutexForClient1.acquire(10, TimeUnit.SECONDS); acquiredLatchForClient1.countDown(); latchForClient1.await(10, TimeUnit.SECONDS); mutexForClient1.release(); } catch (Exception e) { exceptionRef.set(e); } return null; } }); Future<Object> future2 = service.submit(new Callable<Object>() { @Override public Object call() throws Exception { try { mutexForClient2.acquire(10, TimeUnit.SECONDS); acquiredLatchForClient2.countDown(); latchForClient2.await(10, TimeUnit.SECONDS); mutexForClient2.release(); } catch (Exception e) { exceptionRef.set(e); } return null; } }); while (!mutexForClient1.isAcquiredInThisProcess() && !mutexForClient2.isAcquiredInThisProcess()) { Thread.sleep(1000); Assert.assertFalse(future1.isDone() && future2.isDone()); } Assert.assertTrue( mutexForClient1.isAcquiredInThisProcess() != mutexForClient2.isAcquiredInThisProcess()); Thread.sleep(1000); Assert.assertTrue( mutexForClient1.isAcquiredInThisProcess() || mutexForClient2.isAcquiredInThisProcess()); Assert.assertTrue( mutexForClient1.isAcquiredInThisProcess() != mutexForClient2.isAcquiredInThisProcess()); Exception exception = exceptionRef.get(); if (exception != null) { throw exception; } if (mutexForClient1.isAcquiredInThisProcess()) { latchForClient1.countDown(); Assert.assertTrue(acquiredLatchForClient2.await(10, TimeUnit.SECONDS)); Assert.assertTrue(mutexForClient2.isAcquiredInThisProcess()); } else { latchForClient2.countDown(); Assert.assertTrue(acquiredLatchForClient1.await(10, TimeUnit.SECONDS)); Assert.assertTrue(mutexForClient1.isAcquiredInThisProcess()); } } finally { IOUtils.closeQuietly(client1); IOUtils.closeQuietly(client2); } }
From source file:org.elasticsearch.client.sniff.SnifferTests.java
/** * Test multiple sniffing rounds by mocking the {@link Scheduler} as well as the {@link HostsSniffer}. * Simulates the ordinary behaviour of {@link Sniffer} when sniffing on failure is not enabled. * The {@link CountingHostsSniffer} doesn't make any network connection but may throw exception or return no hosts, which makes * it possible to verify that errors are properly handled and don't affect subsequent runs and their scheduling. * The {@link Scheduler} implementation submits rather than scheduling tasks, meaning that it doesn't respect the requested sniff * delays while allowing to assert that the requested delays for each requested run and the following one are the expected values. *//* w ww . j av a 2 s . c om*/ public void testOrdinarySniffRounds() throws Exception { final long sniffInterval = randomLongBetween(1, Long.MAX_VALUE); long sniffAfterFailureDelay = randomLongBetween(1, Long.MAX_VALUE); RestClient restClient = mock(RestClient.class); CountingHostsSniffer hostsSniffer = new CountingHostsSniffer(); final int iters = randomIntBetween(30, 100); final Set<Future<?>> futures = new CopyOnWriteArraySet<>(); final CountDownLatch completionLatch = new CountDownLatch(1); final AtomicInteger runs = new AtomicInteger(iters); final ExecutorService executor = Executors.newSingleThreadExecutor(); final AtomicReference<Future<?>> lastFuture = new AtomicReference<>(); final AtomicReference<Sniffer.Task> lastTask = new AtomicReference<>(); Scheduler scheduler = new Scheduler() { @Override public Future<?> schedule(Sniffer.Task task, long delayMillis) { assertEquals(sniffInterval, task.nextTaskDelay); int numberOfRuns = runs.getAndDecrement(); if (numberOfRuns == iters) { //the first call is to schedule the first sniff round from the Sniffer constructor, with delay O assertEquals(0L, delayMillis); assertEquals(sniffInterval, task.nextTaskDelay); } else { //all of the subsequent times "schedule" is called with delay set to the configured sniff interval assertEquals(sniffInterval, delayMillis); assertEquals(sniffInterval, task.nextTaskDelay); if (numberOfRuns == 0) { completionLatch.countDown(); return null; } } //we submit rather than scheduling to make the test quick and not depend on time Future<?> future = executor.submit(task); futures.add(future); if (numberOfRuns == 1) { lastFuture.set(future); lastTask.set(task); } return future; } @Override public void shutdown() { //the executor is closed externally, shutdown is tested separately } }; try { new Sniffer(restClient, hostsSniffer, scheduler, sniffInterval, sniffAfterFailureDelay); assertTrue("timeout waiting for sniffing rounds to be completed", completionLatch.await(1000, TimeUnit.MILLISECONDS)); assertEquals(iters, futures.size()); //the last future is the only one that may not be completed yet, as the count down happens //while scheduling the next round which is still part of the execution of the runnable itself. assertTrue(lastTask.get().hasStarted()); lastFuture.get().get(); for (Future<?> future : futures) { assertTrue(future.isDone()); future.get(); } } finally { executor.shutdown(); assertTrue(executor.awaitTermination(1000, TimeUnit.MILLISECONDS)); } int totalRuns = hostsSniffer.runs.get(); assertEquals(iters, totalRuns); int setHostsRuns = totalRuns - hostsSniffer.failures.get() - hostsSniffer.emptyList.get(); verify(restClient, times(setHostsRuns)).setHosts(Matchers.<HttpHost>anyVararg()); verifyNoMoreInteractions(restClient); }
From source file:com.mobiperf.MeasurementScheduler.java
@SuppressWarnings("unchecked") private void uploadResults() { MeasurementResult result;/*from ww w .j a v a2s . co m*/ Future<MeasurementResult> future; JSONArray results = readResultsFromFile(); synchronized (this.pendingTasks) { try { for (MeasurementTask task : this.pendingTasks.keySet()) { future = this.pendingTasks.get(task); if (future != null) { sendStringMsg("Finished:\n" + task); if (future.isDone()) { try { this.pendingTasks.remove(task); if (!future.isCancelled()) { result = future.get(); } else { Logger.e("Task execution was canceled"); JSONObject cancelledResult = MeasurementJsonConvertor.encodeToJson(this .getFailureResult(task, new CancellationException("Task cancelled"))); results.put(cancelledResult); } } catch (InterruptedException e) { Logger.e("Task execution interrupted", e); } catch (ExecutionException e) { if (e.getCause() instanceof MeasurementSkippedException) { // Don't do anything with this - no need to report skipped measurements sendStringMsg("Task skipped - " + e.getCause().toString() + "\n" + task); Logger.i("Task skipped", e.getCause()); } else { // Log the error sendStringMsg("Task failed - " + e.getCause().toString() + "\n" + task); Logger.e("Task execution failed", e.getCause()); // Was already sent // finishedTasks.add(this.getFailureResult(task, e.getCause())); } } catch (CancellationException e) { Logger.e("Task cancelled", e); } } else if (task.isPassedDeadline()) { /* * If a task has reached its deadline but has not been run, remove it and report * failure */ this.pendingTasks.remove(task); future.cancel(true); JSONObject cancelledResult = MeasurementJsonConvertor .encodeToJson(this.getFailureResult(task, new RuntimeException("Deadline passed before execution"))); results.put(cancelledResult); } } if (future == null) { /* * Tasks that are scheduled after deadline are put into pendingTasks with a null future. */ this.pendingTasks.remove(task); JSONObject cancelledResult = MeasurementJsonConvertor.encodeToJson( this.getFailureResult(task, new RuntimeException("Task scheduled after deadline"))); results.put(cancelledResult); } } } catch (ConcurrentModificationException e) { /* * keySet is a synchronized view of the keys. However, changes during iteration will throw * ConcurrentModificationException. Since we have synchronized all changes to pendingTasks * this should not happen. */ Logger.e("Pending tasks is changed during measurement upload"); } catch (JSONException e) { e.printStackTrace(); } } if (results.length() > 0) { try { this.checkin.uploadMeasurementResult(results, resourceCapManager); } catch (IOException e) { Logger.e("Error when uploading message"); } } Logger.i("A total of " + results.length() + " uploaded"); Logger.i("A total of " + results.length() + " is in the results list"); }