Java Code Examples for java.util.concurrent.Future#get()

The following examples show how to use java.util.concurrent.Future#get() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * 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());
    }
}
 
Example 2
@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);
    }
}
 
Example 3
Source Project: spring-boot-demo   File: TaskFactoryTest.java    License: MIT License 6 votes vote down vote up
/**
 * 测试异步任务
 */
@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));
}
 
Example 4
Source Project: netbeans   File: CommandHttpTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example 5
Source Project: netbeans   File: VanillaCompileWorker.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
}
 
Example 6
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);
    }
}
 
Example 7
@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);
}
 
Example 8
@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()));
}
 
Example 9
Source Project: EasyTransaction   File: OrderService.java    License: Apache License 2.0 5 votes vote down vote up
@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();
		}
	}

}
 
Example 10
@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()));
}
 
Example 11
private ExecutionResult result(Future<ExecutionResult> future) {
	try {
		return future.get();
	}
	catch (Exception e) {
		throw new IllegalStateException(e);
	}
}
 
Example 12
/**
 * 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;
    }
}
 
Example 13
@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);
}
 
Example 14
Source Project: servicetalk   File: HttpsProxyTest.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 15
/**
 * 测试矩阵转置乘法
 */
@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();
}
 
Example 16
@Test
public void put() throws Exception  {
	HttpEntity<String> requestEntity = new HttpEntity<>(helloWorld);
	Future<?> responseEntityFuture = template.put(baseUrl + "/{method}", requestEntity, "put");
	responseEntityFuture.get();
}
 
Example 17
@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();
}
 
Example 18
Source Project: tessera   File: EnclaveExecManager.java    License: Apache License 2.0 4 votes vote down vote up
@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;
}
 
Example 19
@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);
	}
}
 
Example 20
Source Project: Bats   File: StramWebServices.java    License: Apache License 2.0 4 votes vote down vote up
@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;
}