Java Code Examples for java.util.concurrent.Executor

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 androidannotations, under directory /AndroidAnnotations/functional-test-1-5-tests/src/test/java/com/googlecode/androidannotations/test15/.

Source file: ThreadActivityTest.java

  18 
vote

@Test public void backgroundDelegatesToExecutor(){
  Executor executor=mock(Executor.class);
  BackgroundExecutor.setExecutor(executor);
  activity.emptyBackgroundMethod();
  verify(executor).execute(Mockito.<Runnable>any());
}
 

Example 2

From project android_packages_apps_QuickSearchBox, under directory /src/com/android/quicksearchbox/.

Source file: SearchableCorpusFactory.java

  18 
vote

protected Corpus createWebCorpus(Sources sources){
  Source webSource=sources.getWebSearchSource();
  if (webSource != null && !webSource.canRead()) {
    Log.w(TAG,"Can't read web source " + webSource.getName());
    webSource=null;
  }
  Source browserSource=getBrowserSource(sources);
  if (browserSource != null && !browserSource.canRead()) {
    Log.w(TAG,"Can't read browser source " + browserSource.getName());
    browserSource=null;
  }
  Executor executor=createWebCorpusExecutor();
  return new WebCorpus(mContext,mConfig,executor,webSource,browserSource);
}
 

Example 3

From project capedwarf-blue, under directory /common/src/main/java/org/jboss/capedwarf/common/threads/.

Source file: ExecutorFactory.java

  18 
vote

/** 
 * Get Executor instance. First lookup JNDI, then use default if none found.
 * @return the Executor instance
 */
public static Executor getInstance(){
  if (executor == null) {
synchronized (ExecutorFactory.class) {
      if (executor == null) {
        final Executor tmp=doJndiLookup();
        executor=(tmp != null) ? tmp : createDefaultExecutor();
      }
    }
  }
  return executor;
}
 

Example 4

From project galaxy, under directory /src/co/paralleluniverse/common/concurrent/.

Source file: OrderedThreadPoolExecutor.java

  18 
vote

protected Executor getChildExecutor(Runnable task){
  Object key=getChildExecutorKey(task);
  Executor executor=childExecutors.get(key);
  if (executor == null) {
    executor=new ChildExecutor();
    Executor oldExecutor=childExecutors.putIfAbsent(key,executor);
    if (oldExecutor != null) {
      executor=oldExecutor;
    }
  }
  return executor;
}
 

Example 5

From project jdg, under directory /infinispan/src/main/java/org/jboss/as/clustering/infinispan/.

Source file: ExecutorProvider.java

  18 
vote

/** 
 * {@inheritDoc}
 * @see org.infinispan.executors.ExecutorFactory#getExecutor(java.util.Properties)
 */
@Override public ExecutorService getExecutor(Properties properties){
  Executor executor=(Executor)properties.get(EXECUTOR);
  if (executor == null) {
    throw MESSAGES.invalidExecutorProperty(EXECUTOR,properties);
  }
  return new ManagedExecutorService(executor);
}
 

Example 6

From project jolokia, under directory /agent/jvm/src/main/java/org/jolokia/jvmagent/.

Source file: JolokiaServer.java

  18 
vote

private void initializeExecutor(){
  Executor executor;
  String mode=config.getExecutor();
  if ("fixed".equalsIgnoreCase(mode)) {
    executor=Executors.newFixedThreadPool(config.getThreadNr(),daemonThreadFactory);
  }
 else   if ("cached".equalsIgnoreCase(mode)) {
    executor=Executors.newCachedThreadPool(daemonThreadFactory);
  }
 else {
    executor=Executors.newSingleThreadExecutor(daemonThreadFactory);
  }
  httpServer.setExecutor(executor);
}
 

Example 7

From project sesam, under directory /sesam-bundles/sesam-monitor/src/main/java/be/vlaanderen/sesam/monitor/internal/util/.

Source file: ThreadPoolTaskScheduler.java

  18 
vote

public void execute(Runnable task){
  Executor executor=getScheduledExecutor();
  try {
    executor.execute(errorHandlingTask(task,false));
  }
 catch (  RejectedExecutionException ex) {
    throw new TaskRejectedException("Executor [" + executor + "] did not accept task: "+ task,ex);
  }
}
 

Example 8

From project shiro, under directory /core/src/test/java/org/apache/shiro/concurrent/.

Source file: SubjectAwareExecutorTest.java

  18 
vote

@Test public void testExecute(){
  Executor targetMockExecutor=createNiceMock(Executor.class);
  targetMockExecutor.execute(isA(SubjectRunnable.class));
  replay(targetMockExecutor);
  final SubjectAwareExecutor executor=new SubjectAwareExecutor(targetMockExecutor);
  Runnable work=new Runnable(){
    public void run(){
      System.out.println("Hello World");
    }
  }
;
  executor.execute(work);
  verify(targetMockExecutor);
}
 

Example 9

From project spring-js, under directory /src/main/java/org/springframework/scheduling/concurrent/.

Source file: ThreadPoolTaskExecutor.java

  18 
vote

public void execute(Runnable task){
  Executor executor=getThreadPoolExecutor();
  try {
    executor.execute(task);
  }
 catch (  RejectedExecutionException ex) {
    throw new TaskRejectedException("Executor [" + executor + "] did not accept task: "+ task,ex);
  }
}
 

Example 10

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

Source file: WagonRepositoryConnector.java

  17 
vote

