List of usage examples for java.util.concurrent Callable Callable
Callable
From source file:de.appsolve.padelcampus.utils.HtmlResourceUtil.java
public void updateCss(final ServletContext context) throws Exception { List<Customer> customers = customerDAO.findAll(); if (customers.isEmpty()) { applyCustomerCss(context, getDefaultCssAttributes(), ""); } else {// w w w . ja v a 2 s .co m lessCompiler = new LessCompiler(); lessCompiler.init(); int availableProcessors = Runtime.getRuntime().availableProcessors(); LOG.info(String.format("Compiling lesscss with %s cores", availableProcessors)); ExecutorService executor = Executors.newFixedThreadPool(availableProcessors); List<FutureTask<Void>> taskList = new ArrayList<>(); for (final Customer customer : customers) { FutureTask<Void> futureTask = new FutureTask<>(new Callable<Void>() { @Override public Void call() throws Exception { try { updateCss(context, customer); } catch (Exception ex) { LOG.error(ex, ex); } return null; } }); taskList.add(futureTask); executor.execute(futureTask); } for (FutureTask task : taskList) { task.get(); } executor.shutdown(); } }
From source file:org.soyatec.windowsazure.table.internal.TableStorageRest.java
/** * Lists the table within the account//from w ww . java 2 s .c o m * * @param nextTableName * Table prefix * @return List of table names */ private ListTableResult listTablesImpl(final String nextTableName) { final OutParameter<ListTableResult> result = new OutParameter<ListTableResult>(); getRetryPolicy().execute(new Callable<Object>() { public Object call() throws Exception { NameValueCollection queryParams = new NameValueCollection(); if (!Utilities.isNullOrEmpty(nextTableName)) { queryParams.put(QueryParams.QueryParamTableNextName, nextTableName); } ResourceUriComponents uriComponents = new ResourceUriComponents(getAccountName(), TableStorageConstants.TablesQuery, null); URI uri = HttpUtilities.createRequestUri(getBaseUri(), isUsePathStyleUris(), getAccountName(), TableStorageConstants.TablesQuery, null, getTimeout(), queryParams, uriComponents); HttpRequest request = HttpUtilities.createHttpRequest(uri, HttpMethod.Get); getCredentials().signRequestForSharedKeyLite(request, uriComponents); HttpWebResponse response = HttpUtilities.getResponse(request); if (response.getStatusCode() == HttpStatus.SC_OK) { ListTableResult tablesResult = getTableResultFromResponse(response.getStream()); result.setValue(tablesResult); String nextTableNameHeader = response.getHeader(HeaderNames.TableStorageNextTableName); if (!Utilities.isNullOrEmpty(nextTableNameHeader)) { tablesResult.setNextTableName(nextTableNameHeader); } response.close(); } else { HttpUtilities.processUnexpectedStatusCode(response); } return null; } }); return result.getValue(); }
From source file:com.vsct.dt.hesperides.indexation.ElasticSearchIndexationExecutor.java
public <T> Future<Void> index(final ElasticSearchIndexationCommand task) { return singleThreadPool.submit(new Callable<Void>() { @Override/*from www . j ava 2 s. com*/ public Void call() { withMaxRetry(nRetries, waitBeforeRetryMs, t -> t.index(elasticSearchClient)); return null; } private void withMaxRetry(final int maxRetry, final int wait, final Consumer<ElasticSearchIndexationCommand> consumer) { int count = 1; for (;;) { try { consumer.accept(task); return; } catch (Exception e) { if (count < maxRetry) { LOGGER.warn("Indexation task failed. Retry in {} milliseconds", wait); try { Thread.sleep(wait); } catch (final InterruptedException ie) { ie.printStackTrace(); } count++; } else { LOGGER.error( "Indexation task failed after {} attempts. Index might be broken. Reason: {} {}", nRetries, e, e.getMessage()); return; } } } } }); }
From source file:com.glaf.core.resource.ResourceFactory.java
public static byte[] getData(final String region, final String key) { if (conf.getBoolean(DISTRIBUTED_ENABLED, false)) { String regionName = Environment.getCurrentSystemName() + "_res_" + region; String complexKey = Environment.getCurrentSystemName() + "_res_" + key; if (SystemProperties.getDeploymentSystemName() != null) { regionName = SystemProperties.getDeploymentSystemName() + "_" + Environment.getCurrentSystemName() + "_res_" + region; }/*from www . jav a 2 s. c om*/ if (SystemProperties.getDeploymentSystemName() != null) { complexKey = SystemProperties.getDeploymentSystemName() + "_" + Environment.getCurrentSystemName() + "_res_" + key; } final String regionName2 = regionName; final String complexKey2 = complexKey; boolean waitFor = true; Callable<byte[]> task = new Callable<byte[]>() { @Override public byte[] call() throws Exception { return channel.getData(regionName2, complexKey2); } }; try { Future<byte[]> result = pool.submit(task); long start = System.currentTimeMillis(); // ? if (waitFor) { while (true) { if (System.currentTimeMillis() - start > 2000) { break; } if (result.isDone()) { return result.get(); } } } } catch (Exception ex) { ex.printStackTrace(); logger.error(ex); } } return null; }
From source file:io.fabric8.elasticsearch.plugin.PluginClient.java
public void deleteDocument(String index, String type, String id) { execute(new Callable<Object>() { @Override// ww w . j av a 2 s . co m public Object call() throws Exception { LOGGER.debug("Deleted document: '{}/{}/{}'", index, type, id); DeleteResponse response = client.prepareDelete(index, type, id).get(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Document deleted: '{}'", response.status()); } return null; } }); }
From source file:com.netflix.curator.framework.recipes.atomic.TestDistributedAtomicLong.java
@Test public void testForceSet() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start();// www . j a v a2 s . c o m try { final DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); ExecutorService executorService = Executors.newFixedThreadPool(2); executorService.submit(new Callable<Object>() { @Override public Object call() throws Exception { for (int i = 0; i < 1000; ++i) { dal.increment(); Thread.sleep(10); } return null; } }); executorService.submit(new Callable<Object>() { @Override public Object call() throws Exception { for (int i = 0; i < 1000; ++i) { dal.forceSet(0L); Thread.sleep(10); } return null; } }); Assert.assertTrue(dal.get().preValue() < 10); } finally { client.close(); } }
From source file:com.rogiel.httpchannel.http.Request.java
public Future<Object> asJsonAsync() throws IOException { return ctx.threadPool.submit(new Callable<Object>() { @Override/*from w ww. j av a 2s . c o m*/ public Object call() throws Exception { return asJson(); } }); }
From source file:com.blacklocus.qs.worker.util.log.SamplingQSLogServiceTest.java
@Test public void testSampledLifeCycle() throws InterruptedException { // With these parameters, by far most logger interactions should be filtered out, very few sampled in. final int numThreads = 64, iterations = 200, processingJitterMaxMs = 16, noSoonerThanMs = 100; final Set<String> sampledTaskIds = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); final QSLogService logService = Mockito.mock(QSLogService.class); // track which logging interactions were allowed through (sampled in) Mockito.doAnswer(new Answer() { @Override/*w w w .java 2s . com*/ public Object answer(InvocationOnMock invocation) throws Throwable { sampledTaskIds.add(((QSTaskModel) invocation.getArguments()[0]).taskId); return null; } }).when(logService).startedTask(Matchers.any(QSTaskModel.class)); Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { sampledTaskIds.add(((QSLogModel) invocation.getArguments()[0]).taskId); return null; //TODO jason } }).when(logService).log(Matchers.any(QSLogModel.class)); Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { sampledTaskIds.add(((QSTaskModel) invocation.getArguments()[0]).taskId); return null; //TODO jason } }).when(logService).completedTask(Matchers.any(QSTaskModel.class)); Predicate<QSTaskModel> taskPredicate = SamplingPredicates.noSoonerThan(noSoonerThanMs, TimeUnit.MILLISECONDS); final QSLogService sampledLogService = new SamplingQSLogService(logService, taskPredicate); long startNs = System.nanoTime(); ExecutorService threads = Executors.newFixedThreadPool(numThreads); for (int i = 0; i < numThreads; i++) { threads.submit(new Callable<Void>() { @Override public Void call() throws Exception { LOG.debug("Thread start {}", Thread.currentThread().getName()); for (int i = 0; i < iterations; i++) { String taskId = UUID.randomUUID().toString(); // simulate task processing, some have logs, some don't, processing time varies between each step QSTaskModel task = new QSTaskModel(); task.taskId = taskId; Thread.sleep(RandomUtils.nextInt(processingJitterMaxMs)); sampledLogService.startedTask(task); Thread.sleep(RandomUtils.nextInt(processingJitterMaxMs)); // random number of associated logs [0, 2] for (int j = RandomUtils.nextInt(2); j > 0; j--) { QSLogModel log = new QSLogModel(); log.taskId = taskId; sampledLogService.log(log); Thread.sleep(RandomUtils.nextInt(processingJitterMaxMs)); } sampledLogService.completedTask(task); } LOG.debug("Thread end {}", Thread.currentThread().getName()); return null; } }); } threads.shutdown(); threads.awaitTermination(1, TimeUnit.MINUTES); long endNs = System.nanoTime(); // Theoretical maximum number of sampled in task logging long durationMs = TimeUnit.NANOSECONDS.toMillis(endNs - startNs); long expectedMax = durationMs / noSoonerThanMs + 1; // +1 for time@0: sampled in LOG.debug("Run duration: {}ms no sooner than: {}ms", durationMs, noSoonerThanMs); LOG.debug("Expected max sampled in: {} Actually sampled: {}", expectedMax, sampledTaskIds.size()); Assert.assertTrue(expectedMax >= sampledTaskIds.size()); }
From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.ConferenceUserDaoImplTest.java
@Test public void testCreateAndSearch() throws Exception { this.execute(new Callable<Object>() { @Override/*from w w w . j a va 2 s. com*/ public Object call() { final ConferenceUser user1 = conferenceUserDao.createInternalUser("user@example.com"); user1.setEmail("user@dept.example.com"); conferenceUserDao.updateUser(user1); final ConferenceUser user2 = conferenceUserDao.createInternalUser("admin@example.com"); user2.setEmail("admin@dept.example.com"); user2.getAdditionalEmails().add("admin@external.example.com"); conferenceUserDao.updateUser(user2); conferenceUserDao.createExternalUser("New User", "admin@external.example.com"); return null; } }); this.execute(new Callable<Object>() { @Override public Object call() { Set<ConferenceUser> users = conferenceUserDao.getUsersByPrimaryEmail("user@dept.example.com"); assertNotNull(users); assertEquals(1, users.size()); users = conferenceUserDao.getUsersByAnyEmail("admin@external.example.com"); assertNotNull(users); assertEquals(2, users.size()); return null; } }); }
From source file:com.thinkbiganalytics.spark.repl.SparkScriptEngine.java
@Nonnull @Override// w w w .j a v a 2 s . c o m protected SparkContext createSparkContext() { // Allow interpreter to modify Thread context for Spark getInterpreter().setContextClassLoader(); // The SparkContext ClassLoader is needed during initialization (only for YARN master) return executeWithSparkClassLoader(new Callable<SparkContext>() { @Override public SparkContext call() throws Exception { log.info("Creating spark context with spark conf {}", conf); return new SparkContext(conf); } }); }