Example usage for java.util.concurrent Future get

List of usage examples for java.util.concurrent Future get

Introduction

In this page you can find the example usage for java.util.concurrent Future get.

Prototype

V get() throws InterruptedException, ExecutionException;

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

From source file:biz.fstechnology.micro.common.jms.JmsServiceConnection.java

/**
 * @see biz.fstechnology.micro.common.DefaultServiceConnection#callAsync(biz.fstechnology.micro.common.Request,
 * java.util.function.Consumer)// w  w  w.  j  a  v  a 2s .c  om
 */
@Override
public <T, U> void callAsync(Request<T> request, Consumer<Result<U>> callback) {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Result<U>> rawResponse = executor.submit(() -> call(request));
    executor.submit(() -> {
        try {
            callback.accept(rawResponse.get());
        } catch (Exception e) {
            e.printStackTrace();
            Result<U> result = new Result<>(e);
            callback.accept(result);
        }
    });
    executor.shutdown();
}

From source file:com.echopf.ECHOFile.java

/**
 * {@.en Gets a remote file data.}/*from  w  w w . ja va 2s  . c  o  m*/
 * {@.ja ??????}
 * @throws ECHOException 
 */
public byte[] getRemoteBytes() throws ECHOException {

    // Get ready a background thread
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<byte[]> communicator = new Callable<byte[]>() {
        @Override
        public byte[] call() throws Exception {
            InputStream is = getRemoteInputStream();

            int nRead;
            byte[] data = new byte[16384];
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            buffer.flush();

            return buffer.toByteArray();
        }
    };

    Future<byte[]> future = executor.submit(communicator);

    try {
        return future.get();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt(); // ignore/reset
    } catch (ExecutionException e) {
        Throwable e2 = e.getCause();
        throw new ECHOException(e2);
    }

    return null;
}

From source file:de.zib.gndms.infra.system.DummyTaskActionTest.java

@Test(groups = { "db", "sys", "action", "task" })
public void runFailedDummyAction() throws ExecutionException, InterruptedException, ResourceException {
    synchronized (lock) {
        eraseDatabase();/*  ww w.j a  v  a 2  s . com*/
        runDatabase();
        final EntityManager em = getSys().getEntityManagerFactory().createEntityManager();

        final DummyTaskAction action = new DummyTaskAction(em, createInitialTask(nextUUID()));
        action.setSuccessRate(0.0d);
        final Future<AbstractTask> serializableFuture = getSys().submitAction(action, log);
        assert serializableFuture.get().getState().equals(TaskState.FAILED);
        shutdownDatabase();
    }
}

From source file:com.aerofs.baseline.TestHttpIdInjection.java

@Test
public void shouldHaveChannelIdAndRequestIdInjectedProperly() throws Exception {
    HttpGet get = new HttpGet(ServiceConfiguration.SERVICE_URL + "/consuming");

    Future<HttpResponse> future = client.getClient().execute(get, null);
    HttpResponse response = future.get();

    assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_OK));

    String body = HttpUtils.readResponseEntityToString(response);
    String tokens[] = body.split("-");
    assertThat(tokens.length, equalTo(2));

    // there's a channel id
    assertThat(tokens[0].length(), greaterThan(0));

    // the request id in the body matches the one that's added by the underlying pipeline
    String requestId = tokens[1];
    assertThat(requestId, equalTo(response.getFirstHeader(Headers.REQUEST_TRACING_HEADER).getValue()));
}

From source file:com.sm.connector.client.PartitionClient.java