private Executor getExecutor(int threads){
  if (threads <= 1) {
    return new Executor(){
      public void execute(      Runnable command){
        command.run();
      }
    }
;
  }
 else {
    return new ThreadPoolExecutor(threads,threads,3,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
  }
}
 

Example 11

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

Source file: AbstractExecutionThreadService.java

  17 
vote

/** 
 * Returns the  {@link Executor} that will be used to run this service.Subclasses may override this method to use a custom  {@link Executor}, which may configure its worker thread with a specific name, thread group or priority. The returned executor's  {@link Executor#execute(Runnable) execute()} method is called when this service is started, and should returnpromptly.
 */
protected Executor executor(){
  return new Executor(){
    public void execute(    Runnable command){
      new Thread(command,AbstractExecutionThreadService.this.toString()).start();
    }
  }
;
}
 

Example 12

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

Source file: TestLibraryBehaviors.java

  17 
vote

@Test public void testListenableFuture() throws Exception {
  final Executor e=Executors.newFixedThreadPool(2);
  final CountDownLatch latch=new CountDownLatch(1);
  ListenableFutureTask<String> t=ListenableFutureTask.create(new Callable<String>(){
    public String call() throws Exception {
      latch.countDown();
      return "hello world";
    }
  }
);
  final CountDownLatch listener_latch=new CountDownLatch(1);
  t.addListener(new Runnable(){
    public void run(){
      listener_latch.countDown();
    }
  }
,e);
  e.execute(t);
  assertThat(latch.await(1,TimeUnit.SECONDS),equalTo(true));
  assertThat(listener_latch.await(1,TimeUnit.SECONDS),equalTo(true));
}
 

Example 13

From project chililog-server, under directory /src/main/java/org/chililog/server/pubsub/jsonhttp/.

Source file: JsonHttpService.java

  17 
vote

/** 
 * Start all pubsub services
 */
public synchronized void start(){
  _mqProducerSessionPool=new MqProducerSessionPool(AppProperties.getInstance().getPubSubJsonHttpNettyHandlerThreadPoolSize());
  AppProperties appProperties=AppProperties.getInstance();
  if (_channelFactory != null) {
    _logger.info("PubSub JSON HTTP Web Sever Already Started.");
    return;
  }
  _logger.info("Starting PubSub JSON HTTP  Web Sever on " + appProperties.getPubSubJsonHttpHost() + ":"+ appProperties.getPubSubJsonHttpPort()+ "...");
  int workerCount=appProperties.getPubSubJsonHttpNettyWorkerThreadPoolSize();
  if (workerCount == 0) {
    _channelFactory=new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool());
  }
 else {
    _channelFactory=new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool(),workerCount);
  }
  ServerBootstrap bootstrap=new ServerBootstrap(_channelFactory);
  Executor executor=Executors.newFixedThreadPool(appProperties.getPubSubJsonHttpNettyHandlerThreadPoolSize());
  bootstrap.setPipelineFactory(new JsonHttpServerPipelineFactory(executor));
  String[] hosts=TransportConfiguration.splitHosts(appProperties.getPubSubJsonHttpHost());
  for (  String h : hosts) {
    if (StringUtils.isBlank(h)) {
      if (hosts.length == 1) {
        h="0.0.0.0";
      }
 else {
        continue;
      }
    }
    SocketAddress address=h.equals("0.0.0.0") ? new InetSocketAddress(appProperties.getPubSubJsonHttpPort()) : new InetSocketAddress(h,appProperties.getPubSubJsonHttpPort());
    Channel channel=bootstrap.bind(address);
    _allChannels.add(channel);
  }
  _logger.info("PubSub JSON HTTP Web Sever Started.");
}
 

Example 14

From project collector, under directory /src/main/java/com/ning/metrics/collector/endpoint/servers/.

Source file: ScribeServer.java

  17 
vote

/** 
 * Start the terminal Scribe server
 * @throws TTransportException if the TNonblockingServerSocket cannot be instantiated
 */
public void start() throws TTransportException {
  final Executor executor=new FailsafeScheduledExecutor(1,"ScribeServer");
  executor.execute(new Runnable(){
    @Override public void run(){
      try {
        final TNonblockingServerTransport socket=new TNonblockingServerSocket(config.getScribePort());
        final TProcessor processor=new Processor(eventRequestHandler);
        server=new TNonblockingServer(new TNonblockingServer.Args(socket).processor(processor).protocolFactory(new TBinaryProtocol.Factory()));
        log.info(String.format("Starting terminal Scribe server on port %d",config.getScribePort()));
        server.serve();
      }
 catch (      TTransportException e) {
        log.warn("Unable to start the Scribe server",e);
        Thread.currentThread().interrupt();
      }
    }
  }
);
}
 

Example 15

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

Source file: WebSocketTransport.java

  17 
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 16

From project commons-io, under directory /src/test/java/org/apache/commons/io/input/.

Source file: TailerTest.java

  17 
vote

public void testStopWithNoFileUsingExecutor() throws Exception {
  final File file=new File(getTestDirectory(),"nosuchfile");
  assertFalse("nosuchfile should not exist",file.exists());
  TestTailerListener listener=new TestTailerListener();
  int delay=100;
  int idle=50;
  tailer=new Tailer(file,listener,delay,false);
  Executor exec=new ScheduledThreadPoolExecutor(1);
  exec.execute(tailer);
  Thread.sleep(idle);
  tailer.stop();
  tailer=null;
  Thread.sleep(delay + idle);
  assertNull("Should not generate Exception",listener.exception);
  assertEquals("Expected init to be called",1,listener.initialised);
  assertTrue("fileNotFound should be called",listener.notFound > 0);
  assertEquals("fileRotated should be not be called",0,listener.rotated);
}
 

Example 17

From project flazr, under directory /src/main/java/com/flazr/rtmp/proxy/.

Source file: RtmpProxy.java

  17 
vote

