java.util.concurrent.Future#get ( )源码实例Demo

下面列出了java.util.concurrent.Future#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: netbeans   文件: CommandRestInstanceTest.java
/**
 * Test GlasFish create standalone instance command via REST.
 */
@Test(groups = {"rest-commands"})
public void createStandaloneInstanceTest() {
    PayaraServer server = payaraServer();
    Command command = new CommandCreateInstance(STANDALONE_INSTANCE, null,
            TestDomainV4Constants.NODE_NAME);
    try {
        Future<ResultString> future =
                ServerAdmin.<ResultString>exec(server, command);
        try {
            ResultString result = future.get();
            //assertNotNull(result.getValue());
            assertEquals(result.state, TaskState.COMPLETED);
        } catch (    InterruptedException | ExecutionException ie) {
            fail("CommandCreateInstance command execution failed: " + ie.getMessage());
        }
    } catch (PayaraIdeException gfie) {
        fail("CommandCreateInstance command execution failed: " + gfie.getMessage());
    }
}
 
@Override
protected void afterExecute(Runnable r, Throwable t) {
    super.afterExecute(r, t);
    if (t == null && r instanceof Future<?>) {
        try {
            final Future<?> f = (Future<?>) r;
            if (f.isDone()) {
                f.get();
            }
        } catch (final CancellationException ce) {
            // ignored
        } catch (final ExecutionException ee) {
            t = ee.getCause();
        } catch (final InterruptedException ie) {
            Thread.currentThread().interrupt(); // ignore/reset
        }
    }
    if (t != null) {
        LOG.error("Uncaught exception in pool: {}, {}.", this.name, super.toString(), t);
    }
}
 
源代码3 项目: spring-boot-demo   文件: TaskFactoryTest.java
/**
 * 测试异步任务
 */
@Test
public void asyncTaskTest() throws InterruptedException, ExecutionException {
    long start = System.currentTimeMillis();
    Future<Boolean> asyncTask1 = task.asyncTask1();
    Future<Boolean> asyncTask2 = task.asyncTask2();
    Future<Boolean> asyncTask3 = task.asyncTask3();

    // 调用 get() 阻塞主线程
    asyncTask1.get();
    asyncTask2.get();
    asyncTask3.get();
    long end = System.currentTimeMillis();

    log.info("异步任务全部执行结束,总耗时:{} 毫秒", (end - start));
}
 
源代码4 项目: netbeans   文件: CommandHttpTest.java
/**
 * Test cleanup
 * 
 */
@AfterGroups(groups = {"http-commands"})
public static void stopPayara() {
    final String METHOD = "stopPayara";
    LOGGER.log(Level.INFO, METHOD, "stopFrame");
    LOGGER.log(Level.INFO, METHOD, "stopText");
    LOGGER.log(Level.INFO, METHOD, "stopFrame");
    PayaraServer server = payaraServer();
    Command command = new CommandStopDAS();
    try {
        Future<ResultString> future = 
                ServerAdmin.<ResultString>exec(server, command);
        try {
            ResultString result = future.get();
            gfStdOut.close();
            gfStdErr.close();
            assertNotNull(result.getValue());
            assertTrue(result.getState() == TaskState.COMPLETED);
        } catch (InterruptedException | ExecutionException ie) {
            fail("Version command execution failed: " + ie.getMessage());
        }
    } catch (PayaraIdeException gfie) {
        fail("Version command execution failed: " + gfie.getMessage());
    }
}
 
源代码5 项目: netbeans   文件: VanillaCompileWorker.java
private static void fallbackCopyExistingClassFiles(final Context context,
                                               final JavaParsingContext javaContext,
                                               final Collection<? extends CompileTuple> files) {
//fallback: copy output classes to caches, so that editing is not extremely slow/broken:
BinaryForSourceQuery.Result res2 = BinaryForSourceQuery.findBinaryRoots(context.getRootURI());
Set<String> filter;
if (!context.isAllFilesIndexing()) {
    filter = new HashSet<>();
    for (CompileTuple toIndex : files) {
        String path = toIndex.indexable.getRelativePath();
        filter.add(path.substring(0, path.lastIndexOf(".")));
    }
} else {
    filter = null;
}
try {
    final Future<Void> done = FileManagerTransaction.runConcurrent(() -> {
        File cache = JavaIndex.getClassFolder(context.getRootURI(), false, false);
        for (URL u : res2.getRoots()) {
            FileObject binaryFO = URLMapper.findFileObject(u);
            if (binaryFO == null)
                continue;
            FileManagerTransaction fmtx = TransactionContext.get().get(FileManagerTransaction.class);
            List<File> copied = new ArrayList<>();
            copyRecursively(binaryFO, cache, cache, filter, fmtx, copied);
            final ClassIndexImpl cii = javaContext.getClassIndexImpl();
            if (cii != null) {
                cii.getBinaryAnalyser().analyse(context, cache, copied);
            }
        }
    });
    done.get();
} catch (IOException | InterruptedException | ExecutionException ex) {
    Exceptions.printStackTrace(ex);
}
}
 
