Java Code Examples for java.util.concurrent.ScheduledExecutorService

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 android_external_guava, under directory /src/com/google/common/util/concurrent/.

Source file: Executors.java

  23 
vote

/** 
 * Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService 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#newScheduledThreadPool(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 ScheduledExecutorService getExitingScheduledExecutorService(ScheduledThreadPoolExecutor executor,long terminationTimeout,TimeUnit timeUnit){
  executor.setThreadFactory(daemonThreadFactory(executor.getThreadFactory()));
  ScheduledExecutorService service=java.util.concurrent.Executors.unconfigurableScheduledExecutorService(executor);
  addDelayedShutdownHook(service,terminationTimeout,timeUnit);
  return service;
}
 

Example 2

From project androidquery, under directory /src/com/androidquery/util/.

Source file: AQUtility.java

  18 
vote

public static void cleanCacheAsync(Context context,long triggerSize,long targetSize){
  try {
    File cacheDir=getCacheDir(context);
    Common task=new Common().method(Common.CLEAN_CACHE,cacheDir,triggerSize,targetSize);
    ScheduledExecutorService exe=getFileStoreExecutor();
    exe.schedule(task,0,TimeUnit.MILLISECONDS);
  }
 catch (  Exception e) {
    AQUtility.report(e);
  }
}
 

Example 3

From project channel-directory, under directory /src/com/buddycloud/channeldirectory/search/handler/common/mahout/.

Source file: PostgreSQLRecommenderDataModel.java

  18 
vote

private void scheduleRefreshAction(){
  ScheduledExecutorService scheduledThreadPool=Executors.newScheduledThreadPool(1);
  scheduledThreadPool.scheduleWithFixedDelay(new Runnable(){
    @Override public void run(){
      dataModel.refresh(new LinkedList<Refreshable>());
    }
  }
,REFRESH_DELAY,REFRESH_DELAY,TimeUnit.MINUTES);
}
 

Example 4

From project cometd, under directory /cometd-java/cometd-java-client/src/main/java/org/cometd/client/.

Source file: BayeuxClient.java

  18 
vote

private boolean scheduleAction(Runnable action,long interval,long backoff){
  ScheduledExecutorService scheduler=this.scheduler;
  if (scheduler != null) {
    try {
      scheduler.schedule(action,interval + backoff,TimeUnit.MILLISECONDS);
      return true;
    }
 catch (    RejectedExecutionException x) {
      logger.trace("",x);
    }
  }
  debug("Could not schedule action {} to scheduler {}",action,scheduler);
  return false;
}
 

Example 5

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

Source file: PluginContext.java

  18 
vote

synchronized void stop(){
  if (started) {
    manager.shutdown();
    if (scanner != null) {
      ScheduledExecutorService tmp=scanner;
      scanner=null;
      tmp.shutdownNow();
    }
    executor.shutdownNow();
  }
 else {
    log.warn("Attempt to stop when stopped");
  }
}
 

Example 6

From project floodlight, under directory /src/main/java/net/floodlightcontroller/topology/.

Source file: TopologyManager.java

  18 
vote

@Override public void startUp(FloodlightModuleContext context){
  ScheduledExecutorService ses=threadPool.getScheduledExecutor();
  newInstanceTask=new SingletonTask(ses,new UpdateTopologyWorker());
  linkDiscovery.addListener(this);
  floodlightProvider.addOFMessageListener(OFType.PACKET_IN,this);
  floodlightProvider.addHAListener(this);
  addRestletRoutable();
}
 

Example 7

From project jboss-websockets, under directory /src/test/java/org/jboss/as/websocket/.

Source file: ContentionTest.java

  18 
vote

@Test public void testContention() throws Exception {
  final ScheduledExecutorService scheduledExecutorService=Executors.newScheduledThreadPool(5);
  for (int i=0; i < 4; i++) {
    scheduledExecutorService.scheduleAtFixedRate(new HashRunner(),0,50,TimeUnit.MICROSECONDS);
  }
  scheduledExecutorService.scheduleAtFixedRate(new Runnable(){
    public void run(){
      System.out.println("hashes: " + counter.get());
    }
  }
,0,1000,TimeUnit.MILLISECONDS);
  scheduledExecutorService.awaitTermination(30,TimeUnit.SECONDS);
}
 

Example 8

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.ScheduledExecutorFactory#getScheduledExecutor(java.util.Properties)
 */
@Override public ScheduledExecutorService getScheduledExecutor(Properties properties){
  ScheduledExecutorService executor=(ScheduledExecutorService)properties.get(EXECUTOR);
  if (executor == null) {
    throw MESSAGES.invalidExecutorProperty(EXECUTOR,properties);
  }
  return new ManagedScheduledExecutorService(executor);
}
 

Example 9

From project livetribe-slp, under directory /core/src/main/java/org/livetribe/slp/da/.

Source file: StandardDirectoryAgentServer.java

  18 
vote

/** 
 * @param settings the configuration settings that override the defaults
 * @return a new instance of this directory agent
 */
public static StandardDirectoryAgentServer newInstance(Settings settings){
  UDPConnector udpConnector=Factories.<UDPConnector.Factory>newInstance(settings,UDP_CONNECTOR_FACTORY_KEY).newUDPConnector(settings);
  TCPConnector tcpConnector=Factories.<TCPConnector.Factory>newInstance(settings,TCP_CONNECTOR_FACTORY_KEY).newTCPConnector(settings);
  UDPConnectorServer udpConnectorServer=Factories.<UDPConnectorServer.Factory>newInstance(settings,UDP_CONNECTOR_SERVER_FACTORY_KEY).newUDPConnectorServer(settings);
  TCPConnectorServer tcpConnectorServer=Factories.<TCPConnectorServer.Factory>newInstance(settings,TCP_CONNECTOR_SERVER_FACTORY_KEY).newTCPConnectorServer(settings);
  ScheduledExecutorService scheduledExecutorService=Executors.newSingleThreadScheduledExecutor();
  return new StandardDirectoryAgentServer(udpConnector,tcpConnector,udpConnectorServer,tcpConnectorServer,scheduledExecutorService,settings);
}
 

Example 10

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

Source file: Executors.java

  18 
vote

/** 
 * Converts the given ScheduledThreadPoolExecutor into a ScheduledExecutorService 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#newScheduledThreadPool(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 ScheduledExecutorService getExitingScheduledExecutorService(ScheduledThreadPoolExecutor executor,long terminationTimeout,TimeUnit timeUnit){
  executor.setThreadFactory(daemonThreadFactory(executor.getThreadFactory()));
  ScheduledExecutorService service=java.util.concurrent.Executors.unconfigurableScheduledExecutorService(executor);
  addDelayedShutdownHook(service,terminationTimeout,timeUnit);
  return service;
}
 

Example 11

From project servo, under directory /servo-core/src/main/java/com/netflix/servo/publish/.

Source file: PollScheduler.java

  18 
vote

/** 
 * Add a tasks to execute at a fixed rate based on the provided delay.
 */
