Java Code Examples for java.util.concurrent.Future

The following are top voted examples for showing how to use java.util.concurrent.Future. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: com.zsmartsystems.zigbee   File: ConBeeFrameHandler.java   Source Code and License 7 votes vote down vote up
/**
 * Sends a ConBee request to the NCP and waits for the response. The response is correlated with the request and the
 * returned {@link ConBeeFrame} contains the request and response data.
 *
 * @param transaction
 *            Request {@link ConBeeTransaction}
 * @return response {@link ConBeeFrame}
 */
public ConBeeTransaction sendTransaction(ConBeeTransaction transaction) {
    Future<ConBeeFrame> futureResponse = sendRequestAsync(transaction);
    if (futureResponse == null) {
        logger.debug("Error sending ConBee transaction: Future is null");
        return null;
    }

    try {
        futureResponse.get();
        return transaction;
    } catch (InterruptedException | ExecutionException e) {
        logger.debug("Error sending ConBee transaction to listeners: ", e);
    }

    return null;
}
 
Example 2
Project: monarch   File: MainLauncherJUnitTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testInvokeMainWithMainLauncherWithTwoArgs() throws Exception {
  Future<Boolean> future = this.futures.submit(new Callable<Boolean>() {
    @Override
    public Boolean call() throws Exception {
      Class<?> clazz = MainLauncher.class;
      Method mainMethod = clazz.getMethod("main", String[].class);
      String[] args = new String[] {launchedClass, "arg0", "arg1"};
      mainMethod.invoke(null, new Object[] {args});
      return true;
    }
  });
  systemInMock.provideText("\n");
  assertTrue(future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS));
  assertTrue(flag);
}
 
Example 3
Project: EasyTransaction   File: ReliableMessageMethodExecutor.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <P extends EasyTransRequest<R,E>,E extends EasyTransExecutor,R extends Serializable> Future<R> execute(final Integer callSeq, final P params) {

	MessageRecordContent content = new MessageRecordContent();
	content.setParams(params);
	content.setCallSeq(callSeq);
	transSynchronizer.registerLog(content);
	final PublishResult result = new PublishResult();
	result.setMessageContentId(content.getcId());
	
	FutureTask<PublishResult> future = new FutureTask<PublishResult>(new Callable<PublishResult>() {
		@Override
		public PublishResult call() throws Exception {
			return result;
		}
	});
	future.run();
	
	return (Future<R>) future;
}
 
Example 4
Project: otter-G   File: GlobalTask.java   Source Code and License 6 votes vote down vote up
public void shutdown() {
    running = false;
    interrupt();

    List<Future> cancelFutures = new ArrayList<Future>();
    for (Map.Entry<Long, Future> entry : pendingFuture.entrySet()) {
        if (!entry.getValue().isDone()) {
            logger.warn("WARN ## Task future processId[{}] canceled!", entry.getKey());
            cancelFutures.add(entry.getValue());
        }
    }

    for (Future future : cancelFutures) {
        future.cancel(true);
    }
    pendingFuture.clear();
}
 
Example 5
Project: shuffleboard   File: TabHandle.java   Source Code and License 6 votes vote down vote up
private void startDelayedDrag(DragEvent dragEvent) {
  Future<?> task = delayedDragService.schedule(
      () -> FxUtils.runOnFxThread(tab::onDragOver),
      DRAG_FOCUS_DELAY, TimeUnit.MILLISECONDS);

  setOnDragExited(__de -> task.cancel(false));
}
 
Example 6
Project: incubator-netbeans   File: MetadataModelReadHelper.java   Source Code and License 6 votes vote down vote up
public void run() {
    try {
        Future<Void> future = model.runReadActionWhenReady(new MetadataModelAction<T, Void>() {
            public Void run(T metadata) throws Exception {
                state = State.READING_MODEL;
                fireChange();
                result = action.run(metadata);
                state = State.FINISHED;
                fireChange();
                return null;
            }
        });
        // get any exceptions thrown if the action was run asynchronously
        future.get();
    } catch (Exception e) {
        state = State.FINISHED;
        executionException = new ExecutionException(e.getMessage(), e);
        fireChange();
    }
}
 
