Java Code Examples for java.util.concurrent.ExecutorService

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project AeminiumRuntime, under directory /src/aeminium/runtime/tests/.

Source file: ExecutorServiceTests.java

  19 
vote

@Test public void simpleShutdown(){
  Runtime rt=getRuntime();
  rt.init();
  ExecutorService es=rt.getExecutorService();
  es.shutdown();
  rt.shutdown();
}
 

Example 2

From project airlift, under directory /http-client/src/main/java/io/airlift/http/client/.

Source file: AsyncHttpClientModule.java

  18 
vote

@Override public AsyncHttpClient get(){
  ExecutorService executorService=injector.getInstance(Key.get(ExecutorService.class,annotation));
  HttpClientConfig config=injector.getInstance(Key.get(HttpClientConfig.class,annotation));
  Set<HttpRequestFilter> filters=injector.getInstance(filterKey(annotation));
  return new AsyncHttpClient(new ApacheHttpClient(config),executorService,filters);
}
 

Example 3

From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.

Source file: RegistrySharedObject.java

  18 
vote

/** 
 * @since 3.0
 */
public Future asyncGetRemoteServiceReferences(final ID[] idFilter,final String clazz,final RegularExpression filter){
  ExecutorService executor=Executors.newCachedThreadPool();
  return executor.submit(new Runnable(){
    public void run(){
      try {
        getRemoteServiceReferences(idFilter,clazz,filter);
      }
 catch (      InvalidSyntaxException e) {
        e.printStackTrace();
      }
    }
  }
);
}
 

Example 4

From project android_external_guava, under directory /src/com/google/common/util/concurrent/.

Source file: Executors.java

  18 
vote

/** 
 * Converts the given ThreadPoolExecutor into an ExecutorService that exits when the application is complete.  It does so by using daemon threads and adding a shutdown hook to wait for their completion. <p>This is mainly for fixed thread pools. See  {@link java.util.concurrent.Executors#newFixedThreadPool(int)}.
 * @param executor the executor to modify to make sure it exits when theapplication is finished
 * @param terminationTimeout how long to wait for the executor tofinish before terminating the JVM
 * @param timeUnit unit of time for the time parameter
 * @return an unmodifiable version of the input which will not hang the JVM
 */
public static ExecutorService getExitingExecutorService(ThreadPoolExecutor executor,long terminationTimeout,TimeUnit timeUnit){
  executor.setThreadFactory(daemonThreadFactory(executor.getThreadFactory()));
  ExecutorService service=java.util.concurrent.Executors.unconfigurableExecutorService(executor);
  addDelayedShutdownHook(service,terminationTimeout,timeUnit);
  return service;
}
 

Example 5

From project Arecibo, under directory /collector-rt-support/src/main/java/com/ning/arecibo/collector/kafka/.

Source file: KafkaAreciboClient.java

  18 
vote

@Override public synchronized void stopListening(final String topic){
  final ExecutorService service=executorServicePerTopic.remove(topic);
  if (service == null) {
    return;
  }
 else {
    service.shutdownNow();
  }
  final ConsumerConnector connector=kafkaConnectorPerTopic.remove(topic);
  if (connector != null) {
    connector.shutdown();
  }
}
 

Example 6

From project aws-tasks, under directory /src/main/java/datameer/awstasks/aws/ec2/ssh/.

Source file: SshClientImpl.java

  18 
vote

private void executeCallables(List<SshCallable> sshCallables) throws IOException {
  ExecutorService e=Executors.newCachedThreadPool();
  List<Future<SshCallable>> futureList=Lists.newArrayListWithCapacity(sshCallables.size());
  for (  SshCallable sshCallable : sshCallables) {
    futureList.add(e.submit(sshCallable));
  }
  waitForSshCommandCompletion(futureList);
}
 

Example 7

From project azkaban, under directory /azkaban/src/unit/azkaban/utils/process/.

Source file: ProcessTest.java

  18 
vote

@Test public void testKill() throws Exception {
  ExecutorService executor=Executors.newFixedThreadPool(2);
  AzkabanProcess p1=new AzkabanProcessBuilder("sleep","10").build();
  runInSeperateThread(executor,p1);
  assertTrue("Soft kill should interrupt sleep.",p1.softKill(5,TimeUnit.SECONDS));
  p1.awaitCompletion();
  AzkabanProcess p2=new AzkabanProcessBuilder("sleep","10").build();
  runInSeperateThread(executor,p2);
  p2.hardKill();
  p2.awaitCompletion();
  assertTrue(p2.isComplete());
}
 

Example 8

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/event/.

Source file: EventManager.java

  18 
vote

/** 
 * Fire the specified event asynchronously.
 * @param < T > the result type
 * @param event the specified event
 * @return future result
 * @throws EventException event exception
 */
public <T>Future<T> fireEventAsynchronously(final Event<?> event) throws EventException {
  final ExecutorService executorService=Executors.newSingleThreadExecutor();
  final FutureTask<T> futureTask=new FutureTask<T>(new Callable<T>(){
    @Override public T call() throws Exception {
      synchronizedEventQueue.fireEvent(event);
      return null;
    }
  }
);
  executorService.execute(futureTask);
  return futureTask;
}
 

Example 9

From project bonecp, under directory /bonecp/src/test/java/com/jolbox/bonecp/.

Source file: CommonTestUtils.java

  18 
vote

/** 
 * Helper function.
 * @param threads
 * @param connections
 * @param cpds
 * @param workDelay
 * @param doPreparedStatement 
 * @return time taken
 * @throws InterruptedException
 */
public static long startThreadTest(int threads,long connections,DataSource cpds,int workDelay,boolean doPreparedStatement) throws InterruptedException {
  CountDownLatch startSignal=new CountDownLatch(1);
  CountDownLatch doneSignal=new CountDownLatch(threads);
  ExecutorService pool=Executors.newFixedThreadPool(threads);
  for (int i=0; i < threads; i++) {
    pool.execute(new ThreadTester(startSignal,doneSignal,cpds,connections,workDelay,doPreparedStatement));
  }
  long start=System.currentTimeMillis();
  startSignal.countDown();
  doneSignal.await();
  long end=(System.currentTimeMillis() - start);
  pool.shutdown();
  return end;
}
 

Example 10

From project camel-osgi, under directory /component/src/test/java/org/apache/camel/osgi/service/.

Source file: OsgiMulticastProducerTest.java

  18 
vote

@Test public void testCreateParallelProcessing() throws Exception {
  CamelContext camelContext=mock(CamelContext.class);
  OsgiDefaultEndpoint endpoint=mock(OsgiDefaultEndpoint.class);
  when(endpoint.getCamelContext()).thenReturn(camelContext);
  ExecutorService executor=mock(ExecutorService.class);
  OsgiMulticastProducer producer=new OsgiMulticastProducer(endpoint,Collections.<String,Object>emptyMap(),null,true,executor,false,false,false,1,null);
  assertThat(producer.getAggregationStrategy(),nullValue());
  assertThat(producer.isParallelProcessing(),equalTo(true));
  assertThat(producer.getExecutorService(),sameInstance(executor));
  assertThat(producer.isStreaming(),equalTo(false));
  assertThat(producer.isStopOnException(),equalTo(false));
  assertThat(producer.getTimeout(),equalTo(1L));
  assertThat(producer.getOnPrepare(),nullValue());
}
 

Example 11

From project CamelInAction-source, under directory /chapter10/eip/src/test/java/camelinaction/.

Source file: WireTapTest.java

  18 
vote

@Override protected RouteBuilder createRouteBuilder() throws Exception {
  return new RouteBuilder(){
    @Override public void configure() throws Exception {
      ExecutorService lowPool=new ThreadPoolBuilder(context).poolSize(1).maxPoolSize(5).build("LowPool");
      from("direct:start").log("Incoming message ${body}").wireTap("direct:tap",lowPool).to("mock:result");
      from("direct:tap").log("Tapped message ${body}").to("mock:tap");
    }
  }
;
}
 

Example 12

From project cas, under directory /cas-server-core/src/test/java/org/jasig/cas/ticket/registry/support/.

Source file: JpaLockingStrategyTests.java

  18 
vote

/** 
 * Test concurrent acquire/release semantics.
 */
@Test @IfProfileValue(name="cas.jpa.concurrent",value="true") public void testConcurrentAcquireAndRelease() throws Exception {
  final ExecutorService executor=Executors.newFixedThreadPool(CONCURRENT_SIZE);
  try {
    testConcurrency(executor,getConcurrentLocks("concurrent-new"));
  }
 catch (  Exception e) {
    logger.debug("testConcurrentAcquireAndRelease produced an error",e);
    fail("testConcurrentAcquireAndRelease failed.");
  }
 finally {
    executor.shutdownNow();
  }
}
 

Example 13

From project cascading, under directory /src/local/cascading/flow/local/planner/.

Source file: LocalStepRunner.java

  18 
vote

private List<Future<Throwable>> spawnHeads(){
  ExecutorService executors=Executors.newFixedThreadPool(heads.size());
  List<Future<Throwable>> futures=new ArrayList<Future<Throwable>>();
  for (  Duct head : heads)   futures.add(executors.submit((Callable)head));
  executors.shutdown();
  return futures;
}
 