public void addPoller(PollRunnable task,long delay,TimeUnit timeUnit){
  ScheduledExecutorService service=executor.get();
  if (service != null) {
    service.scheduleWithFixedDelay(task,0,delay,timeUnit);
  }
 else {
    throw new IllegalStateException("you must start the scheduler before tasks can be submitted");
  }
}
 

Example 12

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 ScheduledFuture schedule(Runnable task,Trigger trigger){
  ScheduledExecutorService executor=getScheduledExecutor();
  try {
    ErrorHandler errorHandler=this.errorHandler != null ? this.errorHandler : TaskUtils.getDefaultErrorHandler(true);
    return new ReschedulingRunnable(task,trigger,executor,errorHandler).schedule();
  }
 catch (  RejectedExecutionException ex) {
    throw new TaskRejectedException("Executor [" + executor + "] did not accept task: "+ task,ex);
  }
}
 

Example 13

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

Source file: ScheduledExecutorServiceCollectionAspectTest.java

  18 
vote

@Test public void testSingleScheduling() throws InterruptedException, ExecutionException, TimeoutException {
  SignallingRunnable runner=new SignallingRunnable("testSingleScheduling");
  ScheduledExecutorService executor=createScheduledThreadPoolExecutor();
  ScheduledFuture<?> future=executor.schedule(runner,25L,TimeUnit.MILLISECONDS);
  assertLastExecutionOperation(runner);
  assertCurrentThreadExecution();
  Object result=future.get(5L,TimeUnit.SECONDS);
  assertNull("Unexpected future execution result",result);
  assertTrue("Future not marked as done",future.isDone());
}
 

Example 14

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

Source file: ScheduledExecutorFactoryBean.java

  18 
vote

protected ExecutorService initializeExecutor(ThreadFactory threadFactory,RejectedExecutionHandler rejectedExecutionHandler){
  ScheduledExecutorService executor=createExecutor(this.poolSize,threadFactory,rejectedExecutionHandler);
  if (!ObjectUtils.isEmpty(this.scheduledExecutorTasks)) {
    registerTasks(this.scheduledExecutorTasks,executor);
  }
  this.exposedExecutor=(this.exposeUnconfigurableExecutor ? Executors.unconfigurableScheduledExecutorService(executor) : executor);
  return executor;
}
 

Example 15

From project subsonic, under directory /subsonic-main/src/main/java/net/sourceforge/subsonic/ajax/.

Source file: ChatService.java

  18 
vote

/** 
 * Invoked by Spring.
 */
public void init(){
  ScheduledExecutorService executor=Executors.newSingleThreadScheduledExecutor();
  Runnable runnable=new Runnable(){
    public void run(){
      removeOldMessages();
    }
  }
;
  executor.scheduleWithFixedDelay(runnable,0L,3600L,TimeUnit.SECONDS);
}
 

Example 16

From project subsonic_1, under directory /subsonic-main/src/main/java/net/sourceforge/subsonic/ajax/.

Source file: ChatService.java

  18 
vote

/** 
 * Invoked by Spring.
 */
public void init(){
  ScheduledExecutorService executor=Executors.newSingleThreadScheduledExecutor();
  Runnable runnable=new Runnable(){
    public void run(){
      removeOldMessages();
    }
  }
;
  executor.scheduleWithFixedDelay(runnable,0L,3600L,TimeUnit.SECONDS);
}
 

Example 17

From project Supersonic, under directory /subsonic-main/src/main/java/net/sourceforge/subsonic/ajax/.

Source file: ChatService.java

  18 
vote

/** 
 * Invoked by Spring.
 */
public void init(){
  ScheduledExecutorService executor=Executors.newSingleThreadScheduledExecutor();
  Runnable runnable=new Runnable(){
    public void run(){
      removeOldMessages();
    }
  }
;
  executor.scheduleWithFixedDelay(runnable,0L,3600L,TimeUnit.SECONDS);
}
 

Example 18

From project ubuntu-packaging-floodlight, under directory /src/main/java/net/floodlightcontroller/topology/.

Source file: TopologyManager.java

  18 
vote

@Override public void startUp(FloodlightModuleContext context){
  ScheduledExecutorService ses=threadPool.getScheduledExecutor();
  newInstanceTask=new SingletonTask(ses,new NewInstanceWorker());
  linkDiscovery.addListener(this);
  newInstanceTask.reschedule(1,TimeUnit.MILLISECONDS);
  floodlightProvider.addOFMessageListener(OFType.PACKET_IN,this);
  floodlightProvider.addHAListener(this);
  addRestletRoutable();
}
 

Example 19

From project usergrid-stack, under directory /core/src/main/java/org/usergrid/persistence/cassandra/.

Source file: CassandraService.java

  18 
vote

public void startClusterHealthCheck(){
  ScheduledExecutorService executorService=Executors.newSingleThreadScheduledExecutor();
  executorService.scheduleWithFixedDelay(new Runnable(){
    @Override public void run(){
      if (cluster != null) {
        HConnectionManager connectionManager=cluster.getConnectionManager();
        if (connectionManager != null) {
          clusterUp=!connectionManager.getHosts().isEmpty();
        }
      }
    }
  }
,1,5,TimeUnit.SECONDS);
}
 

Example 20

From project akubra, under directory /akubra-rmi/src/test/java/org/akubraproject/rmi/.

Source file: TransactionalStoreTest.java

  17 
vote

@Test public void testMTStress() throws InterruptedException, ExecutionException {
  ScheduledExecutorService executor=Executors.newScheduledThreadPool(10);
  List<Future<Void>> futures=new ArrayList<Future<Void>>();
  for (int loop=0; loop < 30; loop++) {
    futures.add(executor.submit(new Callable<Void>(){
      public Void call() throws Exception {
        for (int i=0; i < 10; i++) {
          doInTxn(new Action(){
            public void run(            BlobStoreConnection con) throws Exception {
              for (int j=0; j < 3; j++) {
                URI id=URI.create("urn:mt:" + UUID.randomUUID());
                byte[] buf=new byte[4096];
                Blob b;
                b=con.getBlob(id,null);
                OutputStream out;
                IOUtils.copyLarge(new ByteArrayInputStream(buf),out=b.openOutputStream(buf.length,true));
                out.close();
                InputStream in;
                assertEquals(buf,IOUtils.toByteArray(in=b.openInputStream()));
                in.close();
                b.delete();
              }
            }
          }
,true);
        }
        return null;
      }
    }
));
  }
  for (  Future<Void> res : futures)   res.get();
}
 

Example 21

From project byteman, under directory /sample/src/org/jboss/byteman/sample/helper/.

Source file: ThreadHistoryMonitorHelper.java

  17 
vote

