当前位置: 首页>>代码示例>>Java>>正文


Java Future.get方法代码示例

本文整理汇总了Java中java.util.concurrent.Future.get方法的典型用法代码示例。如果您正苦于以下问题:Java Future.get方法的具体用法?Java Future.get怎么用?Java Future.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.concurrent.Future的用法示例。


在下文中一共展示了Future.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testAsyncQuery2

import java.util.concurrent.Future; //导入方法依赖的package包/类
@Test
public void testAsyncQuery2() {
    Object[][] expectedResults = {
            {"John", "Smith", 40},
            {"Jim", "White", 24},
    };
    String[] columnList = {PERSON_FIRST_NAME,PERSON_LAST_NAME,PERSON_AGE};
    IPredicate predicate = new OperatorPredicate(PERSON_LAST_NAME, OperatorPredicate.Operator.GTE, "Sm");
    Future<IResultSet> future = storageSource.executeQueryAsync(PERSON_TABLE_NAME,
            columnList, predicate, new RowOrdering(PERSON_SSN));
    waitForFuture(future);
    try {
        IResultSet resultSet = future.get();
        checkExpectedResults(resultSet, columnList, expectedResults);
    }
    catch (Exception e) {
        fail("Exception thrown in async storage operation: " + e.toString());
    }
}
 
开发者ID:xuraylei,项目名称:fresco_floodlight,代码行数:20,代码来源:StorageTest.java

示例2: computeBestProposal

import java.util.concurrent.Future; //导入方法依赖的package包/类
private void computeBestProposal() {
  long start = _time.milliseconds();
  List<Future> futures = new ArrayList<>();
  for (int i = 0; i < _numPrecomputingThreads; i++) {
    futures.add(_proposalPrecomputingExecutor.submit(new ProposalCandidateComputer(_goalByPriorityForPrecomputing.get(i))));
  }
  for (Future future : futures) {
    try {
      boolean done = false;
      while (!_shutdown && !done) {
        try {
          future.get();
          done = true;
        } catch (InterruptedException ie) {
          LOG.debug("Goal optimizer received exception when precomputing the proposal candidates {}.", ie.toString());
        }
      }
    } catch (ExecutionException ee) {
      LOG.error("Goal optimizer received exception when precomputing the proposal candidates.", ee);
    }
  }
  LOG.info("Finished precomputation {} proposal candidates in {} ms", _totalProposalCandidateComputed.get() - 1,
           _time.milliseconds() - start);
}
 
开发者ID:linkedin,项目名称:cruise-control,代码行数:25,代码来源:GoalOptimizer.java

示例3: handleComplete