public static void main(String[] args) throws Exception {
  Executor executor=Executors.newCachedThreadPool();
  ChannelFactory factory=new NioServerSocketChannelFactory(executor,executor);
  ServerBootstrap sb=new ServerBootstrap(factory);
  ClientSocketChannelFactory cf=new NioClientSocketChannelFactory(executor,executor);
  sb.setPipelineFactory(new ProxyPipelineFactory(cf,RtmpConfig.PROXY_REMOTE_HOST,RtmpConfig.PROXY_REMOTE_PORT));
  InetSocketAddress socketAddress=new InetSocketAddress(RtmpConfig.PROXY_PORT);
  sb.bind(socketAddress);
  logger.info("proxy server started, listening on {}",socketAddress);
  Thread monitor=new StopMonitor(RtmpConfig.PROXY_STOP_PORT);
  monitor.start();
  monitor.join();
  ChannelGroupFuture future=ALL_CHANNELS.close();
  logger.info("closing channels");
  future.awaitUninterruptibly();
  logger.info("releasing resources");
  factory.releaseExternalResources();
  logger.info("server stopped");
}
 

Example 18

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

Source file: TestFileChannelEncryption.java

  17 
vote

/** 
 * Test fails without FLUME-1565
 */
@Test public void testThreadedConsume() throws Exception {
  int numThreads=20;
  Map<String,String> overrides=getOverridesForEncryption();
  overrides.put(FileChannelConfiguration.CAPACITY,String.valueOf(10000));
  channel=createFileChannel(overrides);
  channel.start();
  Assert.assertTrue(channel.isOpen());
  Executor executor=Executors.newFixedThreadPool(numThreads);
  Set<String> in=fillChannel(channel,"threaded-consume");
  final AtomicBoolean error=new AtomicBoolean(false);
  final CountDownLatch startLatch=new CountDownLatch(numThreads);
  final CountDownLatch stopLatch=new CountDownLatch(numThreads);
  final Set<String> out=Collections.synchronizedSet(new HashSet<String>());
  for (int i=0; i < numThreads; i++) {
    executor.execute(new Runnable(){
      @Override public void run(){
        try {
          startLatch.countDown();
          startLatch.await();
          out.addAll(takeEvents(channel,10));
        }
 catch (        Throwable t) {
          error.set(true);
          LOGGER.error("Error in take thread",t);
        }
 finally {
          stopLatch.countDown();
        }
      }
    }
);
  }
  stopLatch.await();
  Assert.assertFalse(error.get());
  compareInputAndOut(in,out);
}
 

Example 19

From project hotpotato, under directory /src/main/java/com/biasedbit/hotpotato/client/.

Source file: AbstractHttpClient.java

  17 
vote

protected void openConnection(final HostContext context){
  final ChannelPipeline pipeline;
  try {
    pipeline=this.pipelineFactory.getPipeline();
  }
 catch (  Exception e) {
    LOG.error("Failed to create pipeline.",e);
    return;
  }
  context.getConnectionPool().connectionOpening();
  String id=new StringBuilder().append(this.hostId(context)).append("-").append(this.connectionCounter++).toString();
  Executor writeDelegator=this.useNio ? null : this.executor;
  final HttpConnection connection=this.connectionFactory.createConnection(id,context.getHost(),context.getPort(),this,this.timeoutManager,writeDelegator);
  pipeline.addLast("handler",connection);
  this.executor.execute(new Runnable(){
    @Override public void run(){
      ClientBootstrap bootstrap=new ClientBootstrap(channelFactory);
      bootstrap.setOption("reuseAddress",true);
      bootstrap.setOption("connectTimeoutMillis",connectionTimeoutInMillis);
      bootstrap.setPipeline(pipeline);
      bootstrap.connect(new InetSocketAddress(context.getHost(),context.getPort())).addListener(new ChannelFutureListener(){
        @Override public void operationComplete(        ChannelFuture future) throws Exception {
          if (future.isSuccess()) {
            channelGroup.add(future.getChannel());
          }
        }
      }
);
    }
  }
);
}
 

Example 20

From project http-client, under directory /src/main/java/com/biasedbit/http/client/.

Source file: AbstractHttpClient.java

  17 
vote

protected void openConnection(final HostContext context){
  final ChannelPipeline pipeline;
  try {
    pipeline=this.pipelineFactory.getPipeline();
  }
 catch (  Exception e) {
    System.err.println("Failed to create pipeline.");
    e.printStackTrace();
    return;
  }
  context.getConnectionPool().connectionOpening();
  String id=new StringBuilder().append(this.hostId(context)).append("-").append(this.connectionCounter++).toString();
  Executor writeDelegator=this.useNio ? null : this.executor;
  final HttpConnection connection=this.connectionFactory.createConnection(id,context.getHost(),context.getPort(),this,this.timeoutManager,writeDelegator);
  pipeline.addLast("handler",connection);
  this.executor.execute(new Runnable(){
    @Override public void run(){
      ClientBootstrap bootstrap=new ClientBootstrap(channelFactory);
      bootstrap.setOption("reuseAddress",true);
      bootstrap.setOption("connectTimeoutMillis",connectionTimeoutInMillis);
      bootstrap.setPipeline(pipeline);
      ChannelFuture future=bootstrap.connect(new InetSocketAddress(context.getHost(),context.getPort()));
      future.addListener(new ChannelFutureListener(){
        @Override public void operationComplete(        ChannelFuture future) throws Exception {
          if (future.isSuccess()) {
            channelGroup.add(future.getChannel());
          }
        }
      }
);
    }
  }
);
}
 

Example 21

From project jboss-msc, under directory /src/test/java/org/jboss/msc/services/http/.

Source file: HttpServerService.java

  17 
vote

public synchronized void start(final StartContext context) throws StartException {
  final Executor executor=this.executor;
  final HttpServer server;
  try {
    server=HttpServer.create();
    server.setExecutor(executor);
    server.bind(bindAddress,backlog);
    server.start();
  }
 catch (  IOException e) {
    throw new StartException("Failed to start web server",e);
  }
  this.server=new HttpServerWrapper(server);
  realServer=server;
}
 

Example 22

From project odata4j, under directory /odata4j-jersey/src/main/java/org/odata4j/jersey/producer/server/.