Example 7
Project: DBus   File: MetaEventWarningSender.java   Source Code and License 6 votes vote down vote up
public void sendMessage(MetaVersion ver, MetaWrapper newMeta, MetaCompareResult result) {
    ControlMessage message = new ControlMessage(System.currentTimeMillis(), ControlType.G_META_SYNC_WARNING.toString(), "dbus-appender");

    message.addPayload("datasource", GlobalCache.getDatasource().getDsName());
    message.addPayload("schema", ver.getSchema());
    message.addPayload("tableId", ver.getTableId());
    message.addPayload("table", ver.getTable());
    message.addPayload("before", ver.getMeta());
    message.addPayload("after", newMeta);
    message.addPayload("compare-result", JSON.toJSON(result));
    message.addPayload("version", ver.getVersion());

    String topic = PropertiesHolder.getProperties(Constants.Properties.CONFIGURE, Constants.ConfigureKey.GLOBAL_EVENT_TOPIC);
    ProducerRecord<String, String> record = new ProducerRecord<>(topic, message.getType(), message.toJSONString());
    Future<RecordMetadata> future = producer.send(record, (metadata, exception) -> {
        if (exception != null) {
            logger.error("Send global event error.{}", exception.getMessage());
        }
    });
    try {
        future.get(10000, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}
 
Example 8
Project: incubator-netbeans   File: ExecutionServiceTest.java   Source Code and License 6 votes vote down vote up
public void testSimpleRun() throws InterruptedException {
    TestProcess process = new TestProcess(0);
    TestCallable callable = new TestCallable();
    callable.addProcess(process);

    ExecutionDescriptor descriptor = new ExecutionDescriptor();
    ExecutionService service = ExecutionService.newService(
            callable, descriptor, "Test");

    Future<Integer> task = service.run();
    assertNotNull(task);

    process.waitStarted();

    process.destroy();
    process.waitFor();
    assertTrue(process.isFinished());
    assertEquals(0, process.exitValue());
}
 
Example 9
Project: incubator-netbeans   File: DocDownloader.java   Source Code and License 6 votes vote down vote up
@NonNull
public static Future<String> download(
        @NonNull final URL url,
        @NonNull final Callable<Boolean> cancel) {
    return RP.submit(()-> {
        if (cancel.call()) {
            return "";  //NOI18N
        }
        final ProgressHandle handle = ProgressHandle.createHandle(NbBundle.getMessage(DocDownloader.class, "LBL_DownloadingDoc"));
        handle.start();
        try {
            final ByteArrayOutputStream out = new ByteArrayOutputStream();
            try(BufferedInputStream in = new BufferedInputStream(url.openStream())) {
                FileUtil.copy(in, out);
            }
            return cancel.call() ?
                    ""  //NOI18N
                    : new String(out.toByteArray(),"UTF-8");  //NOI18N
        } finally {
            handle.finish();
        }
    });
}
 
Example 10
Project: OSchina_resources_android   File: LargeImageActivity.java   Source Code and License 6 votes vote down vote up
private void saveToFile() {
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        Toast.makeText(this, R.string.gallery_save_file_not_have_external_storage, Toast.LENGTH_SHORT).show();
        return;
    }

    final Future<File> future = getImageLoader()
            .load(mPath)
            .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);

    AppOperator.runOnThread(new Runnable() {
        @Override
        public void run() {
            try {
                File sourceFile = future.get();
                if (sourceFile == null || !sourceFile.exists())
                    return;
                String extension = BitmapUtil.getExtension(sourceFile.getAbsolutePath());
                String extDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                        .getAbsolutePath() + File.separator + "开源中国";
                File extDirFile = new File(extDir);
                if (!extDirFile.exists()) {
                    if (!extDirFile.mkdirs()) {
                        // If mk dir error
                        callSaveStatus(false, null);
                        return;
                    }
                }
                final File saveFile = new File(extDirFile, String.format("IMG_%s.%s", System.currentTimeMillis(), extension));
                final boolean isSuccess = StreamUtil.copyFile(sourceFile, saveFile);
                callSaveStatus(isSuccess, saveFile);
            } catch (Exception e) {
                e.printStackTrace();
                callSaveStatus(false, null);
            }
        }
    });
}
 
Example 11
Project: tomcat7   File: WsWebSocketContainer.java   Source Code and License 6 votes vote down vote up
private static void writeRequest(AsyncChannelWrapper channel, ByteBuffer request,
        long timeout) throws TimeoutException, InterruptedException, ExecutionException {
    int toWrite = request.limit();

    Future<Integer> fWrite = channel.write(request);
    Integer thisWrite = fWrite.get(timeout, TimeUnit.MILLISECONDS);
    toWrite -= thisWrite.intValue();

    while (toWrite > 0) {
        fWrite = channel.write(request);
        thisWrite = fWrite.get(timeout, TimeUnit.MILLISECONDS);
        toWrite -= thisWrite.intValue();
    }
}
 
Example 12
Project: incubator-netbeans   File: RequestProcessor.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 * <p/>
 * Executes the given tasks, returning the result of one which has
 * completed and cancelling any incomplete tasks.
 * @since org.openide.util 8.2
 */
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
    Parameters.notNull("tasks", tasks); //NOI18N
    CountDownLatch wait = new CountDownLatch(1);
    List<Future<T>> result = new ArrayList<Future<T>>(tasks.size());
    AtomicReference<T> ref = new AtomicReference<T>();
    try {
        for (Callable<T> c : tasks) {
            if (c == null) {
                throw new NullPointerException ("Contains null tasks: " +  //NOI18N
                        tasks);
            }
            Callable<T> delegate = new WaitableCallable<T>(c, ref, wait);
            result.add (submit(delegate));
        }
        wait.await();
    } finally {
        for (Future<T> f : result) {
            RPFutureTask<?> ft = (RPFutureTask<?>) f;
            ft.cancel(true);
        }
    }
    return ref.get();
}
 
Example 13
Project: android-deferred   File: MultiplePromisesTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testFutures() {
	final Callable<Integer> callable1 = successCallable(999, 100);
	final Callable<String> callable2 = successCallable("HI", 1000);
	
	ExecutorService es = deferredManager.getExecutorService();
	Future<Integer> future1 = es.submit(callable1);
	Future<String> future2 = es.submit(callable2);
	final AtomicInteger doneCount = new AtomicInteger();
	deferredManager.when(future1, future2).done(new DoneCallback<MultipleResults>() {
		@Override
		public void onDone(MultipleResults result) {
			Assert.assertEquals(2, result.size());
			Assert.assertEquals(999, result.get(0).getResult());
			Assert.assertEquals("HI", result.get(1).getResult());
			doneCount.incrementAndGet();
		}
	});
	
	waitForCompletion();
	Assert.assertEquals(1, doneCount.get());
}
 