源代码6 项目: kylin-on-parquet-v2   文件: MemcachedCache.java
public void clear() {
    logger.warn("Clear Remote Cache!");
    Future<Boolean> resultFuture = client.flush();
    try {
        boolean result = resultFuture.get();
        logger.warn("Clear Remote Cache returned with result: " + result);
    } catch (Exception e) {
        logger.warn("Can't clear Remote Cache.", e);
    }
}
 
@Test
public void submitFailingCallableWithErrorHandler() throws Exception {
	TestCallable task = new TestCallable(0);
	TestErrorHandler errorHandler = new TestErrorHandler(1);
	scheduler.setErrorHandler(errorHandler);
	Future<String> future = scheduler.submit(task);
	Object result = future.get(1000, TimeUnit.MILLISECONDS);
	assertTrue(future.isDone());
	assertNull(result);
	assertNotNull(errorHandler.lastError);
}
 
@Test
public void connectSubscribeRequestWriteFlushClose() throws Exception {
    toSource(cpw.connect()).subscribe(subscriber);
    assertThat(subscriber.takeItems(), is(empty()));
    subscriber.request(1);
    Future<?> f = executorService.submit(toRunnable(() -> {
        cpw.write("foo");
        cpw.flush();
        cpw.close();
    }));
    f.get();
    assertThat(subscriber.takeItems(), contains("foo"));
    assertThat(subscriber.takeTerminal(), is(complete()));
}
 