/** 
 * Write all events to the file given by path, repeating sampleCount times at 5 second intervals. The actual filename of each sample report will be either path-n where n = [0,sampleCount] if path does not contain a suffix, for example: /tmp/report-0 /tmp/report-1 /tmp/report-3 or pathbase-n.suffix if there is a '.' delimited suffix (.txt), for example: /tmp/report-0.txt /tmp/report-1.txt /tmp/report-3.txt
 * @param path - the path to the event report file
 * @param sampleCount - the number of samples to take
 * @throws IOException - thrown on any IO failure
 */
public synchronized void writeAllEventsToFile(String path,int sampleCount) throws IOException {
  ScheduledExecutorService ses=Executors.newSingleThreadScheduledExecutor();
  ArrayList<ScheduledFuture> tasks=new ArrayList<ScheduledFuture>();
  String suffix=null;
  String base=path;
  int lastDot=path.lastIndexOf('.');
  if (lastDot > 0) {
    suffix=path.substring(lastDot);
    base=path.substring(0,lastDot);
  }
  for (int n=0; n <= sampleCount; n++) {
    final String samplePath=base + "-" + n+ (suffix != null ? suffix : "");
    int delay=5 * n;
    ScheduledFuture future=ses.schedule(new Runnable(){
      @Override public void run(){
        try {
          doWriteAllEvents(samplePath);
        }
 catch (        IOException e) {
          e.printStackTrace();
        }
      }
    }
,delay,TimeUnit.SECONDS);
    tasks.add(future);
  }
  for (  ScheduledFuture future : tasks) {
    try {
      future.get();
    }
 catch (    Exception e) {
      e.printStackTrace();
    }
  }
}
 

Example 22

From project Carolina-Digital-Repository, under directory /services/src/test/java/edu/unc/lib/dl/cdr/services/processing/.

Source file: CatchUpServiceTest.java

  17 
vote

/** 
 * Verify that extra calls to the catchup method cannot run while it is already executing.
 * @throws EnhancementException
 * @throws InterruptedException
 * @throws ExecutionException
 */
@Test public void lockoutCatchUp() throws EnhancementException, InterruptedException, ExecutionException {
  when(techmd.isActive()).thenReturn(true);
  when(image.isActive()).thenReturn(true);
  List<PID> results=getResultSet(catchup.getPageSize());
  when(techmd.findCandidateObjects(anyInt())).thenReturn(results);
  ScheduledExecutorService scheduler=Executors.newScheduledThreadPool(1);
  Runnable activateRunnable=new Runnable(){
    public void run(){
      while (!catchup.isActive())       ;
      boolean response=catchup.activate();
      assertFalse(response);
    }
  }
;
  Runnable deactivateRunnable=new Runnable(){
    public void run(){
      catchup.deactivate();
      System.out.println("Deactivated " + System.currentTimeMillis());
    }
  }
;
  ScheduledFuture<?> activateHandler=scheduler.schedule(activateRunnable,100,TimeUnit.MILLISECONDS);
  ScheduledFuture<?> deactivateHandler=scheduler.schedule(deactivateRunnable,500,TimeUnit.MILLISECONDS);
  boolean response=catchup.activate();
  assertTrue(response);
  deactivateHandler.get();
  activateHandler.get();
  scheduler.shutdown();
}
 

Example 23

From project cloudhopper-commons-util, under directory /src/test/java/com/cloudhopper/commons/util/demo/.

Source file: Window2Main.java

  17 
vote

static public void main(String[] args) throws Exception {
  ScheduledExecutorService executor=Executors.newSingleThreadScheduledExecutor();
  WindowListener listener=new WindowListener<Integer,String,String>(){
    @Override public void expired(    WindowFuture<Integer,String,String> entry){
      logger.debug("The key=" + entry.getKey() + ", request="+ entry.getRequest()+ " expired");
    }
  }
;
  Window<Integer,String,String> window=new Window<Integer,String,String>(2,executor,5000,listener);
  Window<Integer,String,String> window2=new Window<Integer,String,String>(2,executor,5000,listener,"window2monitor");
  WindowFuture<Integer,String,String> future0=window.offer(0,"Request0",1000,4000);
  logger.info("Request0 offered at " + future0.getOfferTimestamp() + " and expires at "+ future0.getExpireTimestamp());
  System.out.println("Press any key to add another request...");
  System.in.read();
  WindowFuture<Integer,String,String> future1=window2.offer(1,"Request1",1000,4000);
  logger.info("Request1 offered at " + future1.getOfferTimestamp() + " and expires at "+ future1.getExpireTimestamp());
  System.out.println("Press any key to add response...");
  System.in.read();
  logger.info("Adding Response1...");
  WindowFuture<Integer,String,String> responseFuture1=window.complete(1,"Response1");
  if (responseFuture1 == null) {
    logger.info("Request1 was not present in window");
  }
 else {
    logger.info(responseFuture1.getRequest());
    logger.info(responseFuture1.getResponse());
  }
  System.out.println("Press any key to get rid of our reference to Window");
  System.in.read();
  window.destroy();
  window2.destroy();
  window=null;
  window2=null;
  System.gc();
  System.out.println("Press any key to exit...");
  System.in.read();
  executor.shutdown();
}
 

Example 24

From project collector, under directory /src/main/java/com/ning/metrics/collector/hadoop/processing/.

Source file: EventSpoolDispatcher.java

  17 
vote

@Inject public EventSpoolDispatcher(final PersistentWriterFactory factory,final WriterStats stats,final CollectorConfig config){
  this.factory=factory;
  this.stats=stats;
  this.config=config;
  final ScheduledExecutorService scheduledExecutor=new FailsafeScheduledExecutor(1,"WriterQueuesReaper");
  scheduledExecutor.schedule(new Runnable(){
    @Override public void run(){
      try {
        final Set<String> queuePaths=new HashSet<String>(queuesPerPath.keySet());
        for (        final String queuePath : queuePaths) {
          final LocalQueueAndWriter queueAndWriter=queuesPerPath.get(queuePath);
          if (queueAndWriter.isEmpty()) {
            boolean isRemoved=false;
synchronized (queueMapMonitor) {
              if (queueAndWriter.isEmpty()) {
                queuesPerPath.remove(queuePath);
                isRemoved=true;
              }
            }
            if (isRemoved) {
              queueAndWriter.close();
            }
          }
        }
        LocalSpoolManager.cleanupOldSpoolDirectories(LocalSpoolManager.findOldSpoolDirectories(config.getSpoolDirectoryName(),CUTOFF_TIME_OLD_DIRS));
      }
  finally {
        scheduledExecutor.schedule(this,config.getMaxUncommittedPeriodInSeconds(),TimeUnit.SECONDS);
      }
    }
  }
,1,TimeUnit.HOURS);
}
 

Example 25

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 26

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

Source file: MockCollectorControllerModule.java

  17 
vote