Example 14
Project: ibm-cos-sdk-java   File: TestExecutors.java   Source Code and License 6 votes vote down vote up
public static ExecutorService blocksOnFirstCallFromCallableOfType(final ExecutorService delegate, final Class<? extends Callable> type) {
    return new ForwardingExecutorService() {
        private boolean firstCall = true;

        @Override
        protected ExecutorService delegate() {
            return delegate;
        }

        @Override
        public <T> Future<T> submit(Callable<T> task) {
            if (task.getClass().equals(type) && firstCall) {
                firstCall = false;
                try {
                    return Futures.immediateFuture(task.call());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            return super.submit(task);
        }
    };
}
 
Example 15
Project: IPPR2016   File: ProcessServiceImpl.java   Source Code and License 6 votes vote down vote up
@Transactional
@Async
@Override
public Future<List<TaskDTO>> getTasksOfUser(final Long userId) {
  final CompletableFuture<List<TaskDTO>> future = new CompletableFuture<>();

  final TasksOfUserMessage.Request request = new TasksOfUserMessage.Request(userId);

  PatternsCS.ask(userSupervisorActor, request, Global.TIMEOUT).toCompletableFuture()
      .whenComplete((msg, exc) -> {
        if (exc == null) {
          future.complete(((TasksOfUserMessage.Response) msg).getTasks());
        } else {
          future.completeExceptionally(exc);
        }
      });

  return future;
}
 
Example 16
Project: iTAP-controller   File: RemoteSyncManager.java   Source Code and License 6 votes vote down vote up
/**
 * Send a request to the server and generate a future for the 
 * eventual reply.  Note that this call can block if there is no active
 * connection while a new connection is re-established or if the maximum
 * number of requests is already pending
 * @param xid the transaction ID for the request
 * @param request the actual request to send
 * @return A {@link Future} for the reply message
 * @throws InterruptedException 
 */
public Future<SyncReply> sendRequest(int xid,
                                        SyncMessage request) 
                                     throws RemoteStoreException {
    ensureConnected();
    RemoteSyncFuture future = new RemoteSyncFuture(xid, 
                                                   connectionGeneration);
    futureMap.put(Integer.valueOf(xid), future);

    if (futureMap.size() > MAX_PENDING_REQUESTS) {
        synchronized (futureNotify) {
            while (futureMap.size() > MAX_PENDING_REQUESTS) {
                try {
                    futureNotify.wait();
                } catch (InterruptedException e) {
                    throw new RemoteStoreException("Could not send request",
                                                   e);
                }
            }
        }
    }
    channel.write(request); 
    return future;
}
 
Example 17
Project: cas-server-4.2.1   File: JpaTicketRegistryTests.java   Source Code and License 6 votes vote down vote up
@Test
public void verifyConcurrentServiceTicketGeneration() throws Exception {
    final TicketGrantingTicket newTgt = newTGT();
    addTicketInTransaction(newTgt);
    final ExecutorService executor = Executors.newFixedThreadPool(CONCURRENT_SIZE);
    try {
        final List<ServiceTicketGenerator> generators = new ArrayList<>(CONCURRENT_SIZE);
        for (int i = 0; i < CONCURRENT_SIZE; i++) {
            generators.add(new ServiceTicketGenerator(newTgt.getId(), this.jpaTicketRegistry, this.txManager));
        }
        final List<Future<String>> results = executor.invokeAll(generators);
        for (final Future<String> result : results) {
            assertNotNull(result.get());
        }
    } catch (final Exception e) {
        logger.error("testConcurrentServiceTicketGeneration produced an error", e);
        fail("testConcurrentServiceTicketGeneration failed.");
    } finally {
        executor.shutdownNow();
    }
}
 
Example 18
Project: JRediClients   File: RedissonExecutorService.java   Source Code and License 6 votes vote down vote up
private <T> void addListener(final RemotePromise<T> result) {
    result.getAddFuture().addListener(new FutureListener<Boolean>() {

        @Override
        public void operationComplete(io.netty.util.concurrent.Future<Boolean> future) throws Exception {
            if (!future.isSuccess()) {
                result.tryFailure(future.cause());
                return;
            }
            
            if (!future.getNow()) {
                result.tryFailure(new RejectedExecutionException("Task rejected. ExecutorService is in shutdown state"));
            }
            
        }
    });
}
 
Example 19
Project: java-restclient   File: DummyClient.java   Source Code and License 5 votes vote down vote up
private Future<Response> executeAsync(ListenableFuture<Response> future, final HTTPCallback<Response> callback) {
    Futures.addCallback(future, new FutureCallback<Response>() {
        @Override
        public void onSuccess(Response response) {
            callback.success(response);
        }

        @Override
        public void onFailure(Throwable throwable) {
            callback.failure(throwable);
        }
    });

    return callback.getFuture();
}
 
Example 20
Project: hekate   File: BackPressureRequestTest.java   Source Code and License 5 votes vote down vote up
@Test
public void test() throws Exception {
    List<Message<String>> requests = new CopyOnWriteArrayList<>();

    createChannel(c -> useBackPressure(c)
        .withReceiver(requests::add)
    ).join();

    MessagingChannel<String> sender = createChannel(this::useBackPressure).join().get().forRemotes();

    // Enforce back pressure on sender.
    List<ResponseFuture<String>> futureResponses = requestUpToHighWatermark(sender);

    busyWait("requests received", () -> requests.size() == futureResponses.size());

    assertBackPressureEnabled(sender);

    // Go down to low watermark.
    requests.stream().limit(getLowWatermarkBounds()).forEach(r -> r.reply("ok"));

    busyWait("responses received", () ->
        futureResponses.stream().filter(CompletableFuture::isDone).count() == getLowWatermarkBounds()
    );

    // Check that new request can be processed.
    get(sender.send("last"));

    requests.stream().filter(Message::mustReply).forEach(r -> r.reply("ok"));

    for (Future<?> future : futureResponses) {
        get(future);
    }
}
 
Example 21
Project: ECFileCache   File: RedisAccessParallel.java   Source Code and License 5 votes vote down vote up
@Override
public Pair<byte[][], int[]> getChunk(List<Integer> redisIds, String cacheKey, long chunkPos, int chunkSize) throws
                                                       ECFileCacheException {

  List<DecoratedJedisPool> jedisPools = getJedisPools(redisIds);

  byte[][] redisDataArray = new byte[jedisPools.size()][];

  CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(pool);
  List<Future<Integer>> futures = new ArrayList<Future<Integer>>();

  String field = chunkPos + SEP + chunkSize;

  int failCount = 0;
  for (int i = 0; i < jedisPools.size(); ++i) {
    DecoratedJedisPool jedis = jedisPools.get(i);
    if (jedis != null) {
      String key = cacheKey + SEP + i;
      RedisGetChunk redisGetChunk = new RedisGetChunk(jedis, key, field, redisDataArray, i);

      if (!pool.isShutdown()) {
        Future<Integer> future = completionService.submit(redisGetChunk);
        futures.add(future);
      }
    } else {
      failCount++;
    }
  }
  checkRedisResult(completionService, futures, failCount);

  return convertChunk(redisDataArray, chunkSize);
}
 
Example 22
Project: openjdk-jdk10   File: StreamPumper.java   Source Code and License 5 votes vote down vote up
final public Future<Void> process() {
    if (!processing.compareAndSet(false, true)) {
        throw new IllegalStateException("Can not re-run the processing");
    }
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            processingTask.run();
        }
    });
    t.setDaemon(true);
    t.start();

    return processingTask;
}
 