Source file: JerseyServer.java

  17 
vote

/** 
 * stop synchronously, handy for unit test scenarios.
 * @param delaySeconds
 * @return
 */
public JerseyServer stop(int delaySeconds){
  server.stop(delaySeconds);
  Executor serverExecutor=server.getExecutor();
  if (serverExecutor instanceof ThreadPoolExecutor) {
    ((ThreadPoolExecutor)serverExecutor).shutdown();
    if (delaySeconds > 0) {
      try {
        ((ThreadPoolExecutor)serverExecutor).awaitTermination(delaySeconds,TimeUnit.SECONDS);
      }
 catch (      InterruptedException ex) {
      }
    }
  }
  return this;
}
 

Example 23

From project org.openscada.atlantis, under directory /org.openscada.da.server.common/src/org/openscada/da/server/common/impl/.

Source file: HiveCommon.java

  17 
vote

public Executor getOperationService(){
  return new Executor(){
    @Override public void execute(    final Runnable command){
      getOperationServiceInstance().execute(command);
    }
  }
;
}
 

Example 24

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

Source file: AbstractExecutionThreadService.java

  17 
vote

/** 
 * Returns the  {@link Executor} that will be used to run this service.Subclasses may override this method to use a custom  {@link Executor}, which may configure its worker thread with a specific name, thread group or priority. The returned executor's  {@link Executor#execute(Runnable) execute()} method is called when this service is started, and should returnpromptly.
 */
protected Executor executor(){
  return new Executor(){
    public void execute(    Runnable command){
      new Thread(command,AbstractExecutionThreadService.this.toString()).start();
    }
  }
;
}
 

Example 25

From project platform_frameworks_support, under directory /volley/src/com/android/volley/.

Source file: ExecutorDelivery.java

  17 
vote

/** 
 * Creates a new response delivery interface.
 * @param handler {@link Handler} to post responses on
 */
public ExecutorDelivery(final Handler handler){
  mResponsePoster=new Executor(){
    @Override public void execute(    Runnable command){
      handler.post(command);
    }
  }
;
}
 

Example 26

From project sonatype-aether, under directory /aether-connector-wagon/src/main/java/org/sonatype/aether/connector/wagon/.

Source file: WagonRepositoryConnector.java

  17 
vote

private Executor getExecutor(int threads){
  if (threads <= 1) {
    return new Executor(){
      public void execute(      Runnable command){
        command.run();
      }
    }
;
  }
 else {
    return new ThreadPoolExecutor(threads,threads,3,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>());
  }
}
 

Example 27

From project spring-insight-plugins, under directory /collection-plugins/run-exec/src/test/java/com/springsource/insight/plugin/runexec/.

Source file: ExecutorExecuteCollectionAspectTest.java

  17 
vote

@Test public void testThreadPoolExecutor() throws InterruptedException {
  Executor executor=new ThreadPoolExecutor(5,5,5L,TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(5));
  SignallingRunnable runner=new SignallingRunnable("testThreadPoolExecutor");
  executor.execute(runner);
{
    Operation op=assertLastExecutionOperation(runner);
    List<Operation> opsList=TEST_COLLECTOR.getCollectedOperations();
    assertEquals("Mismatched number of operations generated",2,opsList.size());
    SourceCodeLocation scl=op.getSourceCodeLocation();
    assertEquals("Mismatched class name",SignallingRunnable.class.getName(),scl.getClassName());
    assertEquals("Mismatched method name","run",scl.getMethodName());
  }
{
    Operation op=assertCurrentThreadExecution();
    SourceCodeLocation scl=op.getSourceCodeLocation();
    assertEquals("Mismatched class name",getClass().getName(),scl.getClassName());
    assertEquals("Mismatched method name","execute",scl.getMethodName());
  }
}
 

Example 28

From project staccatissimo, under directory /staccatissimo-control/src/test/java/net/sf/staccatocommons/control/.

Source file: BlockingMonadTest.java

  17 
vote

/** 
 */
@Constant public static Executor fork(){
  return new Executor(){
    public void execute(    Runnable command){
      Executors.defaultThreadFactory().newThread(command).start();
    }
  }
;
}
 

Example 29

From project stilts, under directory /stomp-client/src/main/java/org/projectodd/stilts/stomp/client/.

Source file: StompClient.java

  17 
vote

ClientSubscription subscribe(SubscriptionBuilderImpl builder) throws InterruptedException, ExecutionException {
  StompControlFrame frame=new StompControlFrame(Command.SUBSCRIBE,builder.getHeaders());
  String subscriptionId=getNextSubscriptionId();
  frame.setHeader(Header.ID,subscriptionId);
  ReceiptFuture future=sendFrame(frame);
  future.await();
  if (future.isError()) {
    return null;
  }
 else {
    Executor executor=builder.getExecutor();
    if (executor == null) {
      executor=getExecutor();
    }
    ClientSubscription subscription=new ClientSubscription(this,subscriptionId,builder.getMessageHandler(),executor);
    this.subscriptions.put(subscription.getId(),subscription);
    return subscription;
  }
}
 

Example 30

From project cipango, under directory /cipango-server/src/main/java/org/cipango/server/.

Source file: AbstractSipConnector.java

  15 
vote

public AbstractSipConnector(SipServer server,Executor executor,int acceptors){
  _server=server;
  _executor=executor != null ? executor : _server.getThreadPool();
  addBean(_server,false);
  addBean(_executor);
  if (executor == null)   unmanage(_executor);
  if (acceptors <= 0)   acceptors=Math.max(1,(Runtime.getRuntime().availableProcessors()) / 2);
  if (acceptors > 2 * Runtime.getRuntime().availableProcessors())   LOG.warn("{}: Acceptors should be <= 2*availableProcessors",this);
  _acceptors=new Thread[acceptors];
}
 

Example 31