@Override protected void configure(){
  final EventTrackerConfig config=new ConfigurationObjectFactory(System.getProperties()).build(EventTrackerConfig.class);
  bind(EventTrackerConfig.class).toInstance(config);
  final EventSender eventSender=new MockCollectorSender();
  bind(EventSender.class).toInstance(eventSender);
  final ScheduledExecutorService executor=new StubScheduledExecutorService(){
    public AtomicBoolean isShutdown=new AtomicBoolean(false);
    @Override public boolean awaitTermination(    final long timeout,    final TimeUnit unit) throws InterruptedException {
      return true;
    }
    @Override public void shutdown(){
      isShutdown.set(true);
    }
    @Override public List<Runnable> shutdownNow(){
      isShutdown.set(true);
      return new ArrayList<Runnable>();
    }
    @Override public boolean isShutdown(){
      return isShutdown.get();
    }
    @Override public boolean isTerminated(){
      return isShutdown.get();
    }
  }
;
  bind(ScheduledExecutorService.class).toInstance(executor);
  bind(CollectorController.class).toProvider(CollectorControllerProvider.class).asEagerSingleton();
  bind(DiskSpoolEventWriter.class).toInstance(new DiskSpoolEventWriter(new EventHandler(){
    @Override public void handle(    final File file,    final CallbackHandler handler){
      eventSender.send(file,handler);
    }
  }
,config.getSpoolDirectoryName(),config.isFlushEnabled(),config.getFlushIntervalInSeconds(),executor,SyncType.valueOf(config.getSyncType()),config.getSyncBatchSize()));
  bind(EventWriter.class).toProvider(ThresholdEventWriterProvider.class);
}
 

Example 27

From project jackrabbit-oak, under directory /oak-mk/src/test/java/org/apache/jackrabbit/mk/store/.

Source file: DefaultRevisionStoreTest.java

  17 
vote

/** 
 * Verify garbage collection can run concurrently with commits.
 * @throws Exception if an error occurs
 */
@Test public void testConcurrentGC() throws Exception {
  ScheduledExecutorService gcExecutor=Executors.newScheduledThreadPool(1);
  gcExecutor.scheduleWithFixedDelay(new Runnable(){
    @Override public void run(){
      rs.gc();
    }
  }
,100,20,TimeUnit.MILLISECONDS);
  mk.commit("/","+\"a\" : { \"b\" : { \"c\" : { \"d\" : {} } } }",mk.getHeadRevision(),null);
  try {
    for (int i=0; i < 20; i++) {
      mk.commit("/a/b/c/d","+\"e\" : {}",mk.getHeadRevision(),null);
      Thread.sleep(10);
      mk.commit("/a/b/c/d/e","+\"f\" : {}",mk.getHeadRevision(),null);
      Thread.sleep(30);
      mk.commit("/a/b/c/d","-\"e\"",mk.getHeadRevision(),null);
    }
  }
  finally {
    gcExecutor.shutdown();
  }
}
 

Example 28

From project jboss-polyglot, under directory /jobs/src/main/java/org/projectodd/polyglot/jobs/.

Source file: TimeoutListener.java

  17 
vote

@Override public void started(final JobExecutionContext context,final BaseJob job){
  if (this.timeout.interval > 0) {
    ScheduledExecutorService service=Executors.newScheduledThreadPool(1);
    this.timeoutExecutor=service.schedule(new Runnable(){
      public void run(){
        try {
          ((InterruptableJob)context.getJobInstance()).interrupt();
        }
 catch (        Exception e) {
          log.error("Failed to interrupt job " + job.getJobKey(),e);
        }
      }
    }
,timeout.interval,timeout.unit);
  }
}
 

Example 29

From project jclouds-abiquo, under directory /core/src/test/java/org/jclouds/abiquo/internal/.

Source file: AsyncMonitorTest.java

  17 
vote

@SuppressWarnings({"rawtypes","unchecked"}) public void testStartMonitoringWithoutTimeout(){
  ScheduledFuture mockFuture=EasyMock.createMock(ScheduledFuture.class);
  ScheduledExecutorService schedulerMock=EasyMock.createMock(ScheduledExecutorService.class);
  expect(schedulerMock.scheduleWithFixedDelay(anyObject(Runnable.class),anyLong(),anyLong(),anyObject(TimeUnit.class))).andReturn(mockFuture);
  replay(mockFuture);
  replay(schedulerMock);
  AsyncMonitor<Object> monitor=mockMonitor(schedulerMock,new Object(),mockFunction(MonitorStatus.DONE),new EventBus());
  assertNull(monitor.getFuture());
  assertNull(monitor.getTimeout());
  monitor.startMonitoring(null);
  assertNotNull(monitor.getFuture());
  assertNull(monitor.getTimeout());
  verify(mockFuture);
  verify(schedulerMock);
}
 

Example 30

From project krati, under directory /krati-avro/src/demo/java/krati/store/demo/joiner/.

Source file: AvroStoreJoinerHttpServer.java

  17 
vote

public static void main(String[] args) throws Exception {
  File homeDir=new File(System.getProperty("java.io.tmpdir"),AvroStoreJoinerHttpServer.class.getSimpleName());
  int initialCapacity=10000;
  StoreConfig configTemplate=new StoreConfig(homeDir,initialCapacity);
  configTemplate.setSegmentCompactFactor(0.68);
  configTemplate.setSegmentFactory(new MappedSegmentFactory());
  configTemplate.setSegmentFileSizeMB(32);
  configTemplate.setNumSyncBatches(2);
  configTemplate.setBatchSize(100);
  DataStoreFactory storeFactory=new IndexedDataStoreFactory();
  StoreResponderFactory responderFactory=new BasicDataStoreResponderFactory(storeFactory);
  MultiTenantStoreResponder mtStoreResponder=new MultiTenantStoreResponder(homeDir,configTemplate,responderFactory);
  String source;
  StoreResponder responder;
  DataStore<byte[],byte[]> baseStore;
  Serializer<String> keySerializer=new StringSerializer();
  Map<String,AvroStore<String>> map=new HashMap<String,AvroStore<String>>();
  source="Person";
  responder=mtStoreResponder.createTenant(source);
  baseStore=((BasicDataStoreResponder)responder).getStore();
  AvroStore<String> personStore=new SimpleAvroStore<String>(baseStore,createPersonSchema(),keySerializer);
  map.put(source,personStore);
  source="Address";
  responder=mtStoreResponder.createTenant(source);
  baseStore=((BasicDataStoreResponder)responder).getStore();
  AvroStore<String> addressStore=new SimpleAvroStore<String>(baseStore,createAddressSchema(),keySerializer);
  map.put(source,addressStore);
  AvroStoreJoiner<String> joiner=new AvroStoreJoiner<String>("PersonalRecord","avro.test",map,keySerializer);
  joiner.setMaster(personStore);
  PersonWriter personWriter=new PersonWriter(personStore);
  AddressWriter addressWriter=new AddressWriter(addressStore);
  ScheduledExecutorService executor=Executors.newScheduledThreadPool(2,new DaemonThreadFactory());
  executor.scheduleWithFixedDelay(personWriter,0,10,TimeUnit.MILLISECONDS);
  executor.scheduleWithFixedDelay(addressWriter,0,10,TimeUnit.MILLISECONDS);
  HttpServer server=new HttpServer(new AvroStoreResponder<String>(joiner),8080);
  server.start();
  server.join();
}
 