Example 23
Project: accumulate   File: HystrixTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSynchronous() throws Exception {

    //同步调用
    System.out.println(new CommandHelloWorld("World").execute());
    //异步调用
    Future<String> world = new CommandHelloWorld("World").queue();
    System.out.println(world.get());
}
 
Example 24
Project: voyage   File: Client.java   Source Code and License 5 votes vote down vote up
public static void send(IServer server1,int f_i) {
	Message msg = null;
	try {
		//由于客户端配置的async="true",我们用异步方式来获取结果,如果是同步方式,直接msg=server1.echoMsg(f_i)即可
		server1.echoMsg(f_i);
		Future<Message> future = RpcContext.getContext().getFuture();
		msg = future.get();
		System.out.println("msg:"+msg.getMsg()+","+msg.getData());
	} catch(Throwable e) {
		e.printStackTrace();
	}
}
 
Example 25
Project: hashsdn-controller   File: IdIntsDOMDataTreeLIstener.java   Source Code and License 5 votes vote down vote up
public Future<Void> tryFinishProcessing() {
    executorService = Executors.newSingleThreadScheduledExecutor();
    final SettableFuture<Void> settableFuture = SettableFuture.create();

    scheduledFuture = executorService.scheduleAtFixedRate(new CheckFinishedTask(settableFuture), 0, 1, TimeUnit.SECONDS);
    return settableFuture;
}
 
Example 26
Project: java-chess   File: MinimaxAlphaBeta.java   Source Code and License 5 votes vote down vote up
public Move decision(final Board b) {
	// get maximum move
	
	final ArrayList<Move> moves = b.getMoves(color);
	if(moves.size() == 0)
		return null;
		
	Vector<Future<Float>> costs = new Vector<Future<Float>>(moves.size());
	costs.setSize(moves.size());
	
		ExecutorService exec = Executors.newFixedThreadPool(moves.size());
		try {
		    for (int i = 0; i < moves.size(); i++) {
		    	final Move move = moves.get(i);
		        Future<Float> result = exec.submit(new Callable<Float>() {

		            @Override
		            public Float call() {
		            	ArrayList<Move> state = new ArrayList<Move>();
		            	state.add(move);
		            	
		            	float tmp = minValue(b, state, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, 1);
		            	return tmp;
		            }
		        });
		        costs.set(i, result);
		    }
		} finally {
		    exec.shutdown();
		}

		// max
		int maxi = -1;
	float max = Float.NEGATIVE_INFINITY;
		for(int i = 0; i < moves.size(); i++) {
			float cost;
		try {
			cost = costs.get(i).get();
		} catch (Exception e) {
			try {
				Thread.sleep(300);
			} catch (InterruptedException e1) {
			}
			continue;
		}
			if(cost >= max) {
				if(Math.abs(cost-max) < 0.1) // add a little random element
					if(rand.nextBoolean())
						continue;

				max = cost;
				maxi = i;
			}
		}
		
		return moves.get(maxi);
}
 
Example 27
Project: hadoop   File: TestWebHdfsContentLength.java   Source Code and License 5 votes vote down vote up
@Test
public void testPostOpWithRedirect() {
  // POST operation with redirect
  Future<String> future1 = contentLengthFuture(redirectResponse);
  Future<String> future2 = contentLengthFuture(errResponse);
  try {
    FSDataOutputStream os = fs.append(p);
    os.write(new byte[]{0});
    os.close();
    Assert.fail();
  } catch (IOException ioe) {} // expected
  Assert.assertEquals("0", getContentLength(future1));
  Assert.assertEquals("chunked", getContentLength(future2));
}
 
Example 28
Project: devicehub   File: DeviceHubClient.java   Source Code and License 5 votes vote down vote up
/**
 * Send the device request asynchronously
 *
 * @param clientDeviceRequest the device request to send
 * @return the Future instance that holds the response
 */
public Future<ClientDeviceResponse> sendDeviceRequestAsync(
    ClientDeviceRequest clientDeviceRequest) {

  return executorService.submit(
      new Callable<ClientDeviceResponse>() {
        @Override
        public ClientDeviceResponse call() {
          return sendDeviceRequest(clientDeviceRequest);
        }
      });
}
 
Example 29
Project: elasticsearch_my   File: SearchWithRejectionsIT.java   Source Code and License 5 votes vote down vote up
public void testOpenContextsAfterRejections() throws InterruptedException {
    createIndex("test");
    ensureGreen("test");
    final int docs = scaledRandomIntBetween(20, 50);
    for (int i = 0; i < docs; i++) {
        client().prepareIndex("test", "type", Integer.toString(i)).setSource("field", "value").execute().actionGet();
    }
    IndicesStatsResponse indicesStats = client().admin().indices().prepareStats().execute().actionGet();
    assertThat(indicesStats.getTotal().getSearch().getOpenContexts(), equalTo(0L));
    refresh();

    int numSearches = 10;
    Future<SearchResponse>[] responses = new Future[numSearches];
    SearchType searchType = randomFrom(SearchType.DEFAULT, SearchType.QUERY_THEN_FETCH, SearchType.DFS_QUERY_THEN_FETCH);
    logger.info("search type is {}", searchType);
    for (int i = 0; i < numSearches; i++) {
        responses[i] = client().prepareSearch()
                .setQuery(matchAllQuery())
                .setSearchType(searchType)
                .execute();
    }
    for (int i = 0; i < numSearches; i++) {
        try {
            responses[i].get();
        } catch (Exception t) {
        }
    }
    awaitBusy(() -> client().admin().indices().prepareStats().execute().actionGet().getTotal().getSearch().getOpenContexts() == 0, 1, TimeUnit.SECONDS);
    indicesStats = client().admin().indices().prepareStats().execute().actionGet();
    assertThat(indicesStats.getTotal().getSearch().getOpenContexts(), equalTo(0L));
}
 