Example 14

From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/openstack/.

Source file: OpenstackCloudDriver.java

  18 
vote

@Override public MachineDetails[] startManagementMachines(final long duration,final TimeUnit unit) throws TimeoutException, CloudProvisioningException {
  final String token=createAuthenticationToken();
  final long endTime=calcEndTimeInMillis(duration,unit);
  final int numOfManagementMachines=cloud.getProvider().getNumberOfManagementMachines();
  final ExecutorService executor=Executors.newFixedThreadPool(cloud.getProvider().getNumberOfManagementMachines());
  try {
    return doStartManagement(endTime,token,numOfManagementMachines,executor);
  }
  finally {
    executor.shutdown();
  }
}
 

Example 15

From project clutter, under directory /src/clutter/.

Source file: BaseTestCase.java

  18 
vote

protected static void attempt(Runnable task){
  ExecutorService executorService=Executors.newFixedThreadPool(1);
  executorService.submit(task);
  executorService.shutdown();
  try {
    Thread.sleep(100);
  }
 catch (  InterruptedException e) {
    throw new RuntimeException(e);
  }
}
 

Example 16

From project collector, under directory /src/test/java/com/ning/metrics/collector/.

Source file: TestPerformance.java

  18 
vote

private static long scheduleScribeAgents() throws InterruptedException {
  final ExecutorService e=Executors.newFixedThreadPool(THREADPOOL_SIZE,"Performance tests (Scribe client)");
  final long startTime=System.currentTimeMillis();
  for (int i=0; i < NUMBER_OF_SCRIBE_CLIENTS; i++) {
    e.execute(new ScribeClient());
    log.debug(String.format("Thread %d/%d submitted",i + 1,NUMBER_OF_SCRIBE_CLIENTS));
  }
  e.shutdown();
  e.awaitTermination(10,TimeUnit.MINUTES);
  return startTime;
}
 

Example 17

From project dragon, under directory /hadoop-dragon-core/src/main/java/org/apache/hadoop/realtime/local/.

Source file: LocalJobRunner.java

  18 
vote

/** 
 * Creates the executor service used to run tasks.
 * @param numTasks the total number of map tasks to be run
 * @return an ExecutorService instance that handles map tasks
 */
protected ExecutorService createTaskExecutor(int numTasks){
  int maxThreads=conf.getInt(LOCAL_MAX_TASKS,1);
  if (maxThreads < 1) {
    throw new IllegalArgumentException("Configured " + LOCAL_MAX_TASKS + " must be >= 1");
  }
  maxThreads=Math.min(maxThreads,numTasks);
  maxThreads=Math.max(maxThreads,1);
  LOG.debug("Starting thread pool executor.");
  LOG.debug("Max local threads: " + maxThreads);
  LOG.debug("Tasks to process: " + numTasks);
  ThreadFactory tf=new ThreadFactoryBuilder().setNameFormat("LocalJobRunner Task Executor #%d").build();
  ExecutorService executor=Executors.newFixedThreadPool(maxThreads,tf);
  return executor;
}
 

Example 18

From project fire-samples, under directory /cache-demo/src/main/java/demo/vmware/util/.

Source file: JmxAgentBean.java

  18 
vote

/** 
 * Fire up the agent. This method never returns effectively making this a JMX agent only program if it's single threaded. This has the side effect of possibly not cleaning up the log directory.
 */
public void startAgent(){
  AgentConfig config=new AgentConfigImpl();
  config.setLocators(getLocators());
  config.setRmiPort(getRmiPort());
  config.setMcastPort(getMcastPort());
  config.setLogFile(logFile.getPath());
  ExecutorService taskExecutor=Executors.newFixedThreadPool(1);
  AgentRunable runJmx=new AgentRunable(config);
  taskExecutor.execute(runJmx);
  return;
}
 

Example 19

From project FlipDroid, under directory /tika-thrift/src/main/java/it/tika/.

Source file: TikaServiceImpl.java

  18 
vote

public static void main(String[] args) throws TException, TikaException, IOException {
  TikaServiceImpl tikaService=new TikaServiceImpl();
  TikaRequest request=new TikaRequest();
  request.setUrl("http://www.36kr.com/p/100534.html");
  ExecutorService executorService=Executors.newFixedThreadPool(1);
  TikaResponse response=tikaService.fire(request);
  System.out.println(response.getContent());
}
 

Example 20

From project galaxy, under directory /test/co/paralleluniverse/galaxy/netty/.

Source file: UDPCommTest.java

  18 
vote

void await(){
  try {
    ExecutorService executor=comm.getExecutor();
    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE,TimeUnit.MILLISECONDS);
  }
 catch (  InterruptedException e) {
    System.err.println("Interrupted");
  }
}
 

Example 21

From project Gibberbot, under directory /src/info/guardianproject/otr/app/im/plugin/xmpp/.

Source file: LLXmppConnection.java

  18 
vote

public void join() throws InterruptedException {
  ExecutorService oldExecutor=mExecutor;
  createExecutor();
  oldExecutor.shutdown();
  oldExecutor.awaitTermination(10,TimeUnit.SECONDS);
}
 

Example 22

From project graylog2-server, under directory /src/main/java/org/graylog2/inputs/gelf/.

Source file: GELFTCPInput.java

  18 
vote

private void spinUp(){
  final ExecutorService bossThreadPool=Executors.newCachedThreadPool();
  final ExecutorService workerThreadPool=Executors.newCachedThreadPool();
  ServerBootstrap tcpBootstrap=new ServerBootstrap(new NioServerSocketChannelFactory(bossThreadPool,workerThreadPool));
  tcpBootstrap.setPipelineFactory(new GELFTCPPipelineFactory(this.graylogServer));
  try {
    tcpBootstrap.bind(socketAddress);
    LOG.info("Started TCP GELF server on " + socketAddress);
  }
 catch (  ChannelException e) {
    LOG.fatal("Could not bind TCP GELF server to address " + socketAddress,e);
  }
}
 

Example 23

From project groovejaar, under directory /src/groovejaar/.

Source file: GrooveJaar.java

  18 
vote

private void checkUpdate(boolean showNoUpdate) throws InterruptedException, ExecutionException, MalformedURLException {
  ExecutorService executor=Executors.newSingleThreadExecutor();
  Future<Boolean> task=null;
  task=executor.submit(new Updater(lastVersionURL));
  if (task.get())   showMessage(("New version available, check the project page!"));
 else   if (showNoUpdate)   showMessage(("No new version available"));
  executor.shutdown();
}
 

Example 24

From project agraph-java-client, under directory /src/test/pool/.

Source file: AGConnPoolSessionTest.java

  17 
vote

@Test @Category(TestSuites.Stress.class) public void maxActive() throws Exception {
  final int seconds=5;
  final int clients=4;
  final AGConnPool pool=closeLater(AGConnPool.create(AGConnProp.serverUrl,AGAbstractTest.findServerUrl(),AGConnProp.username,AGAbstractTest.username(),AGConnProp.password,AGAbstractTest.password(),AGConnProp.catalog,"/",AGConnProp.repository,"pool.maxActive",AGConnProp.session,AGConnProp.Session.DEDICATED,AGConnProp.sessionLifetime,seconds * clients * 2,AGConnProp.httpSocketTimeout,TimeUnit.SECONDS.toMillis(seconds * clients),AGPoolProp.shutdownHook,true,AGPoolProp.testOnBorrow,true,AGPoolProp.maxActive,2,AGPoolProp.maxWait,TimeUnit.SECONDS.toMillis((seconds * clients) + 10),AGPoolProp.maxIdle,8));
  ExecutorService exec=Executors.newFixedThreadPool(clients);
  List<Future<Boolean>> errors=new ArrayList<Future<Boolean>>(clients);
  final AtomicLong idx=new AtomicLong(0);
  for (int i=0; i < clients; i++) {
    errors.add(exec.submit(new Callable<Boolean>(){
      @Override public Boolean call() throws Exception {
        try {
          long id=idx.incrementAndGet();
          log.debug(id + " start");
          AGRepositoryConnection conn=pool.borrowConnection();
          try {
            log.debug(id + " open");
            conn.size();
            Thread.sleep(TimeUnit.SECONDS.toMillis(seconds));
            conn.size();
          }
  finally {
            conn.close();
            log.debug(id + " close");
          }
          return true;
        }
 catch (        Throwable e) {
          log.error("error " + this,e);
          return false;
        }
      }
    }
));
  }
  assertSuccess(errors,seconds * clients * 2,TimeUnit.SECONDS);
}
 

Example 25

From project aranea, under directory /server/src/main/java/no/dusken/aranea/web/spring/.

Source file: ChainedController.java

  17 
vote

/** 
 * Spawns multiple threads, one for each controller in the list of controllers, and within each thread, delegates to the controller's handleRequest() method. Once all the threads are complete, the ModelAndView objects returned from each of the handleRequest() methods are merged into a single view. The view name for the model is set to the specified view name. If an exception is thrown by any of the controllers in the chain, this exception is propagated up from the handleRequest() method of the ChainedController.
 * @param request  the HttpServletRequest object.
 * @param response the HttpServletResponse object.
 * @return a merged ModelAndView object.
 * @throws Exception if one is thrown from the controllers in the chain.
 */