Example 31

From project ODE-X, under directory /runtime/src/main/java/org/apache/ode/runtime/exec/platform/.

Source file: NodeImpl.java

  17 
vote

@PostConstruct public void init(){
  log.fine("Initializing Node");
  taskExec.configure(this);
  localNodeState.set(NodeState.OFFLINE);
  ScheduledExecutorService clusterScheduler;
  try {
    clusterScheduler=executors.initClusterTaskScheduler();
    clusterScheduler.scheduleAtFixedRate(healthCheck,0,config.getHealthCheck().getFrequency(),TimeUnit.MILLISECONDS);
    clusterScheduler.scheduleAtFixedRate(taskExec,0,config.getTaskCheck().getFrequency(),TimeUnit.MILLISECONDS);
    clusterScheduler.scheduleAtFixedRate(messageHandler,0,config.getMessageCheck().getFrequency(),TimeUnit.MILLISECONDS);
  }
 catch (  PlatformException pe) {
    log.log(Level.SEVERE,"",pe);
  }
  messageHandler.addListener(this);
  log.fine("Cluster Initialized");
}
 

Example 32

From project org.openscada.atlantis, under directory /org.openscada.core.client/src/org/openscada/core/client/.

Source file: AutoReconnectController.java

  17 
vote

/** 
 * Dispose controller forcibly
 * @param disconnect if <code>true</code> the connection will also be disconnected
 */
public void dispose(final boolean disconnect){
  logger.debug("Disposing - disconnect: {}",disconnect);
  final ScheduledExecutorService executor;
synchronized (this) {
    executor=this.executor;
    if (this.executor != null) {
      if (disconnect) {
        disconnect();
      }
      this.executor=null;
    }
  }
  if (executor != null) {
    executor.shutdown();
  }
}
 

Example 33

From project rabbitmq-java-client, under directory /src/com/rabbitmq/client/impl/.

Source file: HeartbeatSender.java

  17 
vote

/** 
 * Sets the heartbeat in seconds.
 */
public void setHeartbeat(int heartbeatSeconds){
synchronized (this.monitor) {
    if (this.shutdown) {
      return;
    }
    if (this.future != null) {
      this.future.cancel(true);
      this.future=null;
    }
    if (heartbeatSeconds > 0) {
      long interval=SECONDS.toNanos(heartbeatSeconds) / 2;
      ScheduledExecutorService executor=createExecutorIfNecessary();
      Runnable task=new HeartbeatRunnable(interval);
      this.future=executor.scheduleAtFixedRate(task,interval,interval,TimeUnit.NANOSECONDS);
    }
  }
}
 

Example 34

From project subsonic_2, under directory /subsonic-booter/src/main/java/net/sourceforge/subsonic/booter/agent/.

Source file: SubsonicAgent.java

  17 
vote

private void startPolling(){
  ScheduledExecutorService executor=Executors.newScheduledThreadPool(2);
  Runnable runnable=new Runnable(){
    public void run(){
      try {
        notifyDeploymentInfo(service.getDeploymentInfo());
      }
 catch (      Throwable x) {
        notifyDeploymentInfo(null);
      }
    }
  }
;
  executor.scheduleWithFixedDelay(runnable,0,POLL_INTERVAL_DEPLOYMENT_INFO_SECONDS,TimeUnit.SECONDS);
  runnable=new Runnable(){
    public void run(){
      if (serviceStatusPollingEnabled) {
        try {
          notifyServiceStatus(getServiceStatus());
        }
 catch (        Throwable x) {
          notifyServiceStatus(null);
        }
      }
    }
  }
;
  executor.scheduleWithFixedDelay(runnable,0,POLL_INTERVAL_SERVICE_STATUS_SECONDS,TimeUnit.SECONDS);
}
 

Example 35

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

Source file: CachingServiceSelector.java

  15 
vote

public CachingServiceSelector(String type,ServiceSelectorConfig selectorConfig,DiscoveryLookupClient lookupClient,ScheduledExecutorService executor){
  Preconditions.checkNotNull(type,"type is null");
  Preconditions.checkNotNull(selectorConfig,"selectorConfig is null");
  Preconditions.checkNotNull(lookupClient,"client is null");
  Preconditions.checkNotNull(executor,"executor is null");
  this.type=type;
  this.pool=selectorConfig.getPool();
  this.lookupClient=lookupClient;
  this.executor=executor;
}
 

Example 36

From project ardverk-commons, under directory /src/main/java/org/ardverk/security/token/.

Source file: DefaultSecurityToken.java

  15 
vote

public DefaultSecurityToken(ScheduledExecutorService executor,MessageDigest messageDigest,final Random random,long frequency,TimeUnit unit){
  this.messageDigest=messageDigest;
  current=new byte[messageDigest.getDigestLength()];
  random.nextBytes(current);
  ScheduledFuture<?> future=null;
  if (0 < frequency) {
    Runnable task=new Runnable(){
      @Override public void run(){
synchronized (keyLock) {
          previous=current;
          current=new byte[current.length];
          random.nextBytes(current);
        }
      }
    }
;
    future=executor.scheduleWithFixedDelay(task,frequency,frequency,unit);
  }
  this.future=future;
}
 

Example 37

From project Arecibo, under directory /event/src/main/java/com/ning/arecibo/event/publisher/.

Source file: EventPublisherModule.java

  15 
vote

@Override public void configure(){
  ConfigurationObjectFactory configFactory=new ConfigurationObjectFactory(System.getProperties());
  ConsistentHashingConfig consistentHashingConfig=configFactory.build(ConsistentHashingConfig.class);
  EventPublisherConfig eventPublisherConfig=configFactory.build(EventPublisherConfig.class);
  bind(ConsistentHashingConfig.class).toInstance(consistentHashingConfig);
  bind(EventPublisherConfig.class).toInstance(eventPublisherConfig);
  bind(ExecutorService.class).annotatedWith(PublisherExecutor.class).toInstance(Executors.newFixedThreadPool(50,new NamedThreadFactory("EventPublisher")));
  bind(Selector.class).annotatedWith(PublisherSelector.class).toInstance(new ServiceSelector(eventPublisherConfig.getEventServiceName()));
  bind(Selector.class).annotatedWith(ConsistentHashingSelector.class).toInstance(new ServiceSelector(eventPublisherConfig.getEventServiceName()));
  bind(ConsistentHashingServiceChooser.class).asEagerSingleton();
  bind(ScheduledExecutorService.class).annotatedWith(JMXCronScheduler.class).toInstance(Executors.newScheduledThreadPool(1));
  bind(EventServiceChooser.class).to(AreciboEventServiceChooser.class).asEagerSingleton();
  bind(EventPublisher.class).to(AreciboEventPublisher.class).asEagerSingleton();
  bind(String.class).annotatedWith(EventSenderType.class).toInstance(senderType);
  ExportBuilder builder=MBeanModule.newExporter(binder());
  builder.export(AreciboEventServiceChooser.class).as("arecibo:type=AreciboEventServiceChooser");
  builder.export(AreciboEventPublisher.class).as("arecibo:name=EventPublisher");
}
 