Example 30
Project: ibm-cos-sdk-java   File: CompleteMultipartCopy.java   Source Code and License 5 votes vote down vote up
/**
 * Collects the Part ETags for initiating the complete multi-part copy
 * request. This is blocking as it waits until all the upload part threads
 * complete.
 */
private List<PartETag> collectPartETags() {

    final List<PartETag> partETags = new ArrayList<PartETag>();
    for (Future<PartETag> future : futures) {
        try {
            partETags.add(future.get());
        } catch (Exception e) {
            throw new SdkClientException("Unable to copy part: "
                    + e.getCause().getMessage(), e.getCause());
        }
    }
    return partETags;
}
 
Example 31
Project: EasyTransaction   File: ExecuteCacheManager.java   Source Code and License 5 votes vote down vote up
public <T> Future<T> cacheCall(Callable<T> compensableCall,Content content){
	logCtx.getLogCache().cacheLogList(Arrays.asList(content));
	
	mapCallable.put(compensableCall,new Object[3]);
	CompensableCallerWrapper<T> compensableCallWrapper = new CompensableCallerWrapper<T>(compensableCall);
	Future<T> future = new ExecuteTriggerByGetFuture<T>(compensableCallWrapper);
	return future;
}
 
Example 32
Project: hadoop   File: TestInMemorySCMStore.java   Source Code and License 5 votes vote down vote up
@Test
public void testAddResourceRefAddResourceConcurrency() throws Exception {
  startEmptyStore();
  final String key = "key1";
  final String fileName = "foo.jar";
  final String user = "user";
  final ApplicationId id = createAppId(1, 1L);
  // add the resource and add the resource ref at the same time
  ExecutorService exec = Executors.newFixedThreadPool(2);
  final CountDownLatch start = new CountDownLatch(1);
  Callable<String> addKeyTask = new Callable<String>() {
    public String call() throws Exception {
      start.await();
      return store.addResource(key, fileName);
    }
  };
  Callable<String> addAppIdTask = new Callable<String>() {
    public String call() throws Exception {
      start.await();
      return store.addResourceReference(key,
          new SharedCacheResourceReference(id, user));
    }
  };
  Future<String> addAppIdFuture = exec.submit(addAppIdTask);
  Future<String> addKeyFuture = exec.submit(addKeyTask);
  // start them at the same time
  start.countDown();
  // get the results
  String addKeyResult = addKeyFuture.get();
  String addAppIdResult = addAppIdFuture.get();
  assertEquals(fileName, addKeyResult);
  System.out.println("addAppId() result: " + addAppIdResult);
  // it may be null or the fileName depending on the timing
  assertTrue(addAppIdResult == null || addAppIdResult.equals(fileName));
  exec.shutdown();
}
 
Example 33
Project: java-restclient   File: RestClientAsyncRetryTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = ExecutionException.class)
public void shouldRetryOnMakeResponseException() throws RestException, ExecutionException, InterruptedException {
    String url = "http://dummy.com/test";

    MockResponse.builder()
            .withURL(url)
            .withMethod(POST)
            .withStatusCode(201)
            .withResponseHeader(ContentType.HEADER_NAME, ContentType.TEXT_PLAIN.toString())
            .withResponseBody(DummyCallbackProcessor.THROW)
            .build();

    final AtomicInteger retries = new AtomicInteger();

    Future<Response> response = RestClient.getDefault().withRetryStrategy(new RetryStrategy() {
        @Override
        public RetryResponse shouldRetry(Request req, Response r, Exception e, int rs) {
            retries.getAndIncrement();
            return new RetryResponse(false, 0);
        }
    }).asyncPost(url);

    LockSupport.parkNanos(2000000);

    assertEquals(1, retries.get());

    response.get();
}
 
Example 34
Project: IPPR2016   File: EventLogServiceImpl.java   Source Code and License 5 votes vote down vote up
@Async
@Override
public Future<List<EventLoggerDTO>> getEventLogForProcessModelAndSubject(final int processModelId,
    final String subject) {
  final List<EventLogEntry> results =
      eventLogRepository.getEventLogForProcessModelAndSubject(processModelId, subject);
  final List<EventLoggerDTO> eventLog = createEventLoggerDTO(results);
  return new AsyncResult<List<EventLoggerDTO>>(eventLog);
}
 
Example 35
Project: monarch   File: GMSJoinLeave.java   Source Code and License 5 votes vote down vote up
private <T> List<Future<T>> submitAll(ExecutorService executor,
    Collection<? extends Callable<T>> tasks) {
  List<Future<T>> result = new ArrayList<Future<T>>(tasks.size());

  for (Callable<T> task : tasks) {
    result.add(executor.submit(task));
  }

  return result;
}
 
Example 36
Project: Achilles_Android   File: CpuMonitor.java   Source Code and License 5 votes vote down vote up
private void scheduleCpuUtilizationTask() {
    if (executor != null) {
        executor.shutdownNow();
        executor = null;
    }

    executor = Executors.newSingleThreadScheduledExecutor();
    @SuppressWarnings("unused") // Prevent downstream linter warnings.
            Future<?> possiblyIgnoredError = executor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            cpuUtilizationTask();
        }
    }, 0, CPU_STAT_SAMPLE_PERIOD_MS, TimeUnit.MILLISECONDS);
}
 
Example 37
Project: NEILREN4J   File: MemcachedManager.java   Source Code and License 5 votes vote down vote up
/**
 * 从缓存中获取.
 *
 * @param keys keys
 * @return Map<String, Object>
 */