import java.util.concurrent.Future; //导入方法依赖的package包/类
@Override
protected void handleComplete ( final Future<UserInformation> future, final ConfigurationGroup group ) throws Exception
{
    logger.debug ( "Handle complete - future: {}, group: {}", future, group );

    final UserInformation userInformation = future.get ();
    if ( userInformation != null )
    {
        setResult ( userInformation );
    }
    else
    {
        if ( this.counter < group.getRetries () )
        {
            logger.debug ( "Retry current group - retry #{} of {}", this.counter, group.getRetries () );
            this.counter++;
            processCurrent ();
        }
        else
        {
            logger.debug ( "Try next authorization group" );
            this.counter = 1;
            processNext ();
        }
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:27,代码来源:Authenticator.java

示例4: testRPC

import java.util.concurrent.Future; //导入方法依赖的package包/类
@Test
public void testRPC() throws InterruptedException, ExecutionException {
    String name = "Ed Warnicke";
    HelloService service = getSession().getRpcService(HelloService.class);

    HelloWorldInput input = new HelloWorldInputBuilder()
            .setName(name)
            .build();
    Future<RpcResult<HelloWorldOutput>> outputFuture = service.helloWorld(input);
    RpcResult<HelloWorldOutput> outputResult = outputFuture.get();
    Assert.assertTrue("RPC was unsuccessful", outputResult.isSuccessful());
    Assert.assertEquals("Did not receive the expected response to helloWorld RPC", "Hello " + name,
            outputResult.getResult().getGreeting());

    validateRPCResponse(name, outputResult.getResult().getGreeting());
    validateGreetingRegistry(name);
}
 
开发者ID:lrodrin,项目名称:opendaylight,代码行数:18,代码来源:HelloIT.java

示例5: watcherMustNotify

import java.util.concurrent.Future; //导入方法依赖的package包/类
@Test
@Ignore
public void watcherMustNotify() throws InterruptedException, ExecutionException {
	File tempDir = Files.createTempDir();
	
	AtomicBoolean shouldCreateFiles = new AtomicBoolean(true);
	AtomicInteger changeCounter=new AtomicInteger(0);
	
	Future<?> fileChanger = Executors.newSingleThreadExecutor().submit(() -> {
		int i=0;
		while (shouldCreateFiles.get()) {
			int run=i++;
			
			Try.runable(() -> {
					System.out.println("run "+run);
					System.out.flush();
					java.nio.file.Files.write(tempDir.toPath().resolve("test"+run), "".getBytes(Charsets.UTF_8), StandardOpenOption.CREATE_NEW);
					java.nio.file.Files.write(tempDir.toPath().resolve("test"+run+"b"), "".getBytes(Charsets.UTF_8), StandardOpenOption.CREATE_NEW);
					Thread.sleep(100);
				})
				.mapCheckedException(RuntimeException::new)
				.run();
		}
	});
	
	PathWatcher.watch(tempDir.toPath())
	.every(1, TimeUnit.SECONDS)
	.with(changes -> {
				return changeCounter.addAndGet(changes.size()) > 10;
			});
	
	shouldCreateFiles.set(false);
	fileChanger.get();
	
	System.out.println("DONE");
	System.out.flush();
}
 
开发者ID:flapdoodle-oss,项目名称:de.flapdoodle.solid,代码行数:38,代码来源:PathWatcherTest.java

示例6: getPosition

import java.util.concurrent.Future; //导入方法依赖的package包/类
private IPosition getPosition(IPosition position, List<Future<IPosition>> futures) throws InterruptedException, ExecutionException {
	MapPosition ret = new MapPosition();
    for (Future<IPosition> future : futures) {
	// Faster than using composite
	IPosition pos = future.get();
	if (pos==null) continue;
	ret.putAll(pos);
	ret.putAllIndices(pos);
	}
    if (ret.size()<1) return position;
    return ret;
}
 
开发者ID:eclipse,项目名称:scanning,代码行数:13,代码来源:LevelRunner.java

示例7: asyncGetMulti

import java.util.concurrent.Future; //导入方法依赖的package包/类
/**
 * 从缓存中获取.
 *
 * @param keys keys
 * @return Map<String, Object>
 */
public Map<String, Object> asyncGetMulti(Collection<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;
}
 
开发者ID:NeilRen,项目名称:NEILREN4J,代码行数:17,代码来源:MemcachedManager.java

示例8: doInBackground

import java.util.concurrent.Future; //导入方法依赖的package包/类
@Override
protected MobileDrivingLicense doInBackground(Void... voids) {

    Callable<MobileDrivingLicense> registerTask = new WebAPI.DownloadLicenseTask();
    Future<MobileDrivingLicense> f = service.submit(registerTask);

    MobileDrivingLicense license = null;
    try {
        license = f.get();
    } catch (InterruptedException | ExecutionException e) {
        Log.e(getClass().getName(), e.getMessage(), e);
    }

    return license;
}
 
开发者ID:mDL-ILP,项目名称:mDL-ILP,代码行数:16,代码来源:WebAPI.java

示例9: getBooleanValue

import java.util.concurrent.Future; //导入方法依赖的package包/类
private boolean getBooleanValue(Future<Boolean> f) {
    try {
        Boolean bool = f.get(SpyMemcachedConstants.DEFAULT_TIMEOUT, SpyMemcachedConstants.DEFAULT_TIMEUNIT);
        return bool.booleanValue();
    } catch (Exception e) {
        f.cancel(false);
        return false;
    }
}
 
开发者ID:NeilRen,项目名称:NEILREN4J,代码行数:10,代码来源:MemcachedManager.java

示例10: asyncGet

import java.util.concurrent.Future; //导入方法依赖的package包/类
/**
 * 从缓存中获取.
 *
 * @param key key
 * @return Object
 */
public Object asyncGet(String key) {
    Object obj = null;
    Future<Object> f = memcachedClient.asyncGet(key);
    try {
        obj = f.get(SpyMemcachedConstants.DEFAULT_TIMEOUT, SpyMemcachedConstants.DEFAULT_TIMEUNIT);
    } catch (Exception e) {
        f.cancel(false);
    }
    return obj;
}
 
开发者ID:NeilRen,项目名称:NEILREN4J,代码行数:17,代码来源:MemcachedManager.java

示例11: wachtTotKlaar

import java.util.concurrent.Future; //导入方法依赖的package包/类
private void wachtTotKlaar(List<Future<Object>> futures)
        throws InterruptedException, ExecutionException, TimeoutException {
    for (Future<Object> future : futures) {
        future.get(1, TimeUnit.MINUTES);
    }
}
 
开发者ID:MinBZK,项目名称:OperatieBRP,代码行数:7,代码来源:PersoonCacheProducer.java

示例12: testScheduleRepeatingIntervalsAreRoughlyCorrect

import java.util.concurrent.Future; //导入方法依赖的package包/类
@RandomlyFails // NB-Core-Build #8322: hung
    public void testScheduleRepeatingIntervalsAreRoughlyCorrect() throws Exception {
        int runCount = 5;
        final CountDownLatch latch = new CountDownLatch(runCount);
        final List<Long> intervals = Collections.synchronizedList(new ArrayList<Long> (runCount));
//        long initialDelay = 30000;
//        long period = 20000;
//        long fudgeFactor = 4000;
        long initialDelay = 3000;
        long period = 2000;
        long fudgeFactor = 400;
        long expectedInitialDelay = initialDelay - fudgeFactor;
        long expectedPeriod = period - fudgeFactor;
        class C implements Runnable {
            volatile long start = System.currentTimeMillis();
            private int runCount;
            @Override
            public void run() {
                runCount++;
                try {
                    synchronized(this) {
                        long end = System.currentTimeMillis();
                        intervals.add (end - start);
                        start = end;
                    }
                } finally {
                    latch.countDown();
                }
            }
        }
        C c = new C();
        RequestProcessor rp = new RequestProcessor ("testScheduleRepeating", 5, true);
        try {
            Future<?> f = rp.scheduleWithFixedDelay(c, initialDelay, period, TimeUnit.MILLISECONDS);
    //        latch.await(initialDelay + fudgeFactor + ((runCount - 1) * (period + fudgeFactor)), TimeUnit.MILLISECONDS); //XXX
            latch.await();
            f.cancel(true);
            for (int i= 0; i < Math.min(runCount, intervals.size()); i++) {
                long expect = i == 0 ? expectedInitialDelay : expectedPeriod;
                assertTrue ("Expected at least " + expect + " milliseconds before run " + i + " but was " + intervals.get(i), intervals.get(i) >= expect);
            }
            //Ensure we have really exited
            try {
                f.get();
                fail ("CancellationException should have been thrown");
            } catch (CancellationException e) {}
            assertTrue(f.isCancelled());
            assertTrue(f.isDone());
        } finally {
            rp.stop();
        }
    }
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:53,代码来源:RequestProcessor180386Test.java

示例13: testCancelSaveNamespace

import java.util.concurrent.Future; //导入方法依赖的package包/类
@Test(timeout=20000)
public void testCancelSaveNamespace() throws Exception {
  Configuration conf = getConf();
  NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
  DFSTestUtil.formatNameNode(conf);
  FSNamesystem fsn = FSNamesystem.loadFromDisk(conf);

  // Replace the FSImage with a spy
  final FSImage image = fsn.getFSImage();
  NNStorage storage = image.getStorage();
  storage.close(); // unlock any directories that FSNamesystem's initialization may have locked
  storage.setStorageDirectories(
      FSNamesystem.getNamespaceDirs(conf), 
      FSNamesystem.getNamespaceEditsDirs(conf));

  FSNamesystem spyFsn = spy(fsn);
  final FSNamesystem finalFsn = spyFsn;
  DelayAnswer delayer = new GenericTestUtils.DelayAnswer(LOG);
  BlockIdManager bid = spy(spyFsn.getBlockIdManager());
  Whitebox.setInternalState(finalFsn, "blockIdManager", bid);
  doAnswer(delayer).when(bid).getGenerationStampV2();

  ExecutorService pool = Executors.newFixedThreadPool(2);
  
  try {
    doAnEdit(fsn, 1);
    final Canceler canceler = new Canceler();
    
    // Save namespace
    fsn.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
    try {
      Future<Void> saverFuture = pool.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
          image.saveNamespace(finalFsn, NameNodeFile.IMAGE, canceler);
          return null;
        }
      });

      // Wait until saveNamespace calls getGenerationStamp
      delayer.waitForCall();
      // then cancel the saveNamespace
      Future<Void> cancelFuture = pool.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
          canceler.cancel("cancelled");
          return null;
        }
      });
      // give the cancel call time to run
      Thread.sleep(500);
      
      // allow saveNamespace to proceed - it should check the cancel flag after
      // this point and throw an exception
      delayer.proceed();

      cancelFuture.get();
      saverFuture.get();
      fail("saveNamespace did not fail even though cancelled!");
    } catch (Throwable t) {
      GenericTestUtils.assertExceptionContains(
          "SaveNamespaceCancelledException", t);
    }
    LOG.info("Successfully cancelled a saveNamespace");


    // Check that we have only the original image and not any
    // cruft left over from half-finished images
    FSImageTestUtil.logStorageContents(LOG, storage);
    for (StorageDirectory sd : storage.dirIterable(null)) {
      File curDir = sd.getCurrentDir();
      GenericTestUtils.assertGlobEquals(curDir, "fsimage_.*",
          NNStorage.getImageFileName(0),
          NNStorage.getImageFileName(0) + MD5FileUtils.MD5_SUFFIX);
    }      
  } finally {
    fsn.close();
  }
}
 