From project clojure, under directory /src/jvm/clojure/lang/.

Source file: Agent.java

  15 
vote

public Action(Agent agent,IFn fn,ISeq args,Executor exec){
  this.agent=agent;
  this.args=args;
  this.fn=fn;
  this.exec=exec;
}
 

Example 32

From project crash, under directory /shell/core/src/main/java/org/crsh/shell/impl/async/.

Source file: AsyncShell.java

  15 
vote

public AsyncShell(Executor executor,Shell shell){
  this.shell=shell;
  this.current=null;
  this.executor=new ExecutorCompletionService<AsyncProcess>(executor);
  this.closed=false;
  this.processes=Collections.synchronizedSet(new HashSet<AsyncProcess>());
}
 

Example 33

From project curator, under directory /curator-framework/src/main/java/com/netflix/curator/framework/imps/.

Source file: Backgrounding.java

  15 
vote

private static BackgroundCallback wrapCallback(final CuratorFrameworkImpl client,final BackgroundCallback callback,final Executor executor){
  return new BackgroundCallback(){
    @Override public void processResult(    CuratorFramework dummy,    final CuratorEvent event) throws Exception {
      executor.execute(new Runnable(){
        @Override public void run(){
          try {
            callback.processResult(client,event);
          }
 catch (          Exception e) {
            client.logError("Background operation result handling threw exception",e);
          }
        }
      }
);
    }
  }
;
}
 

Example 34

From project dimdwarf, under directory /dimdwarf-core/src/main/java/net/orfjackal/dimdwarf/modules/.

Source file: TaskContextModule.java

  15 
vote

protected void configure(){
  bindScope(TaskScoped.class,new ThreadScope(TaskContext.class));
  bind(Context.class).annotatedWith(Task.class).to(TaskContext.class);
  bind(TransactionCoordinator.class).to(TransactionContext.class).in(TaskScoped.class);
  bind(RetryPolicy.class).toInstance(new RetryOnRetryableExceptionsANumberOfTimes(MAX_RETRIES));
  bind(Executor.class).annotatedWith(PlainTaskContext.class).to(TaskExecutor.class);
  bind(Executor.class).annotatedWith(RetryingTaskContext.class).to(RetryingTaskExecutor.class);
  bind(Executor.class).annotatedWith(SingleThreadFallbackTaskContext.class).to(SingleThreadFallbackTaskExecutor.class);
  bind(Executor.class).annotatedWith(Task.class).to(Key.get(Executor.class,SingleThreadFallbackTaskContext.class));
}
 

Example 35

From project disruptor, under directory /src/main/java/com/lmax/disruptor/.

Source file: WorkerPool.java

  15 
vote

/** 
 * Start the worker pool processing events in sequence.
 * @param executor providing threads for running the workers.
 * @return the {@link RingBuffer} used for the work queue.
 * @throws IllegalStateException is the pool has already been started and not halted yet
 */
public RingBuffer<T> start(final Executor executor){
  if (!started.compareAndSet(false,true)) {
    throw new IllegalStateException("WorkerPool has already been started and cannot be restarted until halted.");
  }
  final long cursor=ringBuffer.getCursor();
  workSequence.set(cursor);
  for (  WorkProcessor<?> processor : workProcessors) {
    processor.getSequence().set(cursor);
    executor.execute(processor);
  }
  return ringBuffer;
}
 

Example 36

From project elasticsearch-cloud-aws, under directory /src/main/java/org/elasticsearch/cloud/aws/blobstore/.

Source file: S3BlobStore.java

  15 
vote

public S3BlobStore(Settings settings,AmazonS3 client,String bucket,@Nullable String region,Executor executor){
  super(settings);
  this.client=client;
  this.bucket=bucket;
  this.region=region;
  this.executor=executor;
  this.bufferSizeInBytes=(int)settings.getAsBytesSize("buffer_size",new ByteSizeValue(100,ByteSizeUnit.KB)).bytes();
  if (!client.doesBucketExist(bucket)) {
    if (region != null) {
      client.createBucket(bucket,region);
    }
 else {
      client.createBucket(bucket);
    }
  }
}
 

Example 37

From project elasticsearch-hadoop, under directory /src/main/java/org/elasticsearch/common/blobstore/hdfs/.

Source file: HdfsBlobStore.java

  15 
vote

public HdfsBlobStore(Settings settings,FileSystem fileSystem,Executor executor,Path path) throws IOException {
  this.fileSystem=fileSystem;
  this.path=path;
  if (!fileSystem.exists(path)) {
    fileSystem.mkdirs(path);
  }
  this.bufferSizeInBytes=(int)settings.getAsBytesSize("buffer_size",new ByteSizeValue(100,ByteSizeUnit.KB)).bytes();
  this.executor=executor;
}
 

Example 38

From project httpcore, under directory /httpcore-nio/src/main/java/org/apache/http/nio/protocol/.

Source file: ThrottlingHttpClientHandler.java

  15 
vote

public ThrottlingHttpClientHandler(final HttpProcessor httpProcessor,final HttpRequestExecutionHandler execHandler,final ConnectionReuseStrategy connStrategy,final ByteBufferAllocator allocator,final Executor executor,final HttpParams params){
  super(httpProcessor,connStrategy,allocator,params);
  Args.notNull(execHandler,"HTTP request execution handler");
  Args.notNull(executor,"Executor");
  this.execHandler=execHandler;
  this.executor=executor;
  this.bufsize=this.params.getIntParameter(NIOReactorPNames.CONTENT_BUFFER_SIZE,20480);
}
 

Example 39

From project httpserver, under directory /src/main/java/org/jboss/sun/net/httpserver/.

Source file: ServerImpl.java

  15 
vote

public void setExecutor(Executor executor){
  if (started) {
    throw new IllegalStateException("server already started");
  }
  this.executor=executor;
}
 

Example 40