public Map<String, Object> asyncGetMulti(String[] keys) {
    Map<String, Object> map = null;
    Future<Map<String, Object>> f = memcachedClient.asyncGetBulk(keys);
    try {
        map = f.get(SpyMemcachedConstants.DEFAULT_TIMEOUT, SpyMemcachedConstants.DEFAULT_TIMEUNIT);
    } catch (Exception e) {
        f.cancel(false);
    }
    return map;
}
 
Example 38
Project: hekate   File: AsyncUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testGetUninterruptedlyNoInterrupt() throws Exception {
    CompletableFuture<String> future = new CompletableFuture<>();

    Future<Object> testFuture = runAsync(() ->
        AsyncUtils.getUninterruptedly(future)
    );

    future.complete("something");

    assertEquals("something", get(testFuture));
}
 
Example 39
Project: endpoint-health   File: EndPointCheckSchedulerServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void scheduleCheck(final EndPoint endPoint) {
    final Future<?> future = scheduledExecutorService.scheduleWithFixedDelay(() -> checkEndPoint(endPoint), 0,
        DEFAULT_CHECK_DELAY, TimeUnit.SECONDS);

    endPointFutures.put(endPoint, future);

    LOGGER.info(String.format("%s scheduled", endPoint));
}
 
Example 40
Project: openjdk-jdk10   File: AbstractExecutorServiceTest.java   Source Code and License 5 votes vote down vote up
/**
 * Completed submit(runnable) returns successfully
 */
public void testSubmitRunnable() throws Exception {
    ExecutorService e = new DirectExecutorService();
    Future<?> future = e.submit(new NoOpRunnable());
    future.get();
    assertTrue(future.isDone());
}
 
Example 41
Project: add_to_evernote_note   File: EvernoteNoteStoreClient.java   Source Code and License 5 votes vote down vote up
public Future<Integer> updateLinkedNotebookAsync(final LinkedNotebook linkedNotebook, EvernoteCallback<Integer> callback) {
    return submitTask(new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            return updateLinkedNotebook(linkedNotebook);
        }
    }, callback);
}
 
Example 42
Project: hekate   File: SendPressureGuardTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testBlock() throws Exception {
    SendPressureGuard backPressure = new SendPressureGuard(5, 10, MessagingOverflowPolicy.BLOCK);

    repeat(3, i -> {
        for (int j = 0; j < 10; j++) {
            backPressure.onEnqueue();

            assertEquals(j + 1, backPressure.queueSize());
        }

        assertEquals(10, backPressure.queueSize());

        Future<?> future = runAsync(() -> {
            backPressure.onEnqueue();

            return null;
        });

        expect(TimeoutException.class, () -> future.get(300, TimeUnit.MILLISECONDS));

        assertEquals(11, backPressure.queueSize());

        for (int j = 0; j < 6; j++) {
            backPressure.onDequeue();
        }

        assertNull(get(future));

        assertEquals(5, backPressure.queueSize());

        while (backPressure.queueSize() > 0) {
            backPressure.onDequeue();
        }
    });
}
 
Example 43
Project: add_to_evernote_note   File: EvernoteClientFactory.java   Source Code and License 5 votes vote down vote up
/**
 * @see #getLinkedNotebookHelper(LinkedNotebook)
 */
public Future<EvernoteHtmlHelper> getLinkedHtmlHelperAsync(@NonNull final LinkedNotebook linkedNotebook, @Nullable EvernoteCallback<EvernoteHtmlHelper> callback) {
    return mCreateHelperClient.submitTask(new Callable<EvernoteHtmlHelper>() {
        @Override
        public EvernoteHtmlHelper call() throws Exception {
            return getLinkedHtmlHelper(linkedNotebook);
        }
    }, callback);
}
 
Example 44
Project: uavstack   File: GrafanaClient.java   Source Code and License 5 votes vote down vote up
public Future<HttpResponse> doAsyncHttp(String type, String path, String dataStr, Map<String, String> head,
        GrafanaHttpCallBack callback) {

    Future<HttpResponse> response = null;

    // def callback
    if (null == callback) {
        callback = new GrafanaHttpCallBack(configMap);
    }

    // set req info
    callback.setRequestUrl(getApiHttpReqUrl(path));
    callback.setRequestType(type);
    callback.setRequestData(dataStr);
    callback.appendParams(configMap);

    // def head
    if (null == head) {
        head = getHttpReqHead();
    }
    else {
        head.putAll(getHttpReqHead());
    }

    // action
    if ("post".equals(type)) {
        response = httpAsyncClient.doAsyncHttpPost(getApiHttpReqUrl(path), head, dataStr, null, "application/json",
                "utf-8", callback);
    }
    else if ("get".equals(type)) {
        response = httpAsyncClient.doAsyncHttpGet(getApiHttpReqUrl(path), head, "application/json", callback);
    }
    else if ("delete".equals(type)) {
        response = httpAsyncClient.doAsyncHttpDel(getApiHttpReqUrl(path), head, "application/json", callback);
    }
    return response;
}
 
Example 45
Project: VASSAL-src   File: WarningDialog.java   Source Code and License 5 votes vote down vote up
public static Future<?> showDisableable(
  Component parent,
  Object key,
  String messageKey,
  Object... args)
{
  return ProblemDialog.showDisableable(
    JOptionPane.WARNING_MESSAGE, parent, key, messageKey, args
  );
}
 
Example 46
Project: scanning   File: BeanStatusFinder.java   Source Code and License 5 votes vote down vote up
/**
 * Creates two {@link QueueSearcher} objects to locate the bean with the
 * given uniqueID in the submission queue or status set of the configured
 * {@link IConsumer}. A timeout (in ms) can be specified after which the
 * search is cancelled. If the bean is not found before the timeout or if
 * the bean is not found at all an exception is thrown to alert the caller.
 * If everything runs smoothly, the {@link Status} of the bean is returned.
 *
 * @param timeout long number of ms before search is cancelled.
 * @return current {@link Status} of the requested bean.
 * @throws EventException - if the search timed out or the bean was not
 *                          found.
 */