@SuppressWarnings("unchecked") private ModelAndView handleRequestParallely(HttpServletRequest request,HttpServletResponse response) throws Exception {
  ExecutorService service=Executors.newCachedThreadPool();
  int numberOfControllers=controllers.size();
  CallableController[] callables=new CallableController[numberOfControllers];
  Future<ModelAndView>[] futures=new Future[numberOfControllers];
  for (int i=0; i < numberOfControllers; i++) {
    callables[i]=new CallableController(controllers.get(i),request,response);
    futures[i]=service.submit(callables[i]);
  }
  ModelAndView mergedModel=new ModelAndView();
  for (  Future<ModelAndView> future : futures) {
    ModelAndView model=future.get();
    if (model != null) {
      mergedModel.addAllObjects(model.getModel());
    }
  }
  if (StringUtils.isNotEmpty(this.viewName)) {
    mergedModel.setViewName(this.viewName);
  }
  return mergedModel;
}
 

Example 26

From project archaius, under directory /archaius-core/src/test/java/com/netflix/config/.

Source file: ConcurrentMapConfigurationTest.java

  17 
vote

@Test public void testConcurrency(){
  final ConcurrentMapConfiguration conf=new ConcurrentMapConfiguration();
  ExecutorService exectuor=Executors.newFixedThreadPool(20);
  final CountDownLatch doneSignal=new CountDownLatch(1000);
  for (int i=0; i < 1000; i++) {
    final Integer index=i;
    exectuor.submit(new Runnable(){
      public void run(){
        conf.addProperty("key",index);
        conf.addProperty("key","stringValue");
        doneSignal.countDown();
        try {
          Thread.sleep(50);
        }
 catch (        InterruptedException e) {
        }
      }
    }
);
  }
  try {
    doneSignal.await();
  }
 catch (  InterruptedException e) {
  }
  List prop=(List)conf.getProperty("key");
  assertEquals(2000,prop.size());
}
 

Example 27

From project astyanax, under directory /src/main/java/com/netflix/astyanax/recipes/reader/.

Source file: AllRowsReader.java

  17 
vote

/** 
 * Main execution block for the all rows query.  
 */
@Override public Boolean call() throws Exception {
  List<Callable<Boolean>> subtasks=Lists.newArrayList();
  if (this.concurrencyLevel != null) {
    List<TokenRange> tokens=partitioner.splitTokenRange(startToken == null ? partitioner.getMinToken() : startToken,endToken == null ? partitioner.getMinToken() : endToken,this.concurrencyLevel);
    for (    TokenRange range : tokens) {
      subtasks.add(makeTokenRangeTask(range.getStartToken(),range.getEndToken()));
    }
  }
 else {
    List<TokenRange> ranges=keyspace.describeRing();
    for (    TokenRange range : ranges) {
      subtasks.add(makeTokenRangeTask(partitioner.getTokenMinusOne(range.getStartToken()),range.getEndToken()));
    }
  }
  try {
    if (executor == null) {
      ExecutorService localExecutor=Executors.newFixedThreadPool(subtasks.size(),new ThreadFactoryBuilder().setDaemon(true).setNameFormat("AstyanaxAllRowsReader-%d").build());
      try {
        futures.addAll(startTasks(localExecutor,subtasks));
        return waitForTasksToFinish();
      }
  finally {
        localExecutor.shutdownNow();
      }
    }
 else {
      futures.addAll(startTasks(executor,subtasks));
      return waitForTasksToFinish();
    }
  }
 catch (  Throwable t) {
    LOG.warn("AllRowsReader terminated",t);
    cancel();
    return false;
  }
}
 

Example 28

From project avro, under directory /lang/java/ipc/src/test/java/org/apache/avro/ipc/.

Source file: TestNettyServerWithCallbacks.java

  17 
vote

@Ignore @Test public void performanceTest() throws Exception {
  final int threadCount=8;
  final long runTimeMillis=10 * 1000L;
  ExecutorService threadPool=Executors.newFixedThreadPool(threadCount);
  System.out.println("Running performance test for " + runTimeMillis + "ms...");
  final AtomicLong rpcCount=new AtomicLong(0L);
  final AtomicBoolean runFlag=new AtomicBoolean(true);
  final CountDownLatch startLatch=new CountDownLatch(threadCount);
  for (int ii=0; ii < threadCount; ii++) {
    threadPool.submit(new Runnable(){
      @Override public void run(){
        try {
          startLatch.countDown();
          startLatch.await(2,TimeUnit.SECONDS);
          while (runFlag.get()) {
            rpcCount.incrementAndGet();
            Assert.assertEquals("Hello, World!",simpleClient.hello("World!"));
          }
        }
 catch (        Exception e) {
          e.printStackTrace();
        }
      }
    }
);
  }
  startLatch.await(2,TimeUnit.SECONDS);
  Thread.sleep(runTimeMillis);
  runFlag.set(false);
  threadPool.shutdown();
  Assert.assertTrue("Timed out shutting down thread pool",threadPool.awaitTermination(2,TimeUnit.SECONDS));
  System.out.println("Completed " + rpcCount.get() + " RPCs in "+ runTimeMillis+ "ms => "+ (((double)rpcCount.get() / (double)runTimeMillis) * 1000)+ " RPCs/sec, "+ ((double)runTimeMillis / (double)rpcCount.get())+ " ms/RPC.");
}
 

Example 29

From project b1-pack, under directory /standard/src/test/java/org/b1/pack/standard/common/.

Source file: SynchronousPipeTest.java

  17 
vote

@Test public void test_read_write() throws Exception {
  ExecutorService service=Executors.newCachedThreadPool();
  Future<Boolean> readerFuture=service.submit(new Callable<Boolean>(){
    @Override public Boolean call() throws Exception {
      byte[] buffer=new byte[1000];
      readerStarted=true;
      assertEquals(0,pipe.inputStream.read(buffer,5,0));
      assertFalse(writerStarted);
      assertEquals(2,pipe.inputStream.read(buffer,10,2));
      assertEquals("01",new String(buffer,10,2,Charsets.UTF_8));
      assertTrue(writerStarted);
      assertEquals(8,pipe.inputStream.read(buffer,1,10));
      assertEquals("23456789",new String(buffer,1,8,Charsets.UTF_8));
      assertFalse(writerClosed);
      assertEquals(-1,pipe.inputStream.read(buffer,1,10));
      assertTrue(writerClosed);
      return true;
    }
  }
);
  Thread.sleep(500);
  assertTrue(readerStarted);
  Future<Boolean> writerFuture=service.submit(new Callable<Boolean>(){
    @Override public Boolean call() throws Exception {
      writerStarted=true;
      pipe.outputStream.write(TEST_BYTES);
      Thread.sleep(500);
      pipe.outputStream.close();
      writerClosed=true;
      return true;
    }
  }
);
  assertTrue(readerFuture.get());
  assertTrue(writerFuture.get());
}
 

Example 30

From project BeeQueue, under directory /src/org/beequeue/hash/.

Source file: FileCollection.java

  17 
vote

public static FileCollection scan(File base){
  CopyOnWriteArrayList<FileEntry> entries=new CopyOnWriteArrayList<FileEntry>();
  CopyOnWriteArrayList<String> errors=new CopyOnWriteArrayList<String>();
  try {
    ExecutorService threadPool=Executors.newFixedThreadPool(4);
    constructEntries(base,null,threadPool,entries,errors);
    threadPool.shutdown();
    for (int i=0; !threadPool.awaitTermination(1,TimeUnit.HOURS); i++) {
      log.warning("" + i + "hours passed by.");
      if (i > 24) {
        errors.add("waiting for too long:" + threadPool.shutdownNow());
        break;
      }
    }
  }
 catch (  Exception e) {
    throw new BeeException(e).addPayload(errors.toArray());
  }
  if (errors.size() > 0) {
    throw new BeeException("has errors:").addPayload(errors.toArray());
  }
  FileCollection fileCollection=new FileCollection();
  FileEntry[] array=entries.toArray(new FileEntry[entries.size()]);
  Arrays.sort(array);
  fileCollection.entries=array;
  return fileCollection;
}
 

Example 31

From project big-data-plugin, under directory /test-src/org/pentaho/di/job/entries/hadoopjobexecutor/.

Source file: SecurityManagerStackTest.java

  17 
vote

@Test public void randomized_executions() throws Exception {
  final SecurityManagerStack stack=new SecurityManagerStack();
  final Random random=new Random();
  NoExitSecurityManager test=new NoExitSecurityManager(null);
  SecurityManager original=System.getSecurityManager();
  stack.setSecurityManager(test);
  final int NUM_TASKS=10;
  ExecutorService exec=Executors.newFixedThreadPool(NUM_TASKS);
  exec.invokeAll(Collections.nCopies(NUM_TASKS,new Callable<Void>(){
    @Override public Void call() throws Exception {
      NoExitSecurityManager sm=new NoExitSecurityManager(null);
      try {
        Thread.sleep(random.nextInt(1000));
        System.out.println("set: " + sm);
        stack.setSecurityManager(sm);
        Thread.sleep(random.nextInt(1000));
      }
 catch (      Exception ex) {
      }
 finally {
        System.out.println("rm : \t" + sm);
        stack.removeSecurityManager(sm);
      }
      return null;
    }
  }
));
  exec.shutdown();
  exec.awaitTermination(3,TimeUnit.SECONDS);
  assertEquals(test,System.getSecurityManager());
  stack.removeSecurityManager(test);
  assertEquals(original,System.getSecurityManager());
}
 

