本文整理汇总了Java中java.util.concurrent.Future类的典型用法代码示例。如果您正苦于以下问题:Java Future类的具体用法?Java Future怎么用?Java Future使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Future类属于java.util.concurrent包,在下文中一共展示了Future类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: sendTransaction
import java.util.concurrent.Future; //导入依赖的package包/类
/**
* 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;
}
示例2: testInvokeMainWithMainLauncherWithTwoArgs
import java.util.concurrent.Future; //导入依赖的package包/类
@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);
}
示例3: execute
import java.util.concurrent.Future; //导入依赖的package包/类
@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;
}
示例4: shutdown
import java.util.concurrent.Future; //导入依赖的package包/类
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();
}
示例5: run
import java.util.concurrent.Future; //导入依赖的package包/类
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();
}
}
示例6: sendMessage
import java.util.concurrent.Future; //导入依赖的package包/类
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);
}
}
示例7: testSimpleRun
import java.util.concurrent.Future; //导入依赖的package包/类
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());
}
示例8: download
import java.util.concurrent.Future; //导入依赖的package包/类
@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();
}
});
}
示例9: saveToFile
import java.util.concurrent.Future; //导入依赖的package包/类
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);
}
}
});
}
示例10: writeRequest
import java.util.concurrent.Future; //导入依赖的package包/类
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();
}
}
示例11: invokeAny
import java.util.concurrent.Future; //导入依赖的package包/类
/**
* {@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();
}
示例12: testFutures
import java.util.concurrent.Future; //导入依赖的package包/类
@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());
}
示例13: blocksOnFirstCallFromCallableOfType
import java.util.concurrent.Future; //导入依赖的package包/类
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);
}
};
}
示例14: getTasksOfUser
import java.util.concurrent.Future; //导入依赖的package包/类
@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;
}
示例15: sendRequest
import java.util.concurrent.Future; //导入依赖的package包/类
/**
* 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;
}