开发者ID:naver,项目名称:hadoop,代码行数:80,代码来源:TestSaveNamespace.java

示例14: checkSemantic

import java.util.concurrent.Future; //导入方法依赖的package包/类
protected void checkSemantic(final String relFilePath, final String caretLine) throws Exception {
    Source testSource = getTestSource(getTestFile(relFilePath));

    if (caretLine != null) {
        int caretOffset = getCaretOffset(testSource.createSnapshot().getText().toString(), caretLine);
        enforceCaretOffset(testSource, caretOffset);
    }

    UserTask task = new UserTask() {
        public @Override void run(ResultIterator resultIterator) throws Exception {
            Parser.Result r = resultIterator.getParserResult();
            assertTrue(r instanceof ParserResult);
            ParserResult pr = (ParserResult) r;

            SemanticAnalyzer analyzer = getSemanticAnalyzer();
            assertNotNull("getSemanticAnalyzer must be implemented", analyzer);

            analyzer.run(pr, null);
            Map<OffsetRange, Set<ColoringAttributes>> highlights = analyzer.getHighlights();

            if (highlights == null) {
                highlights = Collections.emptyMap();
            }

            Document doc = GsfUtilities.getDocument(pr.getSnapshot().getSource().getFileObject(), true);
            checkNoOverlaps(highlights.keySet(), doc);

            String annotatedSource = annotateSemanticResults(doc, highlights);
            assertDescriptionMatches(relFilePath, annotatedSource, false, ".semantic");
        }
    };

    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();
        }
    }

}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:43,代码来源:CslTestBase.java