From project jagger, under directory /chassis/core/src/main/java/com/griddynamics/jagger/launch/.

Source file: Launches.java

  15 
vote

@Override public void setExecutor(Executor executor){
  super.setExecutor(executor);
  for (  LaunchTask launchTask : launchTasks) {
    launchTask.setExecutor(getExecutor());
  }
}
 

Example 41

From project jboss-remoting, under directory /src/main/java/org/jboss/remoting3/.

Source file: LocalChannel.java

  15 
vote

LocalChannel(final Executor executor,final LocalChannel otherSide,final ConnectionHandlerContext connectionHandlerContext){
  super(executor,true);
  this.otherSide=otherSide;
  this.connectionHandlerContext=connectionHandlerContext;
  queueLength=8;
  messageQueue=new ArrayDeque<In>(queueLength);
  bufferSize=8192;
}
 

Example 42

From project JSocksProxy, under directory /src/main/java/nu/najt/kecon/jsocksproxy/.

Source file: AbstractSocksImplementation.java

  15 
vote

/** 
 * Constructor
 * @param configurationFacade the configuration facade
 * @param clientSocket the clientSocket
 * @param logger the logger
 */
public AbstractSocksImplementation(final ConfigurationFacade configurationFacade,final Socket clientSocket,final Logger logger,final Executor executor){
  this.clientSocket=clientSocket;
  this.configurationFacade=configurationFacade;
  this.logger=logger;
  this.executor=executor;
}
 

Example 43

From project kernel_1, under directory /exo.kernel.component.common/src/main/java/org/exoplatform/services/jdbc/impl/.

Source file: ManagedConnection.java

  15 
vote

/** 
 * @see java.sql.Connection#abort(java.util.concurrent.Executor)
 */
public void abort(Executor executor) throws SQLException {
  try {
    Method m=con.getClass().getMethod("abort",Executor.class);
    m.invoke(con,executor);
  }
 catch (  NoSuchMethodException e) {
    LOG.debug("The method abort cannot be found in the class " + con.getClass() + ", so we assume it is not supported");
  }
catch (  Exception e) {
    throw new SQLException(e);
  }
}
 

Example 44

From project LateralGM, under directory /org/lateralgm/file/.

Source file: FileChangeMonitor.java

  15 
vote

public FileChangeMonitor(File f,Executor e){
  if (!f.exists())   throw new IllegalArgumentException();
  file=f;
  executor=e;
  changedRunnable=new UpdateRunnable(new FileUpdateEvent(updateSource,Flag.CHANGED));
  deletedRunnable=new UpdateRunnable(new FileUpdateEvent(updateSource,Flag.DELETED));
  lastModified=file.lastModified();
  length=file.length();
  future=monitorService.scheduleWithFixedDelay(this,POLL_INTERVAL,POLL_INTERVAL,TimeUnit.MILLISECONDS);
}
 

Example 45

From project liquidroid, under directory /src/liqui/droid/util/.

Source file: AsyncTask.java

  15 
vote

/** 
 * Executes the task with the specified parameters. The task returns itself (this) so that the caller can keep a reference to it. <p>This method is typically used with  {@link #THREAD_POOL_EXECUTOR} toallow multiple tasks to run in parallel on a pool of threads managed by AsyncTask, however you can also use your own  {@link Executor} for custombehavior. <p><em>Warning:</em> Allowing multiple tasks to run in parallel from a thread pool is generally <em>not</em> what one wants, because the order of their operation is not defined.  For example, if these tasks are used to modify any state in common (such as writing a file due to a button click), there are no guarantees on the order of the modifications. Without careful work it is possible in rare cases for the newer version of the data to be over-written by an older one, leading to obscure data loss and stability issues.  Such changes are best executed in serial; to guarantee such work is serialized regardless of platform version you can use this function with  {@link #SERIAL_EXECUTOR}. <p>This method must be invoked on the UI thread.
 * @param exec The executor to use.  {@link #THREAD_POOL_EXECUTOR} is available as aconvenient process-wide thread pool for tasks that are loosely coupled.
 * @param params The parameters of the task.
 * @return This instance of AsyncTask.
 * @throws IllegalStateException If {@link #getStatus()} returns either{@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
 */
@SuppressWarnings("javadoc") public final AsyncTask<Params,Progress,Result> executeOnExecutor(Executor exec,Params... params){
  if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
      throw new IllegalStateException("Cannot execute task:" + " the task is already running.");
case FINISHED:
    throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)");
}
}
mStatus=Status.RUNNING;
onPreExecute();
mWorker.mParams=params;
exec.execute(mFuture);
return this;
}
 

Example 46

From project Metamorphosis, under directory /metamorphosis-client/src/test/java/com/taobao/metamorphosis/client/consumer/.

Source file: RecoverStorageManagerUnitTest.java

  15 
vote

@Test public void testAppendShutdownLoadRecover() throws Exception {
  this.recoverStorageManager.shutdown();
  final MetaClientConfig metaClientConfig=new MetaClientConfig();
  metaClientConfig.setRecoverMessageIntervalInMills(Integer.MAX_VALUE);
  this.recoverStorageManager=new RecoverStorageManager(metaClientConfig,this.subscribeInfoManager);
  this.recoverStorageManager.start(metaClientConfig);
  final String group="dennis";
  final BlockingQueue<Message> queue=new ArrayBlockingQueue<Message>(1024);
  this.subscribeInfoManager.subscribe("test",group,1024 * 1024,new MessageListener(){
    @Override public void recieveMessages(    final Message message){
      queue.offer(message);
    }
    @Override public Executor getExecutor(){
      return null;
    }
  }
);
  for (int i=0; i < 100; i++) {
    final Message msg2=new Message("test",("hello" + i).getBytes());
    MessageAccessor.setId(msg2,i);
    this.recoverStorageManager.append(group,msg2);
  }
  this.recoverStorageManager.shutdown();
  metaClientConfig.setRecoverMessageIntervalInMills(1000);
  this.recoverStorageManager=new RecoverStorageManager(metaClientConfig,this.subscribeInfoManager);
  this.recoverStorageManager.start(metaClientConfig);
  while (queue.size() < 100) {
    Thread.sleep(1000);
  }
  for (  final Message msg : queue) {
    assertEquals("hello" + msg.getId(),new String(msg.getData()));
  }
  assertEquals(0,this.recoverStorageManager.getOrCreateStore("test",group).size());
}
 