Example 38

From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/.

Source file: BlueprintContainerImpl.java

  15 
vote

public BlueprintContainerImpl(BundleContext bundleContext,Bundle extenderBundle,BlueprintListener eventDispatcher,NamespaceHandlerRegistry handlers,ScheduledExecutorService executors,List<Object> pathList){
  this.bundleContext=bundleContext;
  this.extenderBundle=extenderBundle;
  this.eventDispatcher=eventDispatcher;
  this.handlers=handlers;
  this.pathList=pathList;
  this.converter=new AggregateConverter(this);
  this.componentDefinitionRegistry=new ComponentDefinitionRegistryImpl();
  this.executors=executors;
  this.processors=new ArrayList<Processor>();
  if (System.getSecurityManager() != null) {
    this.accessControlContext=createAccessControlContext();
  }
}
 

Example 39

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

Source file: ConnectionMaxAgeThread.java

  15 
vote

/** 
 * Constructor
 * @param connectionPartition partition to work on
 * @param scheduler Scheduler handler.
 * @param pool pool handle
 * @param maxAgeInMs Threads older than this are killed off 
 * @param lifoMode if true, we're running under a lifo fashion.
 */
protected ConnectionMaxAgeThread(ConnectionPartition connectionPartition,ScheduledExecutorService scheduler,BoneCP pool,long maxAgeInMs,boolean lifoMode){
  this.partition=connectionPartition;
  this.scheduler=scheduler;
  this.maxAgeInMs=maxAgeInMs;
  this.pool=pool;
  this.lifoMode=lifoMode;
}
 

Example 40

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 41

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

Source file: ChildReaper.java

  15 
vote

/** 
 * @param client the client
 * @param path path to reap children from
 * @param executor executor to use for background tasks
 * @param reapingThresholdMs threshold in milliseconds that determines that a path can be deleted
 * @param mode reaping mode
 */
public ChildReaper(CuratorFramework client,String path,Reaper.Mode mode,ScheduledExecutorService executor,int reapingThresholdMs){
  this.client=client;
  this.path=path;
  this.mode=mode;
  this.executor=executor;
  this.reapingThresholdMs=reapingThresholdMs;
  this.reaper=new Reaper(client,executor,reapingThresholdMs);
}
 

Example 42

From project event-collector, under directory /event-collector/src/main/java/com/proofpoint/event/collector/.

Source file: EventTapWriter.java

  15 
vote

@Inject public EventTapWriter(@ServiceType("eventTap") ServiceSelector selector,@EventTap HttpClient httpClient,JsonCodec<List<Event>> eventCodec,@EventTap ScheduledExecutorService executorService,EventTapConfig config){
  Preconditions.checkNotNull(selector,"selector is null");
  Preconditions.checkNotNull(httpClient,"httpClient is null");
  Preconditions.checkNotNull(eventCodec,"eventCodec is null");
  Preconditions.checkNotNull(executorService,"executorService is null");
  Preconditions.checkNotNull(config,"config is null");
  this.selector=selector;
  this.httpClient=httpClient;
  this.eventsCodec=eventCodec;
  this.executorService=executorService;
  this.flowRefreshDuration=config.getEventTapRefreshDuration();
  refreshFlows();
  batchProcessor=new BatchProcessor<Event>("event-tap",this,config.getMaxBatchSize(),config.getQueueSize());
}
 

Example 43

From project flume, under directory /flume-ng-sinks/flume-hdfs-sink/src/main/java/org/apache/flume/sink/hdfs/.

Source file: BucketWriter.java

  15 
vote

BucketWriter(long rollInterval,long rollSize,long rollCount,long batchSize,Context context,String filePath,CompressionCodec codeC,CompressionType compType,HDFSWriter writer,FlumeFormatter formatter,ScheduledExecutorService timedRollerPool,UserGroupInformation user,SinkCounter sinkCounter){
  this.rollInterval=rollInterval;
  this.rollSize=rollSize;
  this.rollCount=rollCount;
  this.batchSize=batchSize;
  this.context=context;
  this.filePath=filePath;
  this.codeC=codeC;
  this.compType=compType;
  this.writer=writer;
  this.formatter=formatter;
  this.timedRollerPool=timedRollerPool;
  this.user=user;
  this.sinkCounter=sinkCounter;
  fileExtensionCounter=new AtomicLong(System.currentTimeMillis());
  isOpen=false;
  writer.configure(context);
}
 

Example 44

From project james-imap, under directory /processor/src/main/java/org/apache/james/imap/processor/.

Source file: IdleProcessor.java

  15 
vote

public IdleProcessor(final ImapProcessor next,final MailboxManager mailboxManager,final StatusResponseFactory factory,long heartbeatInterval,TimeUnit heartbeatIntervalUnit,ScheduledExecutorService heartbeatExecutor){
  super(IdleRequest.class,next,mailboxManager,factory);
  this.heartbeatInterval=heartbeatInterval;
  this.heartbeatIntervalUnit=heartbeatIntervalUnit;
  this.heartbeatExecutor=heartbeatExecutor;
}
 

Example 45

From project jsecurity, under directory /core/src/main/java/org/apache/ki/realm/text/.

Source file: PropertiesRealm.java

  15 
vote

protected void startReloadThread(){
  if (this.reloadIntervalSeconds > 0) {
    this.scheduler=Executors.newSingleThreadScheduledExecutor();
    ((ScheduledExecutorService)this.scheduler).scheduleAtFixedRate(this,reloadIntervalSeconds,reloadIntervalSeconds,TimeUnit.SECONDS);
  }
}
 

Example 46

From project managed-ledger, under directory /src/main/java/org/apache/bookkeeper/mledger/impl/.

Source file: ManagedLedgerImpl.java

  15 
vote

public ManagedLedgerImpl(ManagedLedgerFactoryImpl factory,BookKeeper bookKeeper,MetaStore store,ManagedLedgerConfig config,ScheduledExecutorService executor,final String name){
  this.factory=factory;
  this.bookKeeper=bookKeeper;
  this.config=config;
  this.store=store;
  this.name=name;
  this.executor=executor;
  this.currentLedger=null;
  this.state=State.None;
  this.ledgersVersion=null;
  RemovalListener<Long,LedgerHandle> removalListener=new RemovalListener<Long,LedgerHandle>(){
    public void onRemoval(    RemovalNotification<Long,LedgerHandle> entry){
      LedgerHandle ledger=entry.getValue();
      log.debug("[{}] Closing ledger: {} cause={}",va(name,ledger.getId(),entry.getCause()));
      try {
        ledger.close();
      }
 catch (      Exception e) {
        log.error("[{}] Error closing ledger {}",name,ledger.getId());
        log.error("Exception: ",e);
      }
    }
  }
;
  this.ledgerCache=CacheBuilder.newBuilder().expireAfterAccess(60,TimeUnit.SECONDS).removalListener(removalListener).build();
}
 