public T execute(List<RemoteClientImpl> list, int batchSize) {
    logger.info("execute " + filename + " threads " + list.size() + " invoker " + invoker.toString());
    int noOfThread = list.size();
    //List<RemoteClientImpl> list = createClients( urls);
    //CountDownLatch countDownLatch = new CountDownLatch(noOfThread);
    ExecutorService executor = Executors.newFixedThreadPool(noOfThread, new ThreadPoolFactory("Partition"));
    Aggregate<T> aggregate = null;
    try {//from   ww  w.  j a  va 2 s  . c o  m
        aggregate = (Aggregate<T>) QueryUtils.createInstance(tClass);
    } catch (Exception ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
    List<Future<Aggregate<T>>> results = new ArrayList<Future<Aggregate<T>>>(noOfThread);
    for (int i = 0; i < noOfThread; i++) {
        try {
            Aggregate<T> ft = (Aggregate<T>) QueryUtils.createInstance(tClass);
            RunThread runThread = new RunThread(i, list.get(i), batchSize, noOfThread, ft);
            Future<Aggregate<T>> t = executor.submit(runThread);
            results.add(t);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
    for (Future<Aggregate<T>> each : results) {
        try {
            aggregate.aggregate(each.get().get());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
    executor.shutdown();
    return aggregate.get();
}

From source file:com.anrisoftware.prefdialog.miscswing.actions.Actions.java

Actions() {
    this.actions = new HashMap<String, List<ActionEntry>>();
    this.awtActions = new HashMap<String, List<Runnable>>();
    this.actionListener = new PropertyChangeListener() {

        @Override//from   w  w  w . ja v  a  2 s  .c  om
        public void propertyChange(PropertyChangeEvent evt) {
            Future<?> future = (Future<?>) evt.getSource();
            try {
                future.get();
            } catch (InterruptedException e) {
                log.taskInterrupted(future, e);
            } catch (ExecutionException e) {
                log.taskError(future, e.getCause());
            }
        }
    };
}

From source file:dk.nsi.sdm4.ydelse.parser.YdelseParser.java

/**
 * @see Parser#process(java.io.File, String)
 *///from   w  ww.j a v  a2  s . co  m
@Override
public void process(File dataset, String identifier) throws ParserException {
    File file = findSingleFileOrComplain(dataset);
    SLALogItem slaLogItem = slaLogger.createLogItem(getHome() + ".process", "SDM4." + getHome() + ".process");
    slaLogItem.setMessageId(identifier);
    slaLogItem.addCallParameter(Parser.SLA_INPUT_NAME, dataset.getAbsolutePath());

    countNumberOfLines(file);

    long processed = 0;
    Future<Long> insertionFuture = inserter.readFileAndPerformDatabaseOperations(file);
    try {
        processed = insertionFuture.get();
    } catch (InterruptedException e) {
        slaLogItem.setCallResultError("VitaminParser failed - Cause: " + e.getMessage());
        slaLogItem.store();
        throw new RuntimeException(e);
    } catch (ExecutionException e) {
        slaLogItem.setCallResultError("VitaminParser failed - Cause: " + e.getMessage());
        slaLogItem.store();
        throw new ParserException("Unable to perform insertions for " + file.getAbsolutePath(), e);
    }
    slaLogItem.addCallParameter(Parser.SLA_RECORDS_PROCESSED_MAME, "" + processed);
    slaLogItem.setCallResultOk();
    slaLogItem.store();
}

From source file:com.amazonaws.services.kinesis.multilang.MessageReaderTest.java

@Test
public void drainInputTest() throws InterruptedException, ExecutionException {
    String[] sequenceNumbers = new String[] { "123", "456", "789" };
    String[] responseFors = new String[] { "initialize", "processRecords", "processRecords", "shutdown" };
    InputStream stream = buildInputStreamOfGoodInput(sequenceNumbers, responseFors);

    MessageReader reader = new MessageReader().initialize(stream, shardId, new ObjectMapper(),
            Executors.newCachedThreadPool());
    Future<Boolean> drainFuture = reader.drainSTDOUT();
    Boolean drainResult = drainFuture.get();
    Assert.assertNotNull(drainResult);/*  w w  w.  j a v  a2  s. c om*/
    Assert.assertTrue(drainResult);
}

From source file:com.clustercontrol.monitor.util.ScopeSearchRunUtil.java

@SuppressWarnings("unchecked")
public ArrayList<ArrayList<Object>> searchInfo(List<String> managerList) {

    ArrayList<ArrayList<Object>> dispList = new ArrayList<ArrayList<Object>>();

    Map<String, String> errMsgs = new ConcurrentHashMap<>();
    long start = System.currentTimeMillis();

    try {/*  w w w.j  a v a2 s  .c  o  m*/
        String threadName = Thread.currentThread().getName() + "-ScopeSearch";
        List<RepositorySearchTask> searchList = new ArrayList<RepositorySearchTask>();
        for (String managerName : managerList) {
            RepositorySearchTask task = null;
            task = new RepositorySearchTask(threadName, managerName, ContextProvider.getContext());
            searchList.add(task);
        }

        List<Future<Map<String, List<?>>>> retList = getExecutorService().invokeAll(searchList);

        for (Future<Map<String, List<?>>> future : retList) {
            if (future == null || future.get() == null) {
                continue;
            }
            Map<String, List<?>> map = future.get();
            for (Map.Entry<String, List<?>> entry : map.entrySet()) {
                //?1??
                String managerName = entry.getKey();
                List<?> ret = entry.getValue();
                if (ret.get(POS_INFO) != null && ret.get(POS_INFO) instanceof ArrayList) {
                    ArrayList<ArrayList<Object>> infoList = (ArrayList<ArrayList<Object>>) ret.get(POS_INFO);
                    for (ArrayList<Object> l : infoList) {
                        dispList.add(l);
                    }
                }

                if (ret.get(POS_ERROR) != null && ret.get(POS_ERROR) instanceof String) {
                    errMsgs.put(managerName, (String) ret.get(POS_ERROR));
                }
            }
        }
    } catch (InterruptedException e) {
        m_log.error(e.getMessage());
    } catch (ExecutionException e) {
        m_log.error(e.getMessage());
    }

    //
    if (0 < errMsgs.size()) {
        UIManager.showMessageBox(errMsgs, true);
    }

    long end = System.currentTimeMillis();
    m_log.debug("time=" + (end - start));
    return dispList;
}

From source file:com.github.trask.sandbox.mail.AmazonMailServiceTest.java

@Test
public void shouldThrowException() throws Exception {
    // given//from w ww. j ava 2s . c  o m
    MailService mailService = new AmazonMailService("fail", "fail", executorService);
    String from = "unit.test.from@example.com";
    String to = "unit.test.to@example.com";
    String subject = getClass().getSimpleName();
    String htmlBody = "<html><body>click <a href=\"http://google.com\">here</a>";
    String textBody = "go to http://google.com";

    // when
    Future<Void> future = mailService.sendMail(from, to, subject, htmlBody, textBody);
    boolean exceptionThrown = false;
    try {
        future.get();
    } catch (Exception e) {
        // TODO be more specific about exception
        exceptionThrown = true;
    }

    // then
    assertThat(exceptionThrown, is(true));
}