Example 47

From project metamorphosis-example, under directory /src/main/java/com/taobao/metamorphosis/example/.

Source file: AsyncConsumer.java

  15 
vote

public static void main(final String[] args) throws Exception {
  final MessageSessionFactory sessionFactory=new MetaMessageSessionFactory(initMetaConfig());
  final String topic="meta-test";
  final String group="meta-example";
  ConsumerConfig consumerConfig=new ConsumerConfig(group);
  consumerConfig.setMaxDelayFetchTimeInMills(100);
  final MessageConsumer consumer=sessionFactory.createConsumer(consumerConfig);
  consumer.subscribe(topic,1024 * 1024,new MessageListener(){
    @Override public void recieveMessages(    final Message message){
      System.out.println("Receive message " + new String(message.getData()));
    }
    @Override public Executor getExecutor(){
      return null;
    }
  }
);
  consumer.completeSubscribe();
}
 

Example 48

From project moho, under directory /moho-presence/src/main/java/com/voxeo/moho/presence/sip/impl/.

Source file: MemoryNotifyDispatcher.java

  15 
vote

public MemoryNotifyDispatcher(Executor executor,int cap){
  _executor=executor;
  _cap=cap;
  _remainingThreshold=(int)(_cap * 0.25);
  _queue=new LinkedBlockingQueue<NotifyRequest>(_cap);
}
 

Example 49

From project narya, under directory /core/src/main/java/com/threerings/presents/server/.

Source file: ReportingInvoker.java

  15 
vote

/** 
 * Creates a new reporting invoker. The instance will be registered with the report manager if profiling is enabled ( {@link Invoker#PERF_TRACK}).
 */
public ReportingInvoker(String name,Executor receiver,ReportManager repmgr){
  super(name,receiver);
  if (PERF_TRACK) {
    repmgr.registerReporter(ReportManager.DEFAULT_TYPE,_defrep);
    repmgr.registerReporter(ReportManager.PROFILE_TYPE,_profrep);
  }
}
 

Example 50

From project netty, under directory /handler/src/main/java/io/netty/handler/ssl/.

Source file: SslHandler.java

  15 
vote

/** 
 * Creates a new instance.
 * @param engine the  {@link SSLEngine} this handler will use
 * @param startTls {@code true} if the first write request shouldn't be encryptedby the  {@link SSLEngine}
 * @param delegatedTaskExecutor the  {@link Executor} which will execute the delegated taskthat  {@link SSLEngine#getDelegatedTask()} will return
 */
public SslHandler(SSLEngine engine,boolean startTls,Executor delegatedTaskExecutor){
  if (engine == null) {
    throw new NullPointerException("engine");
  }
  if (delegatedTaskExecutor == null) {
    throw new NullPointerException("delegatedTaskExecutor");
  }
  this.engine=engine;
  this.delegatedTaskExecutor=delegatedTaskExecutor;
  this.startTls=startTls;
}
 

Example 51

From project nuxeo-opensocial, under directory /nuxeo-opensocial-server/src/main/java/org/nuxeo/opensocial/services/.

Source file: NXGuiceModule.java

  15 
vote

/** 
 * {@inheritDoc} 
 */
@Override protected void configure(){
  final ExecutorService service=Executors.newCachedThreadPool(DAEMON_THREAD_FACTORY);
  bind(Executor.class).toInstance(service);
  bind(ExecutorService.class).toInstance(service);
  Runtime.getRuntime().addShutdownHook(new Thread(){
    public void run(){
      service.shutdownNow();
    }
  }
);
  install(new ParseModule());
  install(new PreloadModule());
  install(new RenderModule());
  install(new NXRewriteModule());
  install(new TemplateModule());
  bind(new TypeLiteral<Set<Object>>(){
  }
).annotatedWith(Names.named("org.apache.shindig.gadgets.handlers")).toInstance(ImmutableSet.<Object>of(InvalidationHandler.class,HttpRequestHandler.class));
  requestStaticInjection(HttpResponse.class);
}
 

Example 52

From project parasim, under directory /extensions/computation-execution-impl/src/main/java/org/sybila/parasim/execution/impl/.

Source file: SharedMemoryExecution.java

  15 
vote

public SharedMemoryExecution(final Collection<ComputationId> computationIds,final java.util.concurrent.Executor runnableExecutor,final Computation<L> computation,final Enrichment enrichment,final ContextEvent<ComputationInstanceContext> contextEvent,final Context parentContext,final BlockingQueue<Future<L>> futures){
  Validate.notNull(runnableExecutor);
  Validate.notNull(computation);
  Validate.notNull(enrichment);
  Validate.notNull(contextEvent);
  Validate.notNull(parentContext);
  Validate.notNull(computationIds);
  Validate.notNull(futures);
  this.runnableExecutor=runnableExecutor;
  this.computation=computation;
  this.futures=futures;
  executions=new ArrayList<>(computationIds.size());
  for (  ComputationId computationId : computationIds) {
    executions.add(new SequentialExecution<>(computationId,runnableExecutor,computation.cloneComputation(),enrichment,contextEvent,parentContext));
  }
}
 

Example 53

From project platform_frameworks_ex, under directory /variablespeed/src/com/android/ex/variablespeed/.

Source file: VariableSpeed.java

  15 
vote