Example 47

From project monitor-event-tap, under directory /src/main/java/com/proofpoint/event/monitor/.

Source file: CloudWatchUpdater.java

  15 
vote

@Inject public CloudWatchUpdater(AmazonConfig config,AmazonCloudWatch cloudWatch,@MonitorExecutorService ScheduledExecutorService executorService,NodeInfo nodeInfo){
  Preconditions.checkNotNull(config,"config is null");
  Preconditions.checkNotNull(cloudWatch,"cloudWatch is null");
  Preconditions.checkNotNull(executorService,"executorService is null");
  Preconditions.checkNotNull(nodeInfo,"nodeInfo is null");
  this.updateTime=config.getCloudWatchUpdateTime();
  this.cloudWatch=cloudWatch;
  this.executorService=executorService;
  this.nodeInfo=nodeInfo;
}
 

Example 48

From project msgpack-rpc, under directory /java/src/main/java/org/msgpack/rpc/loop/.

Source file: EventLoop.java

  15 
vote

public EventLoop(ExecutorService workerExecutor,ExecutorService ioExecutor,ScheduledExecutorService scheduledExecutor,MessagePack messagePack){
  this.workerExecutor=workerExecutor;
  this.scheduledExecutor=scheduledExecutor;
  this.ioExecutor=ioExecutor;
  this.messagePack=messagePack;
}
 

Example 49

From project onebusaway-gtfs-realtime-exporter, under directory /src/main/java/org/onebusway/gtfs_realtime/exporter/.

Source file: GtfsRealtimeExporterModule.java

  15 
vote

@Override protected void configure(){
  bind(GtfsRealtimeProvider.class).to(GtfsRealtimeProviderImpl.class);
  bind(GtfsRealtimeMutableProvider.class).to(GtfsRealtimeProviderImpl.class);
  bind(AlertsFileWriter.class);
  bind(TripUpdatesFileWriter.class);
  bind(VehiclePositionsFileWriter.class);
  bind(AlertsServlet.class);
  bind(TripUpdatesServlet.class);
  bind(VehiclePositionsServlet.class);
  bind(ScheduledExecutorService.class).annotatedWith(Names.named(NAME_EXECUTOR)).toInstance(Executors.newSingleThreadScheduledExecutor());
}
 

Example 50

From project org.ops4j.pax.web, under directory /pax-web-extender-war/src/main/java/org/ops4j/pax/web/extender/war/internal/.

Source file: WebEventDispatcher.java

  15 
vote

public WebEventDispatcher(final BundleContext bundleContext,ScheduledExecutorService executors){
  NullArgumentException.validateNotNull(bundleContext,"Bundle Context");
  NullArgumentException.validateNotNull(executors,"Thread executors");
  this.executors=executors;
  this.webListenerTracker=new ServiceTracker(bundleContext,WebListener.class.getName(),new ServiceTrackerCustomizer(){
    public Object addingService(    ServiceReference reference){
      WebListener listener=(WebListener)bundleContext.getService(reference);
synchronized (listeners) {
        sendInitialEvents(listener);
        listeners.add(listener);
      }
      return listener;
    }
    public void modifiedService(    ServiceReference reference,    Object service){
    }
    public void removedService(    ServiceReference reference,    Object service){
      listeners.remove(service);
      bundleContext.ungetService(reference);
    }
  }
);
  this.webListenerTracker.open();
}
 

Example 51

From project platform_3, under directory /discovery/src/main/java/com/proofpoint/discovery/client/.

Source file: CachingServiceSelector.java

  15 
vote

public CachingServiceSelector(String type,ServiceSelectorConfig selectorConfig,DiscoveryLookupClient lookupClient,ScheduledExecutorService executor){
  Preconditions.checkNotNull(type,"type is null");
  Preconditions.checkNotNull(selectorConfig,"selectorConfig is null");
  Preconditions.checkNotNull(lookupClient,"client is null");
  Preconditions.checkNotNull(executor,"executor is null");
  this.type=type;
  this.pool=selectorConfig.getPool();
  this.lookupClient=lookupClient;
  this.executor=executor;
}
 

Example 52

From project platform_packages_apps_contacts, under directory /src/com/android/contacts/voicemail/.

Source file: VoicemailPlaybackPresenter.java

  15 
vote

public VoicemailPlaybackPresenter(PlaybackView view,MediaPlayerProxy player,Uri voicemailUri,ScheduledExecutorService executorService,boolean startPlayingImmediately,AsyncTaskExecutor asyncTaskExecutor,PowerManager.WakeLock wakeLock){
  mView=view;
  mPlayer=player;
  mVoicemailUri=voicemailUri;
  mStartPlayingImmediately=startPlayingImmediately;
  mAsyncTaskExecutor=asyncTaskExecutor;
  mPositionUpdater=new PositionUpdater(executorService,SLIDER_UPDATE_PERIOD_MILLIS);
  mWakeLock=wakeLock;
}
 

Example 53

From project Red5, under directory /src/org/red5/server/net/filter/.

Source file: TrafficShapingFilter.java

  15 
vote

public TrafficShapingFilter(ScheduledExecutorService scheduledExecutor,MessageSizeEstimator messageSizeEstimator,int maxReadThroughput,int maxWriteThroughput){
  log.debug("ctor - executor: {} estimator: {} max read: {} max write: {}",new Object[]{scheduledExecutor,messageSizeEstimator,maxReadThroughput,maxWriteThroughput});
  if (scheduledExecutor == null) {
    scheduledExecutor=new ScheduledThreadPoolExecutor(poolSize);
  }
  if (messageSizeEstimator == null) {
    messageSizeEstimator=new DefaultMessageSizeEstimator(){
      @Override public int estimateSize(      Object message){
        if (message instanceof IoBuffer) {
          return ((IoBuffer)message).remaining();
        }
        return super.estimateSize(message);
      }
    }
;
  }
  this.scheduledExecutor=scheduledExecutor;
  this.messageSizeEstimator=messageSizeEstimator;
  setMaxReadThroughput(maxReadThroughput);
  setMaxWriteThroughput(maxWriteThroughput);
}
 

Example 54

From project red5-server, under directory /src/org/red5/server/net/filter/.

Source file: TrafficShapingFilter.java

  15 
vote

