Example usage for java.util.concurrent Callable Callable

List of usage examples for java.util.concurrent Callable Callable

Introduction

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

Prototype

Callable

Source Link

Usage

From source file:com.aol.advertising.qiao.agent.DataFunnel.java

private void _registerStatsCollector() {
    if (statsCollector != null) {
        statsCollector.register(new Callable<Void>() {
            @Override//from  w  ww.j  a  va2s  .c  o  m
            public Void call() {
                long inputs = dataPipe.getAndResetNumWrites();
                if (inputs > 0) {
                    statsStore.incr(StatsEnum.EVENT_INPUT_COUNT.value(), inputs);
                }

                long outputs = dataPipe.getAndResetNumReads();
                if (outputs > 0) {
                    statsStore.incr(StatsEnum.PROCESSED_COUNT.value(), outputs);
                }

                return null;
            }

        });
    }

}

From source file:io.fabric8.kit.common.ExternalCommand.java

private Future<IOException> startStreamPump(final InputStream errorStream) {
    return executor.submit(new Callable<IOException>() {
        @Override// ww w. ja  v a2s .  c o m
        public IOException call() {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));) {
                for (;;) {
                    String line = reader.readLine();
                    if (line == null) {
                        break;
                    }
                    synchronized (log) {
                        log.warn(line);
                    }
                }
                return null;
            } catch (IOException e) {
                return e;
            }
        }
    });
}

From source file:io.neba.core.resourcemodels.caching.RequestScopedResourceModelCacheTest.java

@Test
public void testCacheIsNotSuffixSensitiveWithoutSafeMode() throws Exception {
    request(new Callable<Object>() {
        @Override//www .ja  v a2 s.c  o  m
        public Object call() throws Exception {

            withResourcePath("/junit/test/1");
            putModelInCache();
            lookupModelFromCache();
            assertModelWasFoundInCache();

            withSuffix("/newSuffix");

            lookupModelFromCache();
            assertModelWasFoundInCache();
            return null;
        }
    });
}

From source file:com.microsoft.azure.management.compute.VirtualMachineImageOperationsImpl.java

/**
* Gets a virtual machine image.//from w w w . j  a v a  2s.co  m
*
* @param parameters Optional.
* @return The get vm image operation response.
*/
@Override
public Future<VirtualMachineImageGetResponse> getAsync(final VirtualMachineImageGetParameters parameters) {
    return this.getClient().getExecutorService().submit(new Callable<VirtualMachineImageGetResponse>() {
        @Override
        public VirtualMachineImageGetResponse call() throws Exception {
            return get(parameters);
        }
    });
}

From source file:com.rapidminer.operator.learner.tree.SelectionCreator.java

/**
 * Creates in parallel an example index start selection for each numerical attribute, or if
 * there is none, only one.// w ww .  ja  v a  2 s .c om
 *
 * @param operator
 *            the operator for which the calculation is done
 * @return a map containing for each numerical attribute an example index array such that the
 *         associated attribute values are in ascending order.
 * @throws OperatorException
 */
public Map<Integer, int[]> getStartSelectionParallel(Operator operator) throws OperatorException {
    Map<Integer, int[]> selection = new HashMap<>();
    if (columnTable.getNumberOfRegularNumericalAttributes() == 0) {
        selection.put(0, createFullArray(columnTable.getNumberOfExamples()));
    } else {
        List<Callable<int[]>> tasks = new ArrayList<Callable<int[]>>();
        final Integer[] bigSelectionArray = createFullBigArray(columnTable.getNumberOfExamples());
        for (int j = columnTable.getNumberOfRegularNominalAttributes(); j < columnTable
                .getTotalNumberOfRegularAttributes(); j++) {
            final double[] attributeColumn = columnTable.getNumericalAttributeColumn(j);
            tasks.add(new Callable<int[]>() {

                @Override
                public int[] call() {
                    Integer[] startSelection = Arrays.copyOf(bigSelectionArray, bigSelectionArray.length);
                    Arrays.sort(startSelection, new Comparator<Integer>() {

                        @Override
                        public int compare(Integer a, Integer b) {
                            return Double.compare(attributeColumn[a], attributeColumn[b]);
                        }
                    });
                    return ArrayUtils.toPrimitive(startSelection);
                }

            });
        }

        List<int[]> results = null;
        try {
            results = Resources.getConcurrencyContext(operator).call(tasks);
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof RuntimeException) {
                throw (RuntimeException) cause;
            } else if (cause instanceof Error) {
                throw (Error) cause;
            } else {
                throw new OperatorException(cause.getMessage(), cause);
            }
        }

        for (int j = columnTable.getNumberOfRegularNominalAttributes(); j < columnTable
                .getTotalNumberOfRegularAttributes(); j++) {
            selection.put(j, results.get(j - columnTable.getNumberOfRegularNominalAttributes()));
        }
    }
    return selection;
}

From source file:cherry.foundation.mail.SendMailBatchTest.java