private VariableSpeed(Executor executor) throws UnsupportedOperationException {
  Preconditions.checkNotNull(executor);
  mExecutor=executor;
  try {
    VariableSpeedNative.loadLibrary();
  }
 catch (  UnsatisfiedLinkError e) {
    throw new UnsupportedOperationException("could not load library",e);
  }
catch (  SecurityException e) {
    throw new UnsupportedOperationException("could not load library",e);
  }
  reset();
}
 

Example 54

From project red5-mavenized, under directory /red5_base/src/main/java/org/red5/io/filter/.

Source file: ExecutorFilter.java

  15 
vote

/** 
 * Creates a new instance with the specified <tt>executor</tt>.
 * @param executor Executor
 */
public ExecutorFilter(Executor executor){
  if (executor == null) {
    throw new NullPointerException("executor");
  }
  logger.debug("Executor set to: " + executor.getClass().getName());
  this.executor=executor;
}
 

Example 55

From project remoting-jmx, under directory /src/main/java/org/jboss/remotingjmx/.

Source file: DelegatingRemotingConnectorServer.java

  15 
vote

public DelegatingRemotingConnectorServer(final MBeanServerLocator mbeanServerLocator,final Endpoint endpoint,final Executor executor,final Map<String,?> environment){
  this.mbeanServerManager=new DelegatingMBeanServerManager(mbeanServerLocator);
  this.endpoint=endpoint;
  this.executor=executor;
  versions=new Versions(environment);
}
 

Example 56

From project rhevm-api, under directory /common/jaxrs/src/main/java/com/redhat/rhevm/api/common/resource/.

Source file: AbstractActionableResource.java

  15 
vote

public AbstractActionableResource(String id,Executor executor,UriInfoProvider uriProvider){
  super(id);
  this.executor=executor;
  this.uriProvider=uriProvider;
  actions=new ReapedMap<String,ActionResource>(REAP_AFTER);
}
 

Example 57

From project sitebricks, under directory /sitebricks-client/src/main/java/com/google/sitebricks/client/.

Source file: AHCWebClient.java

  15 
vote

private ListenableFuture<WebResponse> simpleAsyncRequest(RequestBuilder requestBuilder,Executor executor){
  requestBuilder=addHeadersToRequestBuilder(requestBuilder);
  try {
    final SettableFuture<WebResponse> future=SettableFuture.create();
    final com.ning.http.client.ListenableFuture<Response> responseFuture=httpClient.executeRequest(requestBuilder.build());
    responseFuture.addListener(new Runnable(){
      @Override public void run(){
        try {
          future.set(new WebResponseImpl(injector,responseFuture.get()));
        }
 catch (        InterruptedException e) {
          throw new TransportException(e);
        }
catch (        ExecutionException e) {
          throw new TransportException(e);
        }
      }
    }
,executor);
    return future;
  }
 catch (  IOException e) {
    throw new TransportException(e);
  }
}
 

Example 58

From project spring-amqp, under directory /spring-rabbit/src/main/java/org/springframework/amqp/rabbit/connection/.

Source file: AbstractConnectionFactory.java

  15 
vote

/** 
 * Provide an Executor for use by the Rabbit ConnectionFactory when creating connections. Can either be an ExecutorService or a Spring ThreadPoolTaskExecutor, as defined by a &lt;task:executor/&gt; element.
 * @param executor The executor.
 */
public void setExecutor(Executor executor){
  boolean isExecutorService=executor instanceof ExecutorService;
  boolean isThreadPoolTaskExecutor=executor instanceof ThreadPoolTaskExecutor;
  Assert.isTrue(isExecutorService || isThreadPoolTaskExecutor);
  if (isExecutorService) {
    this.executorService=(ExecutorService)executor;
  }
 else {
    this.executorService=((ThreadPoolTaskExecutor)executor).getThreadPoolExecutor();
  }
}
 

Example 59

From project Tanks_1, under directory /src/org/apache/mina/core/polling/.

Source file: AbstractPollingConnectionlessIoAcceptor.java

  15 
vote

/** 
 * Creates a new instance.
 */
protected AbstractPollingConnectionlessIoAcceptor(IoSessionConfig sessionConfig,Executor executor){
  super(sessionConfig,executor);
  try {
    init();
    selectable=true;
  }
 catch (  RuntimeException e) {
    throw e;
  }
catch (  Exception e) {
    throw new RuntimeIoException("Failed to initialize.",e);
  }
 finally {
    if (!selectable) {
      try {
        destroy();
      }
 catch (      Exception e) {
        ExceptionMonitor.getInstance().exceptionCaught(e);
      }
    }
  }
}
 

Example 60

From project tb-diamond_1, under directory /diamond-client/src/test/java/com/taobao/diamond/client/impl/.

Source file: DefaultDiamondSubscriberUnitTest.java

  15 
vote

@Test public void test_????() throws Exception {
  this.publisher.close();
  this.subscriber.close();
  final String dataId=UUID.randomUUID().toString();
  final String group="leiwen";
  final String content="test bei dong huo qu";
  final java.util.concurrent.atomic.AtomicBoolean invoked=new AtomicBoolean(false);
  this.subscriber.setSubscriberListener(new SubscriberListener(){
    public void receiveConfigInfo(    ConfigureInfomation configureInfomation){
      System.out.println("???????" + configureInfomation);
      assertEquals(dataId,configureInfomation.getDataId());
      assertEquals(group,configureInfomation.getGroup());
      assertEquals(content,configureInfomation.getConfigureInfomation());
      invoked.set(true);
    }
    public Executor getExecutor(){
      return null;
    }
  }
);
  this.subscriber.addDataId(dataId,group);
  this.subscriber.start();
  this.publisher.addDataId(dataId,group,content);
  this.publisher.start();
  this.publisher.publishNew(dataId,group,content);
  while (!invoked.get()) {
    Thread.sleep(1000);
  }
}