public TrafficShapingFilter(ScheduledExecutorService scheduledExecutor,MessageSizeEstimator messageSizeEstimator,int maxReadThroughput,int maxWriteThroughput){
  log.debug("ctor - executor: {} estimator: {} max read: {} max write: {}",new Object[]{scheduledExecutor,messageSizeEstimator,maxReadThroughput,maxWriteThroughput});
  if (scheduledExecutor == null) {
    scheduledExecutor=new ScheduledThreadPoolExecutor(poolSize);
  }
  if (messageSizeEstimator == null) {
    messageSizeEstimator=new DefaultMessageSizeEstimator(){
      @Override public int estimateSize(      Object message){
        if (message instanceof IoBuffer) {
          return ((IoBuffer)message).remaining();
        }
        return super.estimateSize(message);
      }
    }
;
  }
  this.scheduledExecutor=scheduledExecutor;
  this.messageSizeEstimator=messageSizeEstimator;
  setMaxReadThroughput(maxReadThroughput);
  setMaxWriteThroughput(maxWriteThroughput);
}
 

Example 55

From project Schedule, under directory /android/src/com/happytap/schedule/service/.

Source file: ThreadHelper.java

  15 
vote

public static ScheduledExecutorService getScheduler(){
  if (POOL.isShutdown() || POOL.isTerminated()) {
    POOL=Executors.newScheduledThreadPool(2);
  }
  return POOL;
}
 

Example 56

From project serialization, under directory /writer/src/main/java/com/ning/metrics/serialization/writer/.

Source file: DiskSpoolEventWriter.java

  15 
vote

public DiskSpoolEventWriter(final EventHandler eventHandler,final String spoolPath,final boolean flushEnabled,final long flushIntervalInSeconds,final ScheduledExecutorService executor,final SyncType syncType,final int syncBatchSize,final CompressionCodec codec,final EventSerializer eventSerializer){
  this.eventHandler=eventHandler;
  this.syncType=syncType;
  this.syncBatchSize=syncBatchSize;
  this.spoolDirectory=new File(spoolPath);
  this.executor=executor;
  this.tmpSpoolDirectory=new File(spoolDirectory,"_tmp");
  this.quarantineDirectory=new File(spoolDirectory,"_quarantine");
  this.lockDirectory=new File(spoolDirectory,"_lock");
  this.flushEnabled=new AtomicBoolean(flushEnabled);
  this.flushIntervalInSeconds=new AtomicLong(flushIntervalInSeconds);
  this.codec=codec;
  this.eventSerializer=eventSerializer;
  writeTimerName=new MetricName(DiskSpoolEventWriter.class,spoolPath);
  writeTimer=Metrics.newTimer(writeTimerName,TimeUnit.MILLISECONDS,TimeUnit.SECONDS);
  createSpoolDir(spoolDirectory);
  createSpoolDir(tmpSpoolDirectory);
  createSpoolDir(quarantineDirectory);
  createSpoolDir(lockDirectory);
  if (!spoolDirectory.exists() || !tmpSpoolDirectory.exists() || !quarantineDirectory.exists()|| !lockDirectory.exists()) {
    throw new IllegalArgumentException("Eventwriter misconfigured - couldn't create the spool directories");
  }
  scheduleFlush();
  recoverFiles();
  acceptsEvents=true;
}
 

Example 57

From project shiro, under directory /core/src/main/java/org/apache/shiro/realm/text/.

Source file: PropertiesRealm.java

  15 
vote

protected void startReloadThread(){
  if (this.reloadIntervalSeconds > 0) {
    this.scheduler=Executors.newSingleThreadScheduledExecutor();
    ((ScheduledExecutorService)this.scheduler).scheduleAtFixedRate(this,reloadIntervalSeconds,reloadIntervalSeconds,TimeUnit.SECONDS);
  }
}
 

Example 58

From project spring-framework-samples, under directory /task-config/src/main/java/task/.

Source file: EnableScheduledTasks.java

  15 
vote

private Object getScheduler(){
  try {
    return applicationContext.getBean("scheduler",TaskScheduler.class);
  }
 catch (  NoSuchBeanDefinitionException e) {
  }
  try {
    return applicationContext.getBean("scheduler",ScheduledExecutorService.class);
  }
 catch (  NoSuchBeanDefinitionException e) {
  }
  return null;
}
 

Example 59

From project starflow, under directory /src/main/java/com/googlecode/starflow/core/util/.

Source file: ExecutorServiceHelper.java

  15 
vote

/** 
 * Creates a new scheduled thread pool which can schedule threads.
 * @param poolSize the core pool size
 * @param pattern  pattern of the thread name
 * @param name     ${name} in the pattern name
 * @param daemon   whether the threads is daemon or not
 * @return the created pool
 */
public static ScheduledExecutorService newScheduledThreadPool(final int poolSize,final String pattern,final String name,final boolean daemon){
  return Executors.newScheduledThreadPool(poolSize,new ThreadFactory(){
    public Thread newThread(    Runnable r){
      Thread answer=new Thread(r,getThreadName(pattern,name));
      answer.setDaemon(daemon);
      return answer;
    }
  }
);
}
 

Example 60

From project Tanks_1, under directory /src/org/apache/mina/filter/reqres/.

Source file: RequestResponseFilter.java

  15 
vote

public RequestResponseFilter(final ResponseInspector responseInspector,ScheduledExecutorService timeoutScheduler){
  if (responseInspector == null) {
    throw new IllegalArgumentException("responseInspector");
  }
  if (timeoutScheduler == null) {
    throw new IllegalArgumentException("timeoutScheduler");
  }
  this.responseInspectorFactory=new ResponseInspectorFactory(){
    public ResponseInspector getResponseInspector(){
      return responseInspector;
    }
  }
;
  this.timeoutScheduler=timeoutScheduler;
}
 

Example 61

From project teamcity-nuget-support, under directory /nuget-server/src/jetbrains/buildServer/nuget/server/trigger/impl/.

Source file: PackageChangesCheckerThreadTask.java

  15 
vote

public PackageChangesCheckerThreadTask(@NotNull final PackageCheckQueue holder,@NotNull final ScheduledExecutorService executor,@NotNull final Collection<PackageChecker> checkers,@NotNull final NuGetSourceChecker preCheckers){
  myHolder=holder;
  myExecutor=executor;
  myCheckers=checkers;
  myPreCheckers=preCheckers;
}
 

Example 62

From project virgo.kernel, under directory /org.eclipse.virgo.kernel.services/src/main/java/org/eclipse/virgo/kernel/services/concurrent/management/.

Source file: StandardExecutorServiceInfo.java

  15 
vote

/** 
 * {@inheritDoc}
 */
public String getTypeName(){
  ExecutorServiceStatistics executorService=this.managedExecutorService.get();
  if (executorService == null) {
    return null;
  }
 else {
    return (executorService instanceof ScheduledExecutorService ? ScheduledExecutorService.class.getSimpleName() : ExecutorService.class.getSimpleName());
  }
}