Example 32

From project caustic, under directory /console/test/net/caustic/util/.

Source file: ScopeFactoryTest.java

  17 
vote

@Test public void testUniquenessInSeveralThreads() throws Exception {
  final Set<Scope> uuids=Collections.synchronizedSet(new HashSet<Scope>());
  final Set<String> uuidStrings=Collections.synchronizedSet(new HashSet<String>());
  List<Future<Boolean>> futures=new ArrayList<Future<Boolean>>();
  int numThreads=100;
  ExecutorService executor=Executors.newCachedThreadPool();
  for (int i=0; i < numThreads; i++) {
    futures.add(executor.submit(new UUIDFactoryTestRunnable(factory,uuids,uuidStrings)));
  }
  for (  Future<Boolean> future : futures) {
    assertTrue(future.get());
  }
  assertEquals("Generated non-unique hashing UUIDs.",NUM_TESTS * numThreads,uuids.size());
  assertEquals("Generated UUIDs with duplicate String values.",NUM_TESTS * numThreads,uuidStrings.size());
}
 

Example 33

From project components, under directory /soap/src/test/java/org/switchyard/component/soap/.

Source file: SOAPGatewayTest.java

  17 
vote

@Test public void invokeMultiThreaded() throws Exception {
  String output=null;
  String response=null;
  Collection<Callable<String>> callables=new ArrayList<Callable<String>>();
  for (int i=0; i < _noOfThreads; i++) {
    callables.add(new WebServiceInvoker(i));
  }
  ExecutorService executorService=Executors.newFixedThreadPool(DEFAULT_THREAD_COUNT);
  Collection<Future<String>> futures=executorService.invokeAll(callables);
  Assert.assertEquals(futures.size(),_noOfThreads);
  int i=0;
  for (  Future<String> future : futures) {
    response=future.get();
    output="<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<SOAP-ENV:Body>" + "   <test:sayHelloResponse xmlns:test=\"urn:switchyard-component-soap:test-ws:1.0\">"+ "      <return>Hello Thread " + i + "! The soapAction received is </return>"+ "   </test:sayHelloResponse>"+ "</SOAP-ENV:Body></SOAP-ENV:Envelope>";
    XMLAssert.assertXMLEqual(output,response);
    i++;
  }
}
 

Example 34

From project concurrent, under directory /src/test/java/com/github/coderplay/util/concurrent/queue/.

Source file: ProducerConsumerThroughputTest.java

  17 
vote

protected void runOneQueue(String queueName,BlockingQueue<Long> queue,int producerThread,int consumerThread) throws Exception {
  final CyclicBarrier cyclicBarrier=new CyclicBarrier(producerThread + consumerThread + 1);
  final Producer[] producers=new Producer[producerThread];
  for (int i=0; i < producerThread; i++) {
    producers[i]=new Producer(queue,cyclicBarrier,ITERATIONS / producerThread);
  }
  Consumer[] consumers=new Consumer[consumerThread];
  for (int i=0; i < consumerThread; i++) {
    consumers[i]=new Consumer(queue,cyclicBarrier,ITERATIONS / consumerThread);
  }
  final ExecutorService pool=Executors.newFixedThreadPool(producerThread + consumerThread);
  System.gc();
  for (int i=0; i < producerThread; i++) {
    pool.execute(producers[i]);
  }
  for (int i=0; i < consumerThread; i++) {
    pool.execute(consumers[i]);
  }
  cyclicBarrier.await();
  long start=System.currentTimeMillis();
  cyclicBarrier.await();
  long opsPerSecond=(ITERATIONS * 1000L) / (System.currentTimeMillis() - start);
  System.out.println("\tBlockingQueue=" + queueName + " "+ opsPerSecond+ " ops/sec");
}
 

Example 35

From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/identity_server/.

Source file: IdentityServer.java

  17 
vote

public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
  prop=new Properties();
  prop.load(new FileInputStream("ferryinpres.properties"));
  String MYSQL_HOST=prop.getProperty("MYSQL_HOST");
  Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
  ServerSocket server_sock=new ServerSocket(Integer.parseInt(prop.getProperty("IDENTITY_PORT")));
  Class.forName("com.mysql.jdbc.Driver").newInstance();
  String url="jdbc:mysql://" + MYSQL_HOST + "/frontier";
  Connection con=DriverManager.getConnection(url,"ferryinpres","pass");
  ExecutorService pool=Executors.newFixedThreadPool(12);
  for (; ; ) {
    System.out.println("En attente d'un nouveau client");
    Socket sock=server_sock.accept();
    System.out.println("Nouveau client");
    pool.execute(new ServerThread(sock,con));
  }
}
 

Example 36

From project curator, under directory /curator-examples/src/main/java/locking/.

Source file: LockingExample.java

  17 
vote

public static void main(String[] args) throws Exception {
  final FakeLimitedResource resource=new FakeLimitedResource();
  ExecutorService service=Executors.newFixedThreadPool(QTY);
  final TestingServer server=new TestingServer();
  try {
    for (int i=0; i < QTY; ++i) {
      final int index=i;
      Callable<Void> task=new Callable<Void>(){
        @Override public Void call() throws Exception {
          CuratorFramework client=CuratorFrameworkFactory.newClient(server.getConnectString(),new ExponentialBackoffRetry(1000,3));
          try {
            client.start();
            ExampleClientThatLocks example=new ExampleClientThatLocks(client,PATH,resource,"Client " + index);
            for (int j=0; j < REPETITIONS; ++j) {
              example.doWork(10,TimeUnit.SECONDS);
            }
          }
 catch (          Throwable e) {
            e.printStackTrace();
          }
 finally {
            Closeables.closeQuietly(client);
          }
          return null;
        }
      }
;
      service.submit(task);
    }
    service.shutdown();
    service.awaitTermination(10,TimeUnit.MINUTES);
  }
  finally {
    Closeables.closeQuietly(server);
  }
}
 

Example 37

From project cytoscape-plugins, under directory /org.openbel.cytoscape.navigator/src/org/openbel/cytoscape/navigator/task/.

Source file: AbstractSearchKamTask.java

  17 
vote

private List<KamNode> searchKAMNodes(){
  ExecutorService e=Executors.newSingleThreadExecutor();
  Future<List<KamNode>> future=e.submit(buildCallable());
  while (!(future.isDone() || future.isCancelled()) && !e.isShutdown()) {
    try {
      if (halt) {
        e.shutdownNow();
        future.cancel(true);
      }
      Thread.sleep(100);
    }
 catch (    InterruptedException ex) {
      halt=true;
    }
  }
  if (future.isCancelled()) {
    return null;
  }
  try {
    return future.get();
  }
 catch (  InterruptedException ex) {
    log.warn("Error searching kam nodes",ex);
    return null;
  }
catch (  ExecutionException ex) {
    log.warn("Error searching kam nodes",ex);
    return null;
  }
}
 

Example 38

From project dcm4che, under directory /dcm4che-tool/dcm4che-tool-dcmqrscp/src/main/java/org/dcm4che/tool/dcmqrscp/.

Source file: DcmQRSCP.java

  17 
vote

public static void main(String[] args){
  try {
    CommandLine cl=parseComandLine(args);
    DcmQRSCP main=new DcmQRSCP();
    CLIUtils.configure(main.fsInfo,cl);
    CLIUtils.configureBindServer(main.conn,main.ae,cl);
    CLIUtils.configure(main.conn,cl);
    configureDicomFileSet(main,cl);
    configureTransferCapability(main,cl);
    configureInstanceAvailability(main,cl);
    configureStgCmt(main,cl);
    configureSendPending(main,cl);
    configureRemoteConnections(main,cl);
    ExecutorService executorService=Executors.newCachedThreadPool();
    ScheduledExecutorService scheduledExecutorService=Executors.newSingleThreadScheduledExecutor();
    main.device.setScheduledExecutor(scheduledExecutorService);
    main.device.setExecutor(executorService);
    main.device.bindConnections();
  }
 catch (  ParseException e) {
    System.err.println("dcmqrscp: " + e.getMessage());
    System.err.println(rb.getString("try"));
    System.exit(2);
  }
catch (  Exception e) {
    System.err.println("dcmqrscp: " + e.getMessage());
    e.printStackTrace();
    System.exit(2);
  }
}
 

Example 39

From project dmix, under directory /JmDNS/src/javax/jmdns/impl/.

Source file: JmmDNSImpl.java

  17 
vote