public Status find(long timeout) throws EventException {
	/*
	 * Interrogate both submission & status queues simultaneously.
	 */
	//This needs a latch to indicate completion...

	Future<?> statusSetSearch = threadPool.submit(new QueueSearcher(beanID, consumer.getStatusSet()));
	Future<?> submitQueueSearch = threadPool.submit(new QueueSearcher(beanID, consumer.getSubmissionQueue()));

	boolean latched;
	try {
		latched = searchEndedLatch.await(timeout, TimeUnit.MILLISECONDS);
	} catch (InterruptedException iEx) {
		throw new EventException("Could not wait finding bean", iEx);
	} finally {
		//At this stage we can safely shutdown the executor.
		threadPool.shutdown();
	}
	if (!latched) {
		//Something went wrong, but was it an exception or just not found?
		try {
			statusSetSearch.get(1, TimeUnit.MILLISECONDS);
			submitQueueSearch.get(1, TimeUnit.MILLISECONDS);
			throw new EventException("Search timed out before finding bean. Contact your GDA representative.");
		} catch (EventException evEx) {
			throw evEx;
		} catch (Exception ex) {
			throw new EventException("Bean search encountered error(s)",ex);
		}
	}
	else if (foundStatus == null) throw new EventException("Bean not found");
	return foundStatus;
}
 
Example 47
Project: openjdk-jdk10   File: OidTableInit.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Throwable {
    final String[] algorithmNames = {
        "PBKDF2WITHHMACSHA1",
        "PBEWITHMD5ANDDES",
        "DSA",
        "SHA384WITHRSA",
        "RSA",
        "SHA1WITHDSA",
        "SHA512WITHRSA",
        "MD2WITHRSA",
        "PBEWITHSHA1ANDDESEDE",
        "SHA1WITHRSA",
        "DIFFIEHELLMAN",
        "MD5WITHRSA",
        "PBEWITHSHA1ANDRC2_40",
        "SHA256WITHRSA",
    };

    final int THREADS = 2;
    final ExecutorService pool = Executors.newFixedThreadPool(THREADS);
    final CountDownLatch startingGate = new CountDownLatch(THREADS);
    final Runnable r = new Runnable() { public void run() {
        startingGate.countDown();
        do {} while (startingGate.getCount() > 0);
        try {
            for (String algorithmName : algorithmNames)
                AlgorithmId.get(algorithmName);
        } catch (Throwable fail) {
            throw new AssertionError(fail);
        }
    }};
    final ArrayList<Future<?>> futures = new ArrayList<>();
    for (int i = 0; i < THREADS; i++)
        futures.add(pool.submit(r));
    pool.shutdown();
    for (Future<?> future : futures) future.get();
}
 
Example 48
Project: xmlrss   File: PSRedactableSignature.java   Source Code and License 5 votes vote down vote up
/**
 * Applies the given function to every element of the given collection and returns a Collection of the results.
 *
 * @param function   the function which is applied to every element of collection
 * @param collection the elements
 * @param <E>        Input (argument) type
 * @param <R>        Result type
 * @return a collection of results of the function
 * @throws PSRSSException if the parallel execution failed
 */
private <E, R> Collection<R> map(final Function<E, R> function, Iterable<E> collection) throws PSRSSException {
    ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
    Collection<Callable<R>> tasks = new LinkedList<>();

    for (final E item : collection) {
        tasks.add(new Callable<R>() {
            @Override
            public R call() throws Exception {
                return function.execute(item);
            }
        });
    }

    List<Future<R>> futures = pool.invokeAll(tasks);
    Collection<R> results = new ArrayList<>(futures.size());

    for (Future<R> future : futures) {
        if (!future.isCancelled()) {
            try {
                results.add(future.get());
            } catch (InterruptedException | ExecutionException e) {
                throw new PSRSSException(e);
            }
        } else {
            throw new PSRSSException("Parallel execution failed");
        }
    }

    pool.shutdown();

    return results;
}
 
Example 49
Project: downloadmanager   File: DownloadService.java   Source Code and License 5 votes vote down vote up
private static ExecutorService buildDownloadExecutor() {
    final int maxConcurrent = 5;

    // Create a bounded thread pool for executing downloads; it creates
    // threads as needed (up to maximum) and reclaims them when finished.
    final ThreadPoolExecutor executor = new ThreadPoolExecutor(
            maxConcurrent, maxConcurrent, 10, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>()) {
        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            super.afterExecute(r, t);

            if (t == null && r instanceof Future<?>) {
                try {
                    ((Future<?>) r).get();
                } catch (CancellationException ce) {
                    t = ce;
                } catch (ExecutionException ee) {
                    t = ee.getCause();
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
            }

            if (t != null) {
                Log.w(TAG, "Uncaught exception", t);
            }
        }
    };
    executor.allowCoreThreadTimeOut(true);
    return executor;
}
 
Example 50
Project: page-content-tester   File: FetcherManagerTest.java   Source Code and License 5 votes vote down vote up
@Test(timeout = 5000)
public void dontCachePageForSameTest() throws Exception {
    final String testName = getUniqueTestName();
    final Future<FetchedPage> future1 = FetcherManager.getInstance()
            .submit(aValidRequest(), testName);
    final Future<FetchedPage> future2 = FetcherManager.getInstance()
            .submit(aValidRequest(), testName);
    assertThat(future1.get()).isNotSameAs(future2.get());
}
 
Example 51
Project: VASSAL-src   File: ProblemDialog.java   Source Code and License 5 votes vote down vote up
public static Future<?> showDisableable(
  int messageType,
  Object key,
  String messageKey,
  Object... args)
{
  return showDisableable(
    messageType, getFrame(), null, key, messageKey, args
  );
}
 
Example 52
Project: googles-monorepo-demo   File: TestingExecutorsTest.java   Source Code and License 5 votes vote down vote up
public void testSameThreadScheduledExecutorWithException() throws InterruptedException {
  Runnable runnable = new Runnable() {
    @Override public void run() {
      throw new RuntimeException("Oh no!");
    }
  };

  Future<?> future = TestingExecutors.sameThreadScheduledExecutor().submit(runnable);
  try {
    future.get();
    fail("Should have thrown exception");
  } catch (ExecutionException e) {
    // pass
  }
}
 
