List of usage examples for java.util.concurrent FutureTask get
public V get() throws InterruptedException, ExecutionException
From source file:org.springframework.batch.core.scope.AsyncJobScopeIntegrationTests.java
@Test public void testGetSameInMultipleThreads() throws Exception { List<FutureTask<String>> tasks = new ArrayList<FutureTask<String>>(); final JobExecution jobExecution = new JobExecution(11L); ExecutionContext executionContext = jobExecution.getExecutionContext(); executionContext.put("foo", "foo"); JobSynchronizationManager.register(jobExecution); assertEquals("foo", simple.getName()); for (int i = 0; i < 12; i++) { final String value = "foo" + i; FutureTask<String> task = new FutureTask<String>(new Callable<String>() { @Override/*from ww w . j a va 2 s .com*/ public String call() throws Exception { ExecutionContext executionContext = jobExecution.getExecutionContext(); executionContext.put("foo", value); JobContext context = JobSynchronizationManager.register(jobExecution); logger.debug("Registered: " + context.getJobExecutionContext()); try { return simple.getName(); } finally { JobSynchronizationManager.close(); } } }); tasks.add(task); taskExecutor.execute(task); } for (FutureTask<String> task : tasks) { assertEquals("foo", task.get()); } // Don't close the outer scope until all tasks are finished. This should // always be the case if using an AbstractJob JobSynchronizationManager.close(); }
From source file:org.springframework.batch.core.scope.AsyncStepScopeIntegrationTests.java
@Test public void testGetSameInMultipleThreads() throws Exception { List<FutureTask<String>> tasks = new ArrayList<FutureTask<String>>(); final StepExecution stepExecution = new StepExecution("foo", new JobExecution(0L), 123L); ExecutionContext executionContext = stepExecution.getExecutionContext(); executionContext.put("foo", "foo"); StepSynchronizationManager.register(stepExecution); assertEquals("foo", simple.getName()); for (int i = 0; i < 12; i++) { final String value = "foo" + i; FutureTask<String> task = new FutureTask<String>(new Callable<String>() { @Override//w w w . j av a 2 s.c o m public String call() throws Exception { ExecutionContext executionContext = stepExecution.getExecutionContext(); executionContext.put("foo", value); StepContext context = StepSynchronizationManager.register(stepExecution); logger.debug("Registered: " + context.getStepExecutionContext()); try { return simple.getName(); } finally { StepSynchronizationManager.close(); } } }); tasks.add(task); taskExecutor.execute(task); } for (FutureTask<String> task : tasks) { assertEquals("foo", task.get()); } // Don't close the outer scope until all tasks are finished. This should // always be the case if using an AbstractStep StepSynchronizationManager.close(); }
From source file:com.alibaba.napoli.metamorphosis.client.consumer.ConsumerZooKeeper.java
ZKLoadRebalanceListener getBrokerConnectionListener(final FetchManager fetchManager) { final FutureTask<ZKLoadRebalanceListener> task = this.consumerLoadBalanceListeners.get(fetchManager); if (task != null) { try {/* w w w .j ava 2 s .c om*/ return task.get(); } catch (final Exception e) { log.error("?ZKLoadRebalanceListener", e); return null; } } else { return null; } }
From source file:com.alibaba.napoli.metamorphosis.client.consumer.ConsumerZooKeeper.java
@Override public void onZkClientChanged(final ZkClient newClient) { this.zkClient = newClient; // ?consumer//from w w w . ja va 2s . c om for (final FutureTask<ZKLoadRebalanceListener> task : this.consumerLoadBalanceListeners.values()) { try { final ZKLoadRebalanceListener listener = task.get(); // ??consumer??offsetoffset listener.topicRegistry.clear(); log.info("re-register consumer to zk,group=" + listener.consumerConfig.getGroup()); this.registerConsumerInternal(listener); } catch (final Exception e) { log.error("reRegister consumer failed", e); } } }
From source file:org.springframework.batch.core.scope.AsyncJobScopeIntegrationTests.java
@Test public void testGetMultipleInMultipleThreads() throws Exception { List<FutureTask<String>> tasks = new ArrayList<FutureTask<String>>(); for (int i = 0; i < 12; i++) { final String value = "foo" + i; final Long id = 123L + i; FutureTask<String> task = new FutureTask<String>(new Callable<String>() { @Override/*from w w w . j a v a2 s. com*/ public String call() throws Exception { JobExecution jobExecution = new JobExecution(id); ExecutionContext executionContext = jobExecution.getExecutionContext(); executionContext.put("foo", value); JobContext context = JobSynchronizationManager.register(jobExecution); logger.debug("Registered: " + context.getJobExecutionContext()); try { return simple.getName(); } finally { JobSynchronizationManager.close(); } } }); tasks.add(task); taskExecutor.execute(task); } int i = 0; for (FutureTask<String> task : tasks) { assertEquals("foo" + i, task.get()); i++; } }
From source file:com.alibaba.napoli.metamorphosis.client.consumer.ConsumerZooKeeper.java
/** * ?consumer/*from w w w. j av a 2 s . c o m*/ * * @param fetchManager */ public void unRegisterConsumer(final FetchManager fetchManager) { try { final FutureTask<ZKLoadRebalanceListener> futureTask = this.consumerLoadBalanceListeners .remove(fetchManager); if (futureTask != null) { final ZKLoadRebalanceListener listener = futureTask.get(); if (listener != null) { // ??offsets listener.commitOffsets(); this.zkClient.unsubscribeStateChanges(new ZKSessionExpireListenner(listener)); final ZKGroupDirs dirs = this.metaZookeeper.new ZKGroupDirs(listener.consumerConfig.getGroup()); this.zkClient.unsubscribeChildChanges(dirs.consumerRegistryDir, listener); log.info("unsubscribeChildChanges:" + dirs.consumerRegistryDir); // topic? for (final String topic : listener.topicSubcriberRegistry.keySet()) { final String partitionPath = this.metaZookeeper.brokerTopicsPath + "/" + topic; this.zkClient.unsubscribeChildChanges(partitionPath, listener); log.info("unsubscribeChildChanges:" + partitionPath); } // ownership listener.releaseAllPartitionOwnership(); // ZkUtils.deletePath(this.zkClient, listener.dirs.consumerRegistryDir + "/" + listener.consumerIdString); } } } catch (final InterruptedException e) { Thread.interrupted(); log.error("Interrupted when unRegisterConsumer", e); } catch (final Exception e) { log.error("Error in unRegisterConsumer,maybe error when registerConsumer", e); } }
From source file:plugin.chartboost.hasCachedMoreApps.java
/** * This method is called when the Lua function is called. * <p>//from w ww . ja v a2 s.c o m * Warning! This method is not called on the main UI thread. * @param luaState Reference to the Lua state. * Needed to retrieve the Lua function's parameters and to return values back to Lua. * @return Returns the number of values to be returned by the Lua function. */ @Override public int invoke(LuaState luaState) { try { // Corona Activity CoronaActivity coronaActivity = null; if (CoronaEnvironment.getCoronaActivity() != null) { coronaActivity = CoronaEnvironment.getCoronaActivity(); } // The lua state final LuaState L = luaState; // See if the more apps page is cached FutureTask<Boolean> isCachedResult = new FutureTask<Boolean>(new Callable<Boolean>() { @Override public Boolean call() throws Exception { // Is more apps cached? boolean result = false; // If the chartboost instance is valid - could be invalid by calling this method before init invokes if (chartboostHelper.chartboostInstance != null) { result = chartboostHelper.chartboostInstance.hasCachedMoreApps(); } // Push the result L.pushBoolean(result); // Return the result return result; } }); // Run the activity on the uiThread if (coronaActivity != null) { coronaActivity.runOnUiThread(isCachedResult); // Get the value of isCached boolean returnValue = isCachedResult.get(); } } catch (Exception ex) { // An exception will occur if given an invalid argument or no argument. Print the error. ex.printStackTrace(); } return 1; }
From source file:org.springframework.batch.core.scope.AsyncStepScopeIntegrationTests.java
@Test public void testGetMultipleInMultipleThreads() throws Exception { List<FutureTask<String>> tasks = new ArrayList<FutureTask<String>>(); for (int i = 0; i < 12; i++) { final String value = "foo" + i; final Long id = 123L + i; FutureTask<String> task = new FutureTask<String>(new Callable<String>() { @Override//from w ww . ja v a 2s. c om public String call() throws Exception { StepExecution stepExecution = new StepExecution(value, new JobExecution(0L), id); ExecutionContext executionContext = stepExecution.getExecutionContext(); executionContext.put("foo", value); StepContext context = StepSynchronizationManager.register(stepExecution); logger.debug("Registered: " + context.getStepExecutionContext()); try { return simple.getName(); } finally { StepSynchronizationManager.close(); } } }); tasks.add(task); taskExecutor.execute(task); } int i = 0; for (FutureTask<String> task : tasks) { assertEquals("foo" + i, task.get()); i++; } }
From source file:org.springframework.batch.core.step.tasklet.SystemCommandTasklet.java
/** * Execute system command and map its exit code to {@link ExitStatus} using * {@link SystemProcessExitCodeMapper}./*w ww .ja v a 2 s.c o m*/ */ @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { FutureTask<Integer> systemCommandTask = new FutureTask<Integer>(new Callable<Integer>() { @Override public Integer call() throws Exception { Process process = Runtime.getRuntime().exec(command, environmentParams, workingDirectory); return process.waitFor(); } }); long t0 = System.currentTimeMillis(); taskExecutor.execute(systemCommandTask); while (true) { Thread.sleep(checkInterval);//moved to the end of the logic if (stoppable) { JobExecution jobExecution = jobExplorer .getJobExecution(chunkContext.getStepContext().getStepExecution().getJobExecutionId()); if (jobExecution.isStopping()) { stopped = true; } } if (systemCommandTask.isDone()) { contribution.setExitStatus(systemProcessExitCodeMapper.getExitStatus(systemCommandTask.get())); return RepeatStatus.FINISHED; } else if (System.currentTimeMillis() - t0 > timeout) { systemCommandTask.cancel(interruptOnCancel); throw new SystemCommandException("Execution of system command did not finish within the timeout"); } else if (execution.isTerminateOnly()) { systemCommandTask.cancel(interruptOnCancel); throw new JobInterruptedException( "Job interrupted while executing system command '" + command + "'"); } else if (stopped) { systemCommandTask.cancel(interruptOnCancel); contribution.setExitStatus(ExitStatus.STOPPED); return RepeatStatus.FINISHED; } } }
From source file:ubic.basecode.math.linalg.SingularValueDecomposition.java
/** * @param dm// ww w . j ava 2 s.c o m */ private void computeSVD(final DoubleMatrix2D dm) { /* * This fails to converge some times, we have to bail. */ FutureTask<cern.colt.matrix.linalg.SingularValueDecomposition> svdFuture = new FutureTask<>( new Callable<cern.colt.matrix.linalg.SingularValueDecomposition>() { @Override public cern.colt.matrix.linalg.SingularValueDecomposition call() { return new cern.colt.matrix.linalg.SingularValueDecomposition(dm); } }); StopWatch timer = new StopWatch(); timer.start(); Executors.newSingleThreadExecutor().execute(svdFuture); while (!svdFuture.isDone() && !svdFuture.isCancelled()) { try { Thread.sleep(100); } catch (InterruptedException ie) { throw new RuntimeException("SVD cancelled"); } if (timer.getTime() > MAX_COMPUTE_TIME) { svdFuture.cancel(true); throw new RuntimeException("SVD failed to converge within " + MAX_COMPUTE_TIME + "ms, bailing"); } } timer.stop(); try { this.svd = svdFuture.get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } assert this.svd != null; }