@Override public void close() throws IOException {
  if (logger.isLoggable(Level.FINER)) {
    logger.finer("Cancelling JmmDNS: " + this);
  }
  _timer.cancel();
  _ListenerExecutor.shutdown();
  ExecutorService executor=Executors.newCachedThreadPool();
  for (  final JmDNS mDNS : _knownMDNS.values()) {
    executor.submit(new Runnable(){
      /** 
 * {@inheritDoc}
 */
      @Override public void run(){
        try {
          mDNS.close();
        }
 catch (        IOException exception) {
        }
      }
    }
);
  }
  executor.shutdown();
  try {
    executor.awaitTermination(DNSConstants.CLOSE_TIMEOUT,TimeUnit.MILLISECONDS);
  }
 catch (  InterruptedException exception) {
    logger.log(Level.WARNING,"Exception ",exception);
  }
  _knownMDNS.clear();
}
 

Example 40

From project dozer, under directory /core/src/test/java/org/dozer/.

Source file: DozerBeanMapperTest.java

  17 
vote

@Test public void shouldInitializeOnce() throws Exception {
  final CallTrackingMapper mapper=new CallTrackingMapper();
  ExecutorService executorService=Executors.newFixedThreadPool(10);
  final CountDownLatch latch=new CountDownLatch(THREAD_COUNT);
  HashSet<Callable<Object>> callables=new HashSet<Callable<Object>>();
  for (int i=0; i < THREAD_COUNT; i++) {
    callables.add(new Callable<Object>(){
      public Object call() throws Exception {
        latch.countDown();
        latch.await();
        Mapper processor=mapper.getMappingProcessor();
        assertNotNull(processor);
        return null;
      }
    }
);
  }
  executorService.invokeAll(callables);
  assertEquals(1,mapper.getCalls());
  assertTrue(exceptions.isEmpty());
}
 

Example 41

From project drools-mas, under directory /examples/drools-mas-emergency-agent-client/src/test/java/org/drools/mas/.

Source file: EmergencyAgentServiceRemoteTest.java

  17 
vote

@Test public void multiThreadTest() throws InterruptedException {
  final SyncDialogueHelper helper=new SyncDialogueHelper(endpoint);
  final int EMERGENCY_COUNT=45;
  final int THREAD_COUNT=10;
  Collection<Callable<Void>> tasks=new ArrayList<Callable<Void>>();
  for (int i=0; i < EMERGENCY_COUNT; i++) {
    final Emergency emergency=new Emergency("Emergency" + i,new Date(),"Fire" + i,10);
    tasks.add(new Callable<Void>(){
      public Void call() throws Exception {
        helper.invokeInform("me","you",emergency);
        helper.invokeRequest("coordinateEmergency",new LinkedHashMap<String,Object>());
        helper.getReturn(false);
        return null;
      }
    }
);
  }
  ExecutorService executorService=Executors.newFixedThreadPool(THREAD_COUNT);
  List<Future<Void>> futures=executorService.invokeAll(tasks);
  assertEquals(futures.size(),EMERGENCY_COUNT);
}
 

Example 42

From project enterprise, under directory /ha/src/test/java/slavetest/.

Source file: SingleJvmWithNettyTest.java

  17 
vote

@Test public void lockWaitTimeoutShouldHaveSilentTxFinishRollingBackToNotHideOriginalException() throws Exception {
  final long lockTimeout=1;
  initializeDbs(1,stringMap(HaSettings.lock_read_timeout.name(),String.valueOf(lockTimeout)));
  final Long otherNodeId=executeJob(new CommonJobs.CreateNodeJob(true),0);
  final Fetcher<DoubleLatch> latchFetcher=getDoubleLatch();
  ExecutorService executor=newFixedThreadPool(1);
  final long refNodeId=getMasterHaDb().getReferenceNode().getId();
  Future<Void> lockHolder=executor.submit(new Callable<Void>(){
    @Override public Void call() throws Exception {
      executeJobOnMaster(new CommonJobs.HoldLongLock(refNodeId,latchFetcher));
      return null;
    }
  }
);
  DoubleLatch latch=latchFetcher.fetch();
  latch.awaitFirst();
  try {
    executeJob(new CommonJobs.SetNodePropertyWithThrowJob(otherNodeId.longValue(),refNodeId,"key","value"),0);
    fail("Should've failed");
  }
 catch (  ComException e) {
  }
  latch.countDownSecond();
  assertNull(lockHolder.get());
}
 

Example 43

From project example-projects, under directory /exo-jcr-example/src/test/java/org/example/.

Source file: HelloBeanTest.java

  17 
vote

@Test public void testSayHello_String(){
  ExecutorService executor1=Executors.newSingleThreadExecutor();
  ExecutorService executor2=Executors.newSingleThreadExecutor();
  for (int i=0; i < 1; i++) {
    executor1.execute(new HelloTask("root"));
    executor2.execute(new HelloTask("john"));
  }
  executor1.shutdown();
  executor2.shutdown();
  try {
    executor1.awaitTermination(30,TimeUnit.SECONDS);
    executor2.awaitTermination(30,TimeUnit.SECONDS);
  }
 catch (  InterruptedException e) {
    e.printStackTrace();
  }
  assertTrue(true);
}
 

Example 44

From project FBReaderJ, under directory /src/org/geometerplus/zlibrary/ui/android/image/.

Source file: ZLAndroidImageLoader.java

  17 
vote

void startImageLoading(final ZLLoadableImage image,Runnable postLoadingRunnable){
  LinkedList<Runnable> runnables=myOnImageSyncRunnables.get(image.getId());
  if (runnables != null) {
    if (!runnables.contains(postLoadingRunnable)) {
      runnables.add(postLoadingRunnable);
    }
    return;
  }
  runnables=new LinkedList<Runnable>();
  runnables.add(postLoadingRunnable);
  myOnImageSyncRunnables.put(image.getId(),runnables);
  final ExecutorService pool=image.sourceType() == ZLLoadableImage.SourceType.DISK ? mySinglePool : myPool;
  pool.execute(new Runnable(){
    public void run(){
      image.synchronize();
      myImageSynchronizedHandler.fireMessage(image.getId());
    }
  }
);
}
 

Example 45

From project flume, under directory /flume-ng-channels/flume-jdbc-channel/src/test/java/org/apache/flume/channel/jdbc/.

Source file: BaseJdbcChannelProviderTest.java

  17 
vote

/** 
 * Creates 120 events split over 10 channels, stores them via multiple simulated sources and consumes them via multiple simulated channels.
 */
@Test public void testEventWithSimulatedSourceAndSinks() throws Exception {
  provider=new JdbcChannelProviderImpl();
  provider.initialize(derbyCtx);
  Map<String,List<MockEvent>> eventMap=new HashMap<String,List<MockEvent>>();
  for (int i=1; i < 121; i++) {
    MockEvent me=MockEventUtils.generateMockEvent(i,i,i,61 % i,10);
    List<MockEvent> meList=eventMap.get(me.getChannel());
    if (meList == null) {
      meList=new ArrayList<MockEvent>();
      eventMap.put(me.getChannel(),meList);
    }
    meList.add(me);
  }
  List<MockSource> sourceList=new ArrayList<MockSource>();
  List<MockSink> sinkList=new ArrayList<MockSink>();
  for (  String channel : eventMap.keySet()) {
    List<MockEvent> meList=eventMap.get(channel);
    sourceList.add(new MockSource(channel,meList,provider));
    sinkList.add(new MockSink(channel,meList,provider));
  }
  ExecutorService sourceExecutor=Executors.newFixedThreadPool(10);
  ExecutorService sinkExecutor=Executors.newFixedThreadPool(10);
  List<Future<Integer>> srcResults=sourceExecutor.invokeAll(sourceList,300,TimeUnit.SECONDS);
  Thread.sleep(MockEventUtils.generateSleepInterval(3000));
  List<Future<Integer>> sinkResults=sinkExecutor.invokeAll(sinkList,300,TimeUnit.SECONDS);
  int srcCount=0;
  for (  Future<Integer> srcOutput : srcResults) {
    srcCount+=srcOutput.get();
  }
  Assert.assertEquals(120,srcCount);
  int sinkCount=0;
  for (  Future<Integer> sinkOutput : sinkResults) {
    sinkCount+=sinkOutput.get();
  }
  Assert.assertEquals(120,sinkCount);
}
 

Example 46

From project gephi-toolkit-demos, under directory /src/org/gephi/toolkit/demos/.

Source file: ParallelWorkspace.java

  17 
vote

public void script(){
  ProjectController pc=Lookup.getDefault().lookup(ProjectController.class);
  pc.newProject();
  final Workspace workspace1=pc.getCurrentWorkspace();
  Container container=Lookup.getDefault().lookup(ContainerFactory.class).newContainer();
  RandomGraph randomGraph=new RandomGraph();
  randomGraph.setNumberOfNodes(500);
  randomGraph.setWiringProbability(0.005);
  randomGraph.generate(container.getLoader());
  ImportController importController=Lookup.getDefault().lookup(ImportController.class);
  importController.process(container,new DefaultProcessor(),workspace1);
  final Workspace workspace2=pc.duplicateWorkspace(workspace1);
  ExecutorService executor=Executors.newFixedThreadPool(2);
  Future<?> f1=executor.submit(createLayoutRunnable(workspace1));
  Future<?> f2=executor.submit(createLayoutRunnable(workspace2));
  try {
    f1.get();
    f2.get();
  }
 catch (  Exception ex) {
    Exceptions.printStackTrace(ex);
  }
  executor.shutdown();
  ExportController ec=Lookup.getDefault().lookup(ExportController.class);
  try {
    pc.openWorkspace(workspace1);
    ec.exportFile(new File("parallel_worspace1.pdf"));
    pc.openWorkspace(workspace2);
    ec.exportFile(new File("parallel_worspace2.pdf"));
  }
 catch (  IOException ex) {
    Exceptions.printStackTrace(ex);
    return;
  }
}
 