示例15: doTestWriteTimeoutClient

import java.util.concurrent.Future; //导入方法依赖的package包/类
private void doTestWriteTimeoutClient(boolean setTimeoutOnContainer)
        throws Exception {

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(BlockingConfig.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    // Set the async timeout
    if (setTimeoutOnContainer) {
        wsContainer.setAsyncSendTimeout(TIMEOUT_MS);
    }

    tomcat.start();

    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + getHostName() + ":" + getPort() + BlockingConfig.PATH));

    if (!setTimeoutOnContainer) {
        wsSession.getAsyncRemote().setSendTimeout(TIMEOUT_MS);
    }

    long lastSend = 0;

    // Should send quickly until the network buffers fill up and then block
    // until the timeout kicks in
    Exception exception = null;
    try {
        while (true) {
            lastSend = System.currentTimeMillis();
            Future<Void> f = wsSession.getAsyncRemote().sendBinary(
                    ByteBuffer.wrap(MESSAGE_BINARY_4K));
            f.get();
        }
    } catch (Exception e) {
        exception = e;
    }

    long timeout = System.currentTimeMillis() - lastSend;

    // Clear the server side block and prevent further blocks to allow the
    // server to shutdown cleanly
    BlockingPojo.clearBlock();

    // Close the client session, primarily to allow the
    // BackgroundProcessManager to shut down.
    wsSession.close();

    String msg = "Time out was [" + timeout + "] ms";

    // Check correct time passed
    Assert.assertTrue(msg, timeout >= TIMEOUT_MS - MARGIN );

    // Check the timeout wasn't too long
    Assert.assertTrue(msg, timeout < TIMEOUT_MS * 2);

    Assert.assertNotNull(exception);
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:66,代码来源:TestWsWebSocketContainer.java


注:本文中的java.util.concurrent.Future.get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。