源代码9 项目: EasyTransaction   文件: OrderService.java
@Transactional("buySthTransactionManager")
public void buySomethingCascading(int userId,long money, boolean enableFescarTest){
	
	JdbcTemplate jdbcTemplate = util.getJdbcTemplate(Constant.APPID, BUSINESS_CODE_CASCADE, userId);
	Integer id = saveOrderRecord(jdbcTemplate,userId,money);

	transaction.startEasyTrans(BUSINESS_CODE_CASCADE, id);
	
	/**
	 * 调用级联事务
	 */
	WalletPayCascadeTccMethodRequest deductRequest = new WalletPayCascadeTccMethodRequest();
	deductRequest.setUserId(userId);
	deductRequest.setPayAmount(money);
	deductRequest.setUseCoupon(enableFescarTest);
	Future<WalletPayTccMethodResult> execute = transaction.execute(deductRequest);
	
	
	try {
		//主动获取一下结果,触发真正的远程调用
		execute.get();
	} catch (InterruptedException | ExecutionException e1) {
		e1.printStackTrace();
	}
	
	//在事务结束后主动停止若干秒,用于等待远端事务缓存过期,以测试该场景
	if(cascadeTrxFinishedSleepMills > 0){
		try {
			Thread.sleep(cascadeTrxFinishedSleepMills);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
 
@Test
public void submitCallable() throws Exception {
	TestCallable task = new TestCallable(1);
	Future<String> future = executor.submit(task);
	String result = future.get(1000, TimeUnit.MILLISECONDS);
	assertEquals(THREAD_NAME_PREFIX, result.substring(0, THREAD_NAME_PREFIX.length()));
}
 
private ExecutionResult result(Future<ExecutionResult> future) {
	try {
		return future.get();
	}
	catch (Exception e) {
		throw new IllegalStateException(e);
	}
}
 
/**
 * Wait for the requested {@link XBeeEvent} to occur
 *
 * @param eventClass the {@link XBeeEvent} to wait for
 * @return the {@link XBeeEvent} once received, or null on exception
 */
public XBeeEvent eventWait(final Class<?> eventClass) {
    Future<XBeeEvent> future = waitEventAsync(eventClass);
    try {
        return future.get(commandTimeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        logger.debug("XBee interrupted in eventWait {}", eventClass);
        future.cancel(true);
        return null;
    }
}
 
@Test
public void scheduleTriggerTask() throws Exception {
	TestTask task = new TestTask(3);
	Future<?> future = scheduler.schedule(task, new TestTrigger(3));
	Object result = future.get(1000, TimeUnit.MILLISECONDS);
	assertNull(result);
	await(task);
	assertThreadNamePrefix(task);
}
 
源代码14 项目: servicetalk   文件: HttpsProxyTest.java
@Test
public void testBadProxyResponse() throws Exception {
    handler = (socket, in, initialLine) -> {
        socket.getOutputStream().write("HTTP/1.1 500 Internal Server Error\r\n\r\n".getBytes(UTF_8));
        socket.getOutputStream().flush();
    };

    final Future<HttpResponse> httpResponseFuture = client.request(client.get("/path")).toFuture();

    expected.expect(ExecutionException.class);
    expected.expectCause(Matchers.instanceOf(ProxyResponseException.class));
    httpResponseFuture.get();
}
 
源代码15 项目: jstarcraft-ai   文件: MatrixUtilityTestCase.java
/**
 * 测试矩阵转置乘法
 */
@Test
public void testTransposeProduct() throws Exception {
    EnvironmentContext context = EnvironmentFactory.getContext();
    Future<?> task = context.doTask(() -> {
        DenseMatrix matrix = DenseMatrix.valueOf(4, 3);
        matrix.iterateElement(MathCalculator.SERIAL, (scalar) -> {
            scalar.setValue(probability.sample().floatValue());
        });

        System.out.println("print matrix Matrix:");
        System.out.println(matrix.toString());

        Table<Integer, Integer, Float> dataTable = HashBasedTable.create();
        dataTable.put(0, 0, RandomUtility.randomFloat(1F));
        dataTable.put(0, 1, RandomUtility.randomFloat(1F));
        dataTable.put(0, 3, RandomUtility.randomFloat(1F));
        dataTable.put(1, 0, RandomUtility.randomFloat(1F));
        dataTable.put(2, 0, RandomUtility.randomFloat(1F));
        dataTable.put(2, 1, RandomUtility.randomFloat(1F));
        dataTable.put(3, 1, RandomUtility.randomFloat(1F));
        dataTable.put(3, 3, RandomUtility.randomFloat(1F));
        // 稀疏矩阵
        SparseMatrix sparse = SparseMatrix.valueOf(4, 4, dataTable);
        // 稠密矩阵
        DenseMatrix dense = DenseMatrix.valueOf(4, 4);
        for (MatrixScalar term : sparse) {
            int row = term.getRow();
            int column = term.getColumn();
            float value = term.getValue();
            dense.setValue(row, column, value);
        }
        DenseMatrix transpose = DenseMatrix.valueOf(matrix.getColumnSize(), dense.getRowSize());
        DenseMatrix left = DenseMatrix.valueOf(matrix.getColumnSize(), dense.getColumnSize());
        DenseMatrix right = DenseMatrix.valueOf(matrix.getColumnSize(), dense.getColumnSize());
        Assert.assertThat(left.dotProduct(matrix, true, dense, false, MathCalculator.SERIAL), CoreMatchers.equalTo(right.dotProduct(transpose.copyMatrix(matrix, true), false, dense, false, MathCalculator.SERIAL)));
        Assert.assertThat(left.dotProduct(matrix, true, sparse, false, MathCalculator.SERIAL), CoreMatchers.equalTo(right.dotProduct(transpose.copyMatrix(matrix, true), false, dense, false, MathCalculator.SERIAL)));
        left.dotProduct(matrix, true, sparse, false, MathCalculator.SERIAL);
        Assert.assertThat(left, CoreMatchers.equalTo(right));
        right.dotProduct(matrix, true, dense, false, MathCalculator.SERIAL);
        Assert.assertThat(right, CoreMatchers.equalTo(left));
    });
    task.get();
}
 
@Test
public void put() throws Exception  {
	HttpEntity<String> requestEntity = new HttpEntity<>(helloWorld);
	Future<?> responseEntityFuture = template.put(baseUrl + "/{method}", requestEntity, "put");
	responseEntityFuture.get();
}
 
@Test
public void testWebsocketSubscription() throws Exception {
    /*
     * Create subscription
     */
    Subscription subscription = new Subscription();
    subscription.setReason("Monitor new neonatal function (note, age will be determined by the monitor)");
    subscription.setStatus(Subscription.SubscriptionStatus.REQUESTED);
    subscription.setCriteria("Observation?status=final");

    Subscription.SubscriptionChannelComponent channel = new Subscription.SubscriptionChannelComponent();
    channel.setType(Subscription.SubscriptionChannelType.WEBSOCKET);
    channel.setPayload("application/json");
    subscription.setChannel(channel);

    MethodOutcome methodOutcome = ourClient.create().resource(subscription).execute();
    IIdType mySubscriptionId = methodOutcome.getId();

    // Wait for the subscription to be activated
    waitForSize(1, () -> ourClient.search().forResource(Subscription.class).where(Subscription.STATUS.exactly().code("active")).cacheControl(new CacheControlDirective().setNoCache(true)).returnBundle(Bundle.class).execute().getEntry().size());

    /*
     * Attach websocket
     */

    WebSocketClient myWebSocketClient = new WebSocketClient();
    SocketImplementation mySocketImplementation = new SocketImplementation(mySubscriptionId.getIdPart(), EncodingEnum.JSON);

    myWebSocketClient.start();
    URI echoUri = new URI("ws://localhost:" + ourPort + "/hapi-fhir-jpaserver/websocket");
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    ourLog.info("Connecting to : {}", echoUri);
    Future<Session> connection = myWebSocketClient.connect(mySocketImplementation, echoUri, request);
    Session session = connection.get(2, TimeUnit.SECONDS);

    ourLog.info("Connected to WS: {}", session.isOpen());

    /*
     * Create a matching resource
     */
    Observation obs = new Observation();
    obs.setStatus(Observation.ObservationStatus.FINAL);
    ourClient.create().resource(obs).execute();

    // Give some time for the subscription to deliver
    Thread.sleep(2000);

    /*
     * Ensure that we receive a ping on the websocket
     */
    waitForSize(1, () -> mySocketImplementation.myPingCount);

    /*
     * Clean up
     */
    ourClient.delete().resourceById(mySubscriptionId).execute();
}
 
源代码18 项目: tessera   文件: EnclaveExecManager.java
@Override
public Process doStart() throws Exception {

    final Path enclaveServerJar =
            Paths.get(
                    System.getProperty(
                            "enclave.jaxrs.server.jar",
                            "../../enclave/enclave-jaxrs/target/enclave-jaxrs-0.9-SNAPSHOT-server.jar"));

    final ServerConfig serverConfig = configDescriptor.getEnclaveConfig().get().getServerConfigs().get(0);

    ExecArgsBuilder execArgsBuilder = new ExecArgsBuilder();

    final List<String> cmd =
            execArgsBuilder
                    .withPidFile(pid)
                    .withJvmArg("-Dnode.number=" + nodeId)
                    .withJvmArg("-Dlogback.configurationFile=" + logbackConfigFile)
                    .withStartScriptOrExecutableJarFile(enclaveServerJar)
                    .withConfigFile(configDescriptor.getEnclavePath())
                    .build();

    LOGGER.info("Starting enclave {}", configDescriptor.getAlias());

    String javaOpts =
            "-Dnode.number="
                    .concat(nodeId)
                    .concat(" ")
                    .concat("-Dlogback.configurationFile=")
                    .concat(logbackConfigFile.toString());

    Map<String, String> env = new HashMap<>();
    env.put("JAVA_OPTS", javaOpts);

    LOGGER.info("Set env JAVA_OPTS {}", javaOpts);

    Process process = ExecUtils.start(cmd, executorService, env);

    ServerStatusCheckExecutor serverStatusCheckExecutor =
            new ServerStatusCheckExecutor(ServerStatusCheck.create(serverConfig));

    Future<Boolean> future = executorService.submit(serverStatusCheckExecutor);

    Boolean result = future.get(3, TimeUnit.MINUTES);

    if (!result) {
        throw new IllegalStateException("Enclave server not started");
    }

    LOGGER.info("Started enclave {}", configDescriptor.getAlias());

    return process;
}
 
源代码19 项目: systemds   文件: WriterBinaryBlockParallel.java
@Override
protected void writeBinaryBlockMatrixToHDFS( Path path, JobConf job, FileSystem fs, MatrixBlock src, long rlen, long clen, int blen )
	throws IOException, DMLRuntimeException
{
	//estimate output size and number of output blocks (min 1)
	int numPartFiles = (int)(OptimizerUtils.estimatePartitionedSizeExactSparsity(rlen, clen, 
			blen, src.getNonZeros()) / InfrastructureAnalyzer.getHDFSBlockSize());
	numPartFiles = Math.max(numPartFiles, 1);
	
	//determine degree of parallelism
	int numThreads = OptimizerUtils.getParallelBinaryWriteParallelism();
	numThreads = Math.min(numThreads, numPartFiles);
	
	//fall back to sequential write if dop is 1 (e.g., <128MB) in order to create single file
	if( numThreads <= 1 ) {
		super.writeBinaryBlockMatrixToHDFS(path, job, fs, src, rlen, clen, blen);
		return;
	}

	//create directory for concurrent tasks
	HDFSTool.createDirIfNotExistOnHDFS(path, DMLConfig.DEFAULT_SHARED_DIR_PERMISSION);
	
	//create and execute write tasks
	try 
	{
		ExecutorService pool = CommonThreadPool.get(numThreads);
		ArrayList<WriteFileTask> tasks = new ArrayList<>();
		int blklen = (int)Math.ceil((double)rlen / blen / numThreads) * blen;
		for(int i=0; i<numThreads & i*blklen<rlen; i++) {
			Path newPath = new Path(path, IOUtilFunctions.getPartFileName(i));
			tasks.add(new WriteFileTask(newPath, job, fs, src, i*blklen, Math.min((i+1)*blklen, rlen), blen));
		}

		//wait until all tasks have been executed
		List<Future<Object>> rt = pool.invokeAll(tasks);	
		pool.shutdown();
		
		//check for exceptions 
		for( Future<Object> task : rt )
			task.get();
		
		// delete crc files if written to local file system
		if (fs instanceof LocalFileSystem) {
			for(int i=0; i<numThreads & i*blklen<rlen; i++) 
				IOUtilFunctions.deleteCrcFilesFromLocalFileSystem(fs,
					new Path(path, IOUtilFunctions.getPartFileName(i)));
		}
	} 
	catch (Exception e) {
		throw new IOException("Failed parallel write of binary block input.", e);
	}
}
 
源代码20 项目: Bats   文件: StramWebServices.java
@POST // not supported by WebAppProxyServlet, can only be called directly
@Path(PATH_LOGICAL_PLAN)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public JSONObject logicalPlanModification(JSONObject request)
{
  init();
  JSONObject response = new JSONObject();
  try {
    JSONArray jsonArray = request.getJSONArray("requests");
    List<LogicalPlanRequest> requests = new ArrayList<>();
    for (int i = 0; i < jsonArray.length(); i++) {
      JSONObject jsonObj = (JSONObject)jsonArray.get(i);
      LogicalPlanRequest requestObj = (LogicalPlanRequest)Class.forName(LogicalPlanRequest.class.getPackage().getName() + "." + jsonObj.getString("requestType")).newInstance();
      @SuppressWarnings("unchecked")
      Map<String, String> properties = BeanUtils.describe(requestObj);
      @SuppressWarnings("unchecked")
      Iterator<String> keys = jsonObj.keys();

      while (keys.hasNext()) {
        String key = keys.next();
        if (!key.equals("requestType")) {
          properties.put(key, jsonObj.get(key).toString());
        }
      }
      BeanUtils.populate(requestObj, properties);
      requests.add(requestObj);
    }
    Future<?> fr = dagManager.logicalPlanModification(requests);
    fr.get(3000, TimeUnit.MILLISECONDS);
  } catch (Exception ex) {
    LOG.error("Error processing plan change", ex);
    try {
      if (ex instanceof ExecutionException) {
        response.put("error", ex.getCause().toString());
      } else {
        response.put("error", ex.toString());
      }
    } catch (Exception e) {
      // ignore
    }
  }

  return response;
}