Example 53
Project: tomcat7   File: SimplePOJOAsyncExample.java   Source Code and License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    PoolConfiguration p = new PoolProperties();
    p.setFairQueue(true);
    p.setUrl("jdbc:mysql://localhost:3306/mysql?autoReconnect=true");
    p.setDriverClassName("com.mysql.jdbc.Driver");
    p.setUsername("root");
    p.setPassword("password");
    p.setJmxEnabled(true);
    p.setTestWhileIdle(false);
    p.setTestOnBorrow(true);
    p.setValidationQuery("SELECT 1");
    p.setTestOnReturn(false);
    p.setValidationInterval(30000);
    p.setTimeBetweenEvictionRunsMillis(30000);
    p.setMaxActive(100);
    p.setInitialSize(10);
    p.setMaxWait(10000);
    p.setRemoveAbandonedTimeout(60);
    p.setMinEvictableIdleTimeMillis(30000);
    p.setMinIdle(10);
    p.setLogAbandoned(true);
    p.setRemoveAbandoned(true);
    p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
    DataSource datasource = new DataSource();
    datasource.setPoolProperties(p);

    Connection con = null;
    try {
      Future<Connection> future = datasource.getConnectionAsync();
      while (!future.isDone()) {
          System.out.println("Connection is not yet available. Do some background work");
          try {
              Thread.sleep(100); //simulate work
          }catch (InterruptedException x) {
              Thread.interrupted();
          }
      }
      con = future.get(); //should return instantly
      Statement st = con.createStatement();
      ResultSet rs = st.executeQuery("select * from user");
      int cnt = 1;
      while (rs.next()) {
          System.out.println((cnt++)+". Host:" +rs.getString("Host")+" User:"+rs.getString("User")+" Password:"+rs.getString("Password"));
      }
      rs.close();
      st.close();
    } finally {
      if (con!=null) try {con.close();}catch (Exception ignore) {}
    }
}
 
Example 54
Project: incubator-netbeans   File: OpenProjectList.java   Source Code and License 4 votes vote down vote up
public Future<Project[]> openProjectsAPI() {
    return LOAD;
}
 
Example 55
Project: iot-edge-greengrass   File: DefaultHttpService.java   Source Code and License 4 votes vote down vote up
private void waitWithTimeout(Future future) throws Exception {
    future.get(OPERATION_TIMEOUT_IN_SEC, TimeUnit.SECONDS);
}
 
Example 56
Project: incubator-netbeans   File: CslTestBase.java   Source Code and License 4 votes vote down vote up
/** Test the occurrences to make sure they equal the golden file.
 * If the symmetric parameter is set, this test will also ensure that asking for
 * occurrences on ANY of the matches produced by the original caret position will
 * produce the exact same map. This is obviously not appropriate for things like
 * occurrences on the exit points.
 */
protected void checkOccurrences(String relFilePath, String caretLine, final boolean symmetric) throws Exception {
    Source testSource = getTestSource(getTestFile(relFilePath));

    Document doc = testSource.getDocument(true);
    final int caretOffset = getCaretOffset(doc.getText(0, doc.getLength()), caretLine);

    final OccurrencesFinder finder = getOccurrencesFinder();
    assertNotNull("getOccurrencesFinder must be implemented", finder);
    finder.setCaretPosition(caretOffset);

    UserTask task = new UserTask() {
        public @Override void run(ResultIterator resultIterator) throws Exception {
            Parser.Result r = resultIterator.getParserResult(caretOffset);
            if (r instanceof ParserResult) {
                finder.run((ParserResult) r, null);
                Map<OffsetRange, ColoringAttributes> occurrences = finder.getOccurrences();
                if (occurrences == null) {
                    occurrences = Collections.emptyMap();
                }

                String annotatedSource = annotateFinderResult(resultIterator.getSnapshot(), occurrences, caretOffset);
                assertDescriptionMatches(resultIterator.getSnapshot().getSource().getFileObject(), annotatedSource, true, ".occurrences");

                if (symmetric) {
                    // Extra check: Ensure that occurrences are symmetric: Placing the caret on ANY of the occurrences
                    // should produce the same set!!
                    for (OffsetRange range : occurrences.keySet()) {
                        int midPoint = range.getStart() + range.getLength() / 2;
                        finder.setCaretPosition(midPoint);
                        finder.run((ParserResult) r, null);
                        Map<OffsetRange, ColoringAttributes> alternates = finder.getOccurrences();
                        assertEquals("Marks differ between caret positions - failed at " + midPoint, occurrences, alternates);
                    }
                }
            }
        }
    };
    if (classPathsForTest == null || classPathsForTest.isEmpty()) {
        ParserManager.parse(Collections.singleton(testSource), task);
    } else {
        Future<Void> future = ParserManager.parseWhenScanFinished(Collections.singleton(testSource), task);
        if (!future.isDone()) {
            future.get();
        }
    }
}
 
Example 57
Project: otter-G   File: ExecutorTemplate.java   Source Code and License 4 votes vote down vote up
public void start() {
    completionService = new ExecutorCompletionService(executor);
    futures = Collections.synchronizedList(new ArrayList<Future>());
}
 
Example 58
Project: swage   File: ContextAwareCompletionService.java   Source Code and License 4 votes vote down vote up
@Override
public Future<V> take() throws InterruptedException {
    return delegate.take();
}
 
Example 59
Project: de.flapdoodle.solid   File: FutureWriter.java   Source Code and License 4 votes vote down vote up
public void enqueue(Future<String> future) throws IOException {
    if (closed) {
        throw new IOException("Writer is closed");
    }
    orderedFutures.add(future);
}
 
Example 60
Project: ditb   File: IntegrationTestMTTR.java   Source Code and License 4 votes vote down vote up
public PutCallable(Future<?> f) throws IOException {
  super(f);
  this.table = new HTable(util.getConfiguration(), tableName);
}