Example 47

From project gibson, under directory /gibson-appender/src/test/java/org/ardverk/gibson/appender/.

Source file: ExampleIT.java

  17 
vote

public static void main(String[] args) throws InterruptedException {
  Runnable task=new Runnable(){
    @Override public void run(){
      while (true) {
        try {
          logger().error(log(),createThrowable(msg(),5 + GENERATOR.nextInt(10)));
        }
 catch (        Exception err) {
          logger().error("Excpetion",err);
        }
        try {
          Thread.sleep(25);
        }
 catch (        InterruptedException ignore) {
        }
      }
    }
  }
;
  ExecutorService executor=Executors.newCachedThreadPool();
  for (int i=0; i < 4; i++) {
    executor.execute(task);
  }
  Thread.sleep(Long.MAX_VALUE);
}
 

Example 48

From project gnip4j, under directory /core/src/main/java/com/zaubersoftware/gnip4j/api/impl/.

Source file: DefaultGnipFacade.java

  17 
vote

@Override public final GnipStream createStream(final String account,final String streamName,final StreamNotification observer){
  final ExecutorService executor=Executors.newFixedThreadPool(streamDefaultWorkers);
  final GnipStream target=createStream(account,streamName,observer,executor);
  return new GnipStream(){
    @Override public void close(){
      try {
        target.close();
      }
  finally {
        executor.shutdown();
      }
    }
    @Override public void await() throws InterruptedException {
      target.await();
    }
    @Override public final String getStreamName(){
      return target.getStreamName();
    }
    @Override public StreamStats getStreamStats(){
      return target.getStreamStats();
    }
  }
;
}
 

Example 49

From project google-gson, under directory /src/test/java/com/google/gson/functional/.

Source file: ConcurrencyTest.java

  17 
vote

/** 
 * Source-code based on http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
 */
public void testMultiThreadSerialization() throws InterruptedException {
  final CountDownLatch startLatch=new CountDownLatch(1);
  final CountDownLatch finishedLatch=new CountDownLatch(10);
  final AtomicBoolean failed=new AtomicBoolean(false);
  ExecutorService executor=Executors.newFixedThreadPool(10);
  for (int taskCount=0; taskCount < 10; taskCount++) {
    executor.execute(new Runnable(){
      public void run(){
        MyObject myObj=new MyObject();
        try {
          startLatch.await();
          for (int i=0; i < 10; i++) {
            gson.toJson(myObj);
          }
        }
 catch (        Throwable t) {
          failed.set(true);
        }
 finally {
          finishedLatch.countDown();
        }
      }
    }
);
  }
  startLatch.countDown();
  finishedLatch.await();
  assertFalse(failed.get());
}
 

Example 50

From project gora, under directory /gora-hbase/src/test/java/org/apache/gora/hbase/util/.

Source file: TestHBaseByteInterface.java

  17 
vote

@Test public void testEncodingDecodingMultithreaded() throws Exception {
  int numThreads=8;
  ExecutorService pool=Executors.newFixedThreadPool(numThreads);
  Collection<Callable<Integer>> tasks=new ArrayList<Callable<Integer>>();
  for (int i=0; i < numThreads; i++) {
    tasks.add(new Callable<Integer>(){
      @Override public Integer call(){
        try {
          testEncodingDecoding();
          return 0;
        }
 catch (        Exception e) {
          e.printStackTrace();
          return 1;
        }
      }
    }
);
  }
  List<Future<Integer>> results=pool.invokeAll(tasks);
  for (  Future<Integer> result : results) {
    Assert.assertEquals(0,(int)result.get());
  }
}
 

Example 51

From project grouperfish, under directory /service/src/main/java/com/mozilla/grouperfish/util/loader/.

Source file: Loader.java

  17 
vote

/** 
 * Loads document into Grouperfish using a multithreaded client. Returns the number of document loaded.
 */
public int load(Iterable<T> stream){
  log.debug("Starting import into map '{}'",baseUrl_);
  final ExecutorService workers=workers();
  int i=1;
  List<T> batch=new ArrayList<T>(BATCH_SIZE);
  for (  T item : stream) {
    batch.add(item);
    if (i % BATCH_SIZE == 0) {
      workers.submit(new InsertTask<T>(baseUrl_,batch));
      batch=new ArrayList<T>(BATCH_SIZE);
    }
    if (i % 5000 == 0) {
      log.info("Queued {} items into map {}",i,baseUrl_);
    }
    ++i;
  }
  if (!batch.isEmpty()) {
    workers.submit(new InsertTask<T>(baseUrl_,batch));
  }
  shutdownGracefully(workers);
  return i - 1;
}
 

Example 52

From project gson, under directory /gson/src/test/java/com/google/gson/functional/.

Source file: ConcurrencyTest.java

  17 
vote

/** 
 * Source-code based on http://groups.google.com/group/google-gson/browse_thread/thread/563bb51ee2495081
 */
public void testMultiThreadSerialization() throws InterruptedException {
  final CountDownLatch startLatch=new CountDownLatch(1);
  final CountDownLatch finishedLatch=new CountDownLatch(10);
  final AtomicBoolean failed=new AtomicBoolean(false);
  ExecutorService executor=Executors.newFixedThreadPool(10);
  for (int taskCount=0; taskCount < 10; taskCount++) {
    executor.execute(new Runnable(){
      public void run(){
        MyObject myObj=new MyObject();
        try {
          startLatch.await();
          for (int i=0; i < 10; i++) {
            gson.toJson(myObj);
          }
        }
 catch (        Throwable t) {
          failed.set(true);
        }
 finally {
          finishedLatch.countDown();
        }
      }
    }
);
  }
  startLatch.countDown();
  finishedLatch.await();
  assertFalse(failed.get());
}
 

Example 53

From project guice-jit-providers, under directory /core/test/com/google/inject/.

Source file: InjectorTest.java

  17 
vote

public void testJitBindingFromAnotherThreadDuringInjection(){
  final ExecutorService executorService=Executors.newSingleThreadExecutor();
  final AtomicReference<JustInTime> got=new AtomicReference<JustInTime>();
  Guice.createInjector(new AbstractModule(){
    protected void configure(){
      requestInjection(new Object(){
        @Inject void initialize(        final Injector injector) throws ExecutionException, InterruptedException {
          Future<JustInTime> future=executorService.submit(new Callable<JustInTime>(){
            public JustInTime call() throws Exception {
              return injector.getInstance(JustInTime.class);
            }
          }
);
          got.set(future.get());
        }
      }
);
    }
  }
);
  assertNotNull(got.get());
}
 

Example 54

From project ha-jdbc, under directory /src/test/java/net/sf/hajdbc/balancer/.

Source file: AbstractBalancerTest.java

  17 
vote

@Test public void nextSingleWeight(){
  Balancer<Void,MockDatabase> balancer=this.factory.createBalancer(new HashSet<MockDatabase>(Arrays.asList(this.databases[0],this.databases[1])));
  assertSame(this.databases[1],balancer.next());
  int count=10;
  CountDownLatch latch=new CountDownLatch(count);
  WaitingInvoker invoker=new WaitingInvoker(latch);
  ExecutorService executor=Executors.newFixedThreadPool(count);
  List<Future<Void>> futures=new ArrayList<Future<Void>>(count);
  for (int i=0; i < count; ++i) {
    futures.add(executor.submit(new InvocationTask(balancer,invoker,this.databases[1])));
  }
  try {
    latch.await();
    assertSame(this.databases[1],balancer.next());
synchronized (invoker) {
      invoker.notifyAll();
    }
    this.complete(futures);
    assertSame(this.databases[1],balancer.next());
  }
 catch (  InterruptedException e) {
    Thread.currentThread().interrupt();
  }
 finally {
    executor.shutdownNow();
  }
}
 

Example 55

From project hank, under directory /src/java/com/rapleaf/hank/zookeeper/.

Source file: WatchedMap.java

  17 
vote

private static synchronized void detectCompletionConcurrently(ZooKeeperPlus zk,String path,Collection<String> relPaths,CompletionAwaiter awaiter,CompletionDetector completionDetector){
  final ExecutorService completionDetectionExecutor=Executors.newFixedThreadPool(NUM_CONCURRENT_COMPLETION_DETECTORS,new ThreadFactory(){
    private int threadId=0;
    @Override public Thread newThread(    Runnable runnable){
      return new Thread(runnable,"Completion Detector #" + threadId++);
    }
  }
);
  for (  String relPath : relPaths) {
    completionDetectionExecutor.execute(new DetectCompletionRunnable(zk,path,relPath,awaiter,completionDetector));
  }
  completionDetectionExecutor.shutdown();
  boolean terminated=false;
  while (!terminated) {
    try {
      terminated=completionDetectionExecutor.awaitTermination(COMPLETION_DETECTION_EXECUTOR_TERMINATION_CHECK_PERIOD,TimeUnit.MILLISECONDS);
    }
 catch (    InterruptedException e) {
      completionDetectionExecutor.shutdownNow();
    }
  }
}
 