@Test
public void testInterrupt() throws Exception {

    final File shutdownTrigger = new File("./shutdownTrigger.txt");
    shutdownTrigger.deleteOnExit();//from www .ja  va  2s  .com
    Callable<Boolean> callable = new Callable<Boolean>() {
        @Override
        public Boolean call() {
            try (FileOutputStream os = new FileOutputStream(shutdownTrigger)) {
                return true;
            } catch (IOException ex) {
                return false;
            }
        }
    };

    ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
    ScheduledFuture<Boolean> future = service.schedule(callable, 5L, TimeUnit.SECONDS);
    final Thread currentThread = Thread.currentThread();
    ScheduledFuture<Boolean> interrupt = service.schedule(new Callable<Boolean>() {
        @Override
        public Boolean call() {
            currentThread.interrupt();
            return true;
        }
    }, 2L, TimeUnit.SECONDS);

    SendMailBatch batch = create(1000L, shutdownTrigger, false);
    ExitStatus status = batch.execute();

    assertEquals(ExitStatus.NORMAL, status);
    assertTrue(future.get().booleanValue());
    assertTrue(interrupt.get().booleanValue());
    assertFalse(shutdownTrigger.exists());

    verify(bizDateTime, atLeastOnce()).now();
    verify(mailSendHandler, atLeastOnce()).listMessage((LocalDateTime) eq(null));
    verify(mailSendHandler, atLeastOnce()).sendMessage(eq(1L));
    verify(mailSendHandler, atLeastOnce()).sendMessage(eq(2L));
    verify(mailSendHandler, atLeastOnce()).sendMessage(eq(3L));
}

From source file:com.spotify.helios.ZooKeeperTestingClusterManager.java

@Override
public void awaitUp(long timeout, TimeUnit timeunit) throws TimeoutException {
    Polling.awaitUnchecked(timeout, timeunit, new Callable<Object>() {
        @Override//from w w  w.ja  v  a  2  s .c  o  m
        public Object call() throws Exception {
            try {
                return curatorWithSuperAuth().getChildren().forPath("/");
            } catch (Exception e) {
                return null;
            }
        }
    });
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.SessionDaoImplTest.java

@Test
public void testCreateSessionURLThenDeletingSession() {
    //create a session with id SESSION_ID
    this.execute(new Callable<Object>() {
        @Override/*from w w w .  j ava  2s. c  o m*/
        public Object call() {
            BlackboardSessionResponse sessionResponse = generateSessionResponse();

            final Session session = sessionDao.createSession(sessionResponse, "http://www.example.com/session");
            assertNotNull(session);

            verifyCreatedSession();
            verifyCreatedUsers();

            final ConferenceUser user = conferenceUserDao.getUserByUniqueId("admin@example.com");
            assertNotNull(user);
            UserSessionUrl url = userSessionUrlDao.createUserSessionUrl(session, user,
                    "http://www.example.com/aliens");
            assertNotNull(url);

            return null;
        }
    });

    //Create url and link it to the session
    this.execute(new Callable<Object>() {
        @Override
        public Object call() {
            final Session session = sessionDao.getSessionByBlackboardId(SESSION_ID);
            assertNotNull(session);

            sessionDao.deleteSession(session);

            return null;
        }
    });
}

From source file:at.alladin.rmbt.client.v2.task.HttpProxyTask.java

public QoSTestResult call() throws Exception {
    final QoSTestResult result = initQoSTestResult(QoSTestResultEnum.HTTP_PROXY);
    try {// w w  w  . ja  va  2 s  . c  om
        onStart(result);

        Future<QoSTestResult> httpTimeoutTask = RMBTClient.getCommonThreadPool()
                .submit(new Callable<QoSTestResult>() {

                    public QoSTestResult call() throws Exception {
                        httpGet(result);
                        return result;
                    }

                });

        final QoSTestResult testResult = httpTimeoutTask.get((int) (downloadTimeout / 1000000),
                TimeUnit.SECONDS);
        return testResult;
    } catch (TimeoutException e) {
        e.printStackTrace();
        result.getResultMap().put(RESULT_HASH, "TIMEOUT");
    } catch (Exception e) {
        throw e;
    } finally {
        onEnd(result);
    }

    return result;
}

From source file:com.basho.riak.client.http.util.logging.ConcurrentLoggingTest.java

/**
 * Test method for//ww  w.  ja  v  a  2  s.  c  om
 * {@link com.basho.riak.client.http.util.logging.LogNoHttpResponseRetryHandler#retryMethod(org.apache.commons.httpclient.HttpMethod, java.io.IOException, int)}
 * .
 * 
 * @throws InterruptedException
 */
@Test
public void retry_concurrentLogAndDump() throws InterruptedException {
    // create a bunch of threads
    // each must log 10 statements and call flush
    // ALL the statements must be present BUT ONCE in
    // the mock delegate appender (order does not matter)
    final int numThreads = 10;
    final LogNoHttpResponseRetryHandler handler = new LogNoHttpResponseRetryHandler();
    ExecutorService es = Executors.newFixedThreadPool(numThreads);
    List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(numThreads);

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch dumpLatch = new CountDownLatch(10);

    for (int i = 0; i < numThreads; i++) {
        final int threadCounter = i;
        tasks.add(new Callable<Void>() {

            @Override
            public Void call() {
                Logger logger = Logger.getLogger("httpclient.wire");
                try {
                    startLatch.await();

                    for (int j = 0; j < 10; j++) {
                        logger.debug(String.format(MESSAGE, new Object[] { threadCounter, j }));
                    }

                    dumpLatch.countDown();
                    dumpLatch.await();

                    handler.retryMethod(new GetMethod(), new NoHttpResponseException(), 0);

                    return null;
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException(e);
                }
            }
        });
    }

    startLatch.countDown();
    es.invokeAll(tasks);

    verify(mockLogger, times(100)).callAppenders(logEventCaptor.capture());

    TreeSet<Integer> check = new TreeSet<Integer>();

    for (LoggingEvent le : logEventCaptor.getAllValues()) {
        // verify that each of Thread:Iter is present for 0-90-9
        int loc = Integer.parseInt(le.getMessage().toString());
        check.add(loc);
    }

    assertEquals(100, check.size());
    assertEquals(0, (int) check.first());
    assertEquals(99, (int) check.last());
}