Example 56

From project hawtjournal, under directory /src/test/java/org/fusesource/hawtjournal/api/.

Source file: JournalTest.java

  17 
vote

@Test public void testConcurrentWriteAndRead() throws Exception {
  final AtomicInteger counter=new AtomicInteger(0);
  ExecutorService executor=Executors.newFixedThreadPool(25);
  int iterations=1000;
  for (int i=0; i < iterations; i++) {
    final int index=i;
    executor.submit(new Runnable(){
      public void run(){
        try {
          boolean sync=index % 2 == 0 ? true : false;
          String write=new String("DATA" + index);
          Location location=journal.write(ByteBuffer.wrap(write.getBytes("UTF-8")),sync);
          String read=new String(journal.read(location).array(),"UTF-8");
          if (read.equals("DATA" + index)) {
            counter.incrementAndGet();
          }
 else {
            System.out.println(write);
            System.out.println(read);
          }
        }
 catch (        Exception ex) {
          ex.printStackTrace();
        }
      }
    }
);
  }
  executor.shutdown();
  assertTrue(executor.awaitTermination(1,TimeUnit.MINUTES));
  assertEquals(iterations,counter.get());
}
 

Example 57

From project hazelcast-cluster-monitor, under directory /src/main/java/com/hazelcast/monitor/server/event/.

Source file: MemberInfoEventGenerator.java

  17 
vote

public ChangeEvent generateEvent(){
  if (member == null) {
    return null;
  }
  ExecutorService esService=client.getExecutorService();
  DistributedTask<DistributedMemberInfoCallable.MemberInfo> task=new DistributedTask<DistributedMemberInfoCallable.MemberInfo>(new DistributedMemberInfoCallable(),member);
  esService.submit(task);
  DistributedMemberInfoCallable.MemberInfo result;
  try {
    result=task.get();
  }
 catch (  Exception e) {
    e.printStackTrace();
    return null;
  }
  MemberInfo memberInfo=convert(result);
  return memberInfo;
}
 

Example 58

From project hcatalog, under directory /src/test/org/apache/hcatalog/common/.

Source file: TestHiveClientCache.java

  17 
vote

/** 
 * Check that a *new* client is created if asked from different threads even with the same hive configuration
 * @throws ExecutionException
 * @throws InterruptedException
 */
@Test public void testMultipleThreadAccess() throws ExecutionException, InterruptedException {
  final HiveClientCache cache=new HiveClientCache(1000);
class GetHiveClient implements Callable<HiveMetaStoreClient> {
    @Override public HiveMetaStoreClient call() throws IOException, MetaException, LoginException {
      return cache.get(hiveConf);
    }
  }
  ExecutorService executor=Executors.newFixedThreadPool(2);
  Callable<HiveMetaStoreClient> worker1=new GetHiveClient();
  Callable<HiveMetaStoreClient> worker2=new GetHiveClient();
  Future<HiveMetaStoreClient> clientFuture1=executor.submit(worker1);
  Future<HiveMetaStoreClient> clientFuture2=executor.submit(worker2);
  HiveMetaStoreClient client1=clientFuture1.get();
  HiveMetaStoreClient client2=clientFuture2.get();
  assertNotNull(client1);
  assertNotNull(client2);
  assertNotSame(client1,client2);
}
 

Example 59

From project adbcj, under directory /jdbc/src/main/java/org/adbcj/jdbc/.

Source file: JdbcConnectionManager.java

  15 
vote

public JdbcConnectionManager(String jdbcUrl,String username,String password,ExecutorService executorService,Properties properties){
  this.jdbcUrl=jdbcUrl;
  this.properties=new Properties(properties);
  this.executorService=executorService;
  this.properties.put(USER,username);
  this.properties.put(PASSWORD,password);
}
 

Example 60

From project aether-core, under directory /aether-connector-file/src/main/java/org/eclipse/aether/connector/file/.

Source file: ParallelRepositoryConnector.java

  15 
vote

public void close(){
  this.closed=true;
  if (executor instanceof ExecutorService) {
    ((ExecutorService)executor).shutdown();
  }
}
 

Example 61

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/client/cache/.

Source file: AsynchronousValidator.java

  15 
vote

/** 
 * Create AsynchronousValidator which will make revalidation requests using the supplied  {@link CachingHttpClient} and{@link ExecutorService}.
 * @param cachingClient used to execute asynchronous requests
 * @param executor used to manage a thread pool of revalidation workers
 */
AsynchronousValidator(CachingHttpClient cachingClient,ExecutorService executor){
  this.cachingClient=cachingClient;
  this.executor=executor;
  this.queued=new HashSet<String>();
  this.cacheKeyGenerator=new CacheKeyGenerator();
}
 

Example 62

From project android-joedayz, under directory /Proyectos/GreenDroid/src/greendroid/app/.

Source file: GDApplication.java

  15 
vote

/** 
 * Return an ExecutorService (global to the entire application) that may be used by clients when running long tasks in the background.
 * @return An ExecutorService to used when processing long running tasks
 */
public ExecutorService getExecutor(){
  if (mExecutorService == null) {
    mExecutorService=Executors.newFixedThreadPool(CORE_POOL_SIZE,sThreadFactory);
  }
  return mExecutorService;
}
 

Example 63

From project android-rackspacecloud, under directory /extensions/httpnio/src/main/java/org/jclouds/http/httpnio/config/.

Source file: NioTransformingHttpCommandExecutorServiceModule.java

  15 
vote

@SuppressWarnings("unused") @Inject Factory(Closer closer,@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor,@Named(Constants.PROPERTY_MAX_CONNECTION_REUSE) int maxConnectionReuse,@Named(Constants.PROPERTY_MAX_SESSION_FAILURES) int maxSessionFailures,Provider<Semaphore> allConnections,Provider<BlockingQueue<HttpCommandRendezvous<?>>> commandQueue,Provider<BlockingQueue<NHttpConnection>> available,Provider<AsyncNHttpClientHandler> clientHandler,Provider<DefaultConnectingIOReactor> ioReactor,HttpParams params){
  this.closer=closer;
  this.executor=executor;
  this.maxConnectionReuse=maxConnectionReuse;
  this.maxSessionFailures=maxSessionFailures;
  this.allConnections=allConnections;
  this.commandQueue=commandQueue;
  this.available=available;
  this.clientHandler=clientHandler;
  this.ioReactor=ioReactor;
  this.params=params;
}
 

Example 64

From project android-service-arch, under directory /ServiceFramework/src/ru/evilduck/framework/service/.

Source file: SFThreadPoolIntentService.java

  15 
vote

protected static PoolConfigurator asFixedThreadPool(final int threadCount){
  return new PoolConfigurator(){
    @Override public ExecutorService configure(){
      return Executors.newFixedThreadPool(threadCount);
    }
  }
;
}
 

Example 65

From project Blitz, under directory /src/com/laxser/blitz/web/portal/impl/.

Source file: PortalFactoryImpl.java

  15 
vote

public void setExecutorService(ExecutorService executor){
  if (logger.isInfoEnabled()) {
    logger.info("using executorService: " + executor);
  }
  this.executorService=executor;
}
 

Example 66

From project CineShowTime-Android, under directory /Libraries/GreenDroid/src/greendroid/app/.

Source file: GDApplication.java

  15 
vote

public ExecutorService getExecutor(){
  if (mExecutorService == null) {
    mExecutorService=Executors.newFixedThreadPool(CORE_POOL_SIZE,sThreadFactory);
  }
  return mExecutorService;
}
 

Example 67

From project cleo, under directory /src/main/java/cleo/search/typeahead/.

Source file: MultiTypeahead.java

  15 
vote

public MultiTypeahead(String name,List<Typeahead<E>> typeaheads,ExecutorService executorService){
  this.name=name;
  this.typeaheads=typeaheads;
  this.typeaheadMap=new HashMap<String,Typeahead<E>>();
  for (  Typeahead<E> ta : typeaheads) {
    typeaheadMap.put(ta.getName(),ta);
  }
  this.executor=(executorService != null) ? executorService : Executors.newFixedThreadPool(100,new TypeaheadTaskThreadFactory());
  logger.info(name + " started");
}
 

Example 68

From project cloudhopper-smpp, under directory /src/main/java/com/cloudhopper/smpp/impl/.

Source file: DefaultSmppClient.java

  15 
vote

/** 
 * Creates a new default SmppClient.
 * @param executor The executor that IO workers will be executed with. AnExecutors.newCachedDaemonThreadPool() is recommended. The max threads will never grow more than expectedSessions if NIO sockets are used.
 * @param expectedSessions The max number of concurrent sessions expectedto be active at any time.  This number controls the max number of worker threads that the underlying Netty library will use.  If processing occurs in a sessionHandler (a blocking op), be <b>VERY</b> careful setting this to the correct number of concurrent sessions you expect.
 * @param monitorExecutor The scheduled executor that all sessions will shareto monitor themselves and expire requests.  If null monitoring will be disabled.
 */
public DefaultSmppClient(ExecutorService executors,int expectedSessions,ScheduledExecutorService monitorExecutor){
  this.channels=new DefaultChannelGroup();
  this.executors=executors;
  this.channelFactory=new NioClientSocketChannelFactory(this.executors,this.executors,expectedSessions);
  this.clientBootstrap=new ClientBootstrap(channelFactory);
  this.clientConnector=new SmppClientConnector(this.channels);
  this.clientBootstrap.getPipeline().addLast(SmppChannelConstants.PIPELINE_CLIENT_CONNECTOR_NAME,this.clientConnector);
  this.monitorExecutor=monitorExecutor;
}
 

Example 69

From project clustermeister, under directory /api/src/main/java/com/github/nethad/clustermeister/api/impl/.

Source file: ClustermeisterImpl.java

  15 
vote

@Override public ExecutorService getExecutorService(ExecutorServiceMode executorServiceMode){
  JPPFExecutorService executorService=new JPPFExecutorService(jppfClient);
  if (executorServiceMode != null) {
    executorServiceMode.configureJppfExecutorService(executorService);
  }
 else {
    ExecutorServiceMode.standard().configureJppfExecutorService(executorService);
  }
  executorServices.add(executorService);
  return executorService;
}
 

Example 70

From project cometd, under directory /cometd-java/cometd-websocket-jetty/src/main/java/org/cometd/websocket/server/.

Source file: WebSocketTransport.java

  15 
vote

@Override protected void destroy(){
  try {
    _factory.stop();
  }
 catch (  Exception x) {
    _logger.trace("",x);
  }
  _scheduler.shutdown();
  Executor threadPool=_executor;
  if (threadPool instanceof ExecutorService) {
    ((ExecutorService)threadPool).shutdown();
  }
 else   if (threadPool instanceof LifeCycle) {
    try {
      ((LifeCycle)threadPool).stop();
    }
 catch (    Exception x) {
      _logger.trace("",x);
    }
  }
  super.destroy();
}
 

Example 71

From project commons-j, under directory /src/main/java/nerds/antelax/commons/net/pubsub/.

Source file: ClientMessageHandler.java

  15 
vote

ClientMessageHandler(final ExecutorService callbackService){
  Preconditions.checkNotNull(callbackService,"ExecutorService cannot be null");
  activeChannel=new AtomicReference<Channel>(null);
  this.callbackService=callbackService;
  subscribers=new ConcurrentHashMap<String,Collection<PubSubClient.MessageCallback>>();
  lock=new ReentrantLock();
}
 

Example 72

From project droidparts, under directory /extra/src/org/droidparts/util/.

Source file: ImageAttacher.java

  15 
vote

public ImageAttacher(BitmapCacher bitmapCacher,ExecutorService executorService,RESTClient restClient){
  this.bitmapCacher=bitmapCacher;
  this.executorService=executorService;
  this.restClient=restClient;
  handler=new Handler(Looper.getMainLooper());
}
 

Example 73

From project gda-common, under directory /uk.ac.gda.common/src/gda/util/.

Source file: OSCommandRunner.java

  15 
vote

private static void _runNoWait(final List<String> _commands,final LOGOPTION logOption,final String stdInFileName,final Map<? extends String,? extends String> envPutAll,final List<String> envRemove,ExecutorService executor){
  Runnable r=new Runnable(){
    @Override public void run(){
      OSCommandRunner osCommandRunner=new OSCommandRunner(_commands,logOption != LOGOPTION.NEVER,stdInFileName,null,envPutAll,envRemove);
      if (osCommandRunner.exception != null) {
        String msg="Exception seen trying to run command " + osCommandRunner.getCommandAsString();
        logger.error(msg);
        logger.error(osCommandRunner.exception.toString());
      }
 else       if (osCommandRunner.exitValue != 0) {
        String msg="Exit code = " + Integer.toString(osCommandRunner.exitValue) + " returned from command "+ osCommandRunner.getCommandAsString();
        logger.warn(msg);
        if (logOption != LOGOPTION.NEVER) {
          osCommandRunner.logOutput();
        }
      }
 else {
        if (logOption == LOGOPTION.ALWAYS) {
          osCommandRunner.logOutput();
        }
      }
    }
  }
;
  if (executor != null) {
    executor.submit(r);
  }
 else {
    new Thread(r,OSCommandRunner.class.getSimpleName()).start();
  }
}
 

Example 74

From project giraph, under directory /src/main/java/org/apache/giraph/utils/.

Source file: ProgressableUtils.java

  15 
vote

/** 
 * Wait maximum given number of milliseconds for executor tasks to terminate, while periodically reporting progress.
 * @param executor Executor which we are waiting for
 * @param progressable Progressable for reporting progress (Job context)
 * @param remainingWaitMsecs Number of milliseconds to wait
 * @return Whether all executor tasks terminated or not
 */
public static boolean awaitExecutorTermination(ExecutorService executor,Progressable progressable,int remainingWaitMsecs){
  long timeoutTimeMsecs=System.currentTimeMillis() + remainingWaitMsecs;
  int currentWaitMsecs;
  while (true) {
    currentWaitMsecs=Math.min(remainingWaitMsecs,MSEC_PERIOD);
    try {
      if (executor.awaitTermination(currentWaitMsecs,TimeUnit.MILLISECONDS)) {
        return true;
      }
    }
 catch (    InterruptedException e) {
      throw new IllegalStateException("awaitExecutorTermination: " + "InterruptedException occurred while waiting for executor's " + "tasks to terminate",e);
    }
    if (LOG.isInfoEnabled()) {
      LOG.info("awaitExecutorTermination: " + "Waiting for executor tasks to terminate " + executor.toString());
    }
    if (System.currentTimeMillis() >= timeoutTimeMsecs) {
      return false;
    }
    progressable.progress();
    remainingWaitMsecs=Math.max(0,remainingWaitMsecs - currentWaitMsecs);
  }
}
 

Example 75

From project GreenDroid, under directory /GreenDroid/src/greendroid/app/.

Source file: GDApplication.java

  15 
vote

/** 
 * Return an ExecutorService (global to the entire application) that may be used by clients when running long tasks in the background.
 * @return An ExecutorService to used when processing long running tasks
 */
public ExecutorService getExecutor(){
  if (mExecutorService == null) {
    mExecutorService=Executors.newFixedThreadPool(CORE_POOL_SIZE,sThreadFactory);
  }
  return mExecutorService;
}
 

Example 76

From project GreenDroidQABar, under directory /src/greendroid/app/.

Source file: GDApplication.java

  15 
vote

public ExecutorService getExecutor(){
  if (mExecutorService == null) {
    mExecutorService=Executors.newFixedThreadPool(CORE_POOL_SIZE,sThreadFactory);
  }
  return mExecutorService;
}
 

Example 77

From project griffon, under directory /subprojects/griffon-rt/src/main/groovy/griffon/core/.

Source file: UIThreadManager.java

  15 
vote

public Future call(Object[] args){
  if (args.length == 1 && args[0] instanceof Callable) {
    return INSTANCE.executeFuture((Callable)args[0]);
  }
 else   if (args.length == 2 && args[0] instanceof ExecutorService && args[1] instanceof Callable) {
    return INSTANCE.executeFuture((ExecutorService)args[0],(Callable)args[1]);
  }
  throw new MissingMethodException(EXECUTE_FUTURE,UIThreadManager.class,args);
}
 

Example 78

From project gxa, under directory /atlas-analytics/src/main/java/uk/ac/ebi/gxa/analytics/generator/service/.

Source file: ExperimentAnalyticsGeneratorService.java

  15 
vote

public ExperimentAnalyticsGeneratorService(AtlasDAO atlasDAO,AtlasDataDAO atlasDataDAO,AtlasComputeService atlasComputeService,ExecutorService executor){
  this.atlasDAO=atlasDAO;
  this.atlasDataDAO=atlasDataDAO;
  this.atlasComputeService=atlasComputeService;
  this.executor=executor;
}
 

Example 79

From project HBase-Lattice, under directory /hbl/src/main/java/com/inadco/hbl/client/.

Source file: HblQueryClient.java

  15 
vote

private void init(Configuration conf,ExecutorService es,int maxThreads) throws IOException {
  Validate.notNull(conf);
  this.conf=conf;
  if (maxThreads <= 0)   maxThreads=DEFAULT_MAX_THREADS;
 else   if (maxThreads < 3)   maxThreads=3;
  if (es == null) {
    ThreadPoolExecutor tpe=new ThreadPoolExecutor(3,maxThreads,5,TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(DEFAULT_QUEUE_SIZE));
    tpe.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
    closeables.addFirst(new IOUtil.ExecutorServiceCloseable(tpe,30));
    tpe.setThreadFactory(new ThreadFactory(){
      @Override public Thread newThread(      Runnable r){
        Thread t=Executors.defaultThreadFactory().newThread(r);
        t.setPriority(Thread.NORM_PRIORITY + 1);
        return t;
      }
    }
);
    tpe.prestartAllCoreThreads();
    es=tpe;
  }
  Validate.notNull(es);
  this.es=es;
  tpool=new HTablePool(conf,400);
  closeables.addFirst(tpool);
}