Java Code Examples for java.util.concurrent.Executors
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 anadix, under directory /integration/anadix-selenium/src/main/java/org/anadix/utils/.
Source file: MultithreadedAnalyzer.java

public MultithreadedAnalyzer(Analyzer analyzer,int threads){ if (analyzer == null) { throw new NullPointerException("analyzer can't be null"); } if (threads < 1) { throw new IllegalArgumentException("thread count must be greater than or equal to 1"); } this.analyzer=analyzer; exec=Executors.newFixedThreadPool(threads); results=new ConcurrentHashMap<Integer,Future<Report>>(); }
Example 2
From project adbcj, under directory /mysql/netty/src/main/java/org/adbcj/mysql/netty/.
Source file: MysqlConnectionManager.java

public MysqlConnectionManager(String host,int port,String username,String password,String schema,Properties properties){ super(username,password,schema,properties); executorService=Executors.newCachedThreadPool(); ChannelFactory factory=new NioClientSocketChannelFactory(executorService,executorService); bootstrap=new ClientBootstrap(factory); init(host,port); }
Example 3
From project AdServing, under directory /modules/db/src/main/java/net/mad/ads/db/.
Source file: AdDBManager.java

public AdDBManager build(){ AdDBManager manager=new AdDBManager(blocking); if (!blocking && executorService == null) { executorService=Executors.newFixedThreadPool(1); } manager.executorService=executorService; return manager; }
Example 4
From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageSchema/.
Source file: DatabaseDefn.java

/** * There should be one DatabaseInfo object per agileBase application instance. This constructor generates it. It bootstraps the application. All schema objects are loaded into memory from the pervasive store. The authentication manager (AuthManagerInfo), store of all users, roles and permissions is loaded too. Finally, the data manager (a DataManagementInfo object) is created and initialised * @throws CantDoThatException If more than one Authenticator was found in the database */ public DatabaseDefn(DataSource relationalDataSource,String webAppRoot) throws SQLException, ObjectNotFoundException, CantDoThatException, MissingParametersException, CodingErrorException { this.relationalDataSource=relationalDataSource; Session hibernateSession=HibernateUtil.currentSession(); try { this.authManager=new AuthManager(relationalDataSource); } finally { HibernateUtil.closeSession(); } this.dataManagement=new DataManagement(relationalDataSource,webAppRoot,this.authManager); DashboardPopulator dashboardPopulator=new DashboardPopulator(this); this.initialDashboardPopulatorThread=new Thread(dashboardPopulator); this.initialDashboardPopulatorThread.start(); int hourNow=Calendar.getInstance().get(Calendar.HOUR_OF_DAY); int initialDelay=24 + AppProperties.lowActivityHour - hourNow; this.dashboardScheduler=Executors.newSingleThreadScheduledExecutor(); this.scheduledDashboardPopulate=dashboardScheduler.scheduleAtFixedRate(dashboardPopulator,initialDelay,24,TimeUnit.HOURS); }
Example 5
public Client(){ String host="127.0.0.1"; int port=7890; ClientBootstrap bootstrap=new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool())); bootstrap.setPipelineFactory(new ChannelPipelineFactory(){ public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new ObjectEncoder(),new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)),new ClientHandler(Client.this)); } } ); ChannelFuture future=bootstrap.connect(new InetSocketAddress(host,port)); future.getChannel().getCloseFuture().awaitUninterruptibly(); bootstrap.releaseExternalResources(); }
Example 6
From project agraph-java-client, under directory /src/test/pool/.
Source file: AGConnPoolSessionTest.java

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

private HttpEventClient newEventClient(List<URI> v2Uris){ HttpServiceSelector v1Selector=new StaticHttpServiceSelector("event","general",Collections.<URI>emptyList()); HttpServiceSelector v2Selector=new StaticHttpServiceSelector("collector","general",v2Uris); HttpEventClientConfig config=new HttpEventClientConfig(); Set<EventTypeMetadata<?>> eventTypes=getValidEventTypeMetaDataSet(FixedDummyEventClass.class); JsonEventWriter eventWriter=new JsonEventWriter(eventTypes,config); return new HttpEventClient(v1Selector,v2Selector,eventWriter,new NodeInfo("test"),config,new AsyncHttpClient(new ApacheHttpClient(new HttpClientConfig().setConnectTimeout(new Duration(10,SECONDS))),Executors.newCachedThreadPool())); }
Example 8
From project akubra, under directory /akubra-rmi/src/main/java/org/akubraproject/rmi/server/.
Source file: Exporter.java

private static ScheduledExecutorService createExecutor(){ return Executors.newSingleThreadScheduledExecutor(new ThreadFactory(){ public Thread newThread( Runnable r){ Thread t=new Thread(r,"akubra-rmi-unexporter"); t.setPriority(Thread.MIN_PRIORITY); t.setDaemon(true); return t; } } ); }
Example 9
From project alljoyn_java, under directory /src/org/alljoyn/bus/.
Source file: BusAttachment.java

/** * Constructs a BusAttachment. * @param applicationName the name of the application * @param policy if this attachment is allowed to receive messagesfrom remote devices */ public BusAttachment(String applicationName,RemoteMessage policy){ isShared=false; isConnected=false; this.allowRemoteMessages=(policy == RemoteMessage.Receive); busAuthListener=new AuthListenerInternal(); try { foundAdvertisedName=getClass().getDeclaredMethod("foundAdvertisedName",String.class,Short.class,String.class); foundAdvertisedName.setAccessible(true); lostAdvertisedName=getClass().getDeclaredMethod("lostAdvertisedName",String.class,Short.class,String.class); lostAdvertisedName.setAccessible(true); } catch ( NoSuchMethodException ex) { } create(applicationName,allowRemoteMessages); dbusbo=new ProxyBusObject(this,"org.freedesktop.DBus","/org/freedesktop/DBus",SESSION_ID_ANY,new Class[]{DBusProxyObj.class}); dbus=dbusbo.getInterface(DBusProxyObj.class); executor=Executors.newSingleThreadExecutor(); }
Example 10
From project amsterdam, under directory /src/main/java/com/unicodecollective/amsterdam/.
Source file: TokenBucket.java

public void startFilling(FillRate fillRate){ checkNotNull(fillRate); checkState(bucketFillerExecutor == null,"Bucket filler has already been started for this token bucket."); bucketFillerExecutor=Executors.newSingleThreadExecutor(); bucketFillerExecutor.execute(new BucketFiller(fillRate)); filling=true; }
Example 11
From project android-joedayz, under directory /Proyectos/GreenDroid/src/greendroid/app/.
Source file: GDApplication.java

/** * Return an ExecutorService (global to the entire application) that may be used by clients when running long tasks in the background. * @return An ExecutorService to used when processing long running tasks */ public ExecutorService getExecutor(){ if (mExecutorService == null) { mExecutorService=Executors.newFixedThreadPool(CORE_POOL_SIZE,sThreadFactory); } return mExecutorService; }
Example 12
From project android-service-arch, under directory /ServiceFramework/src/ru/evilduck/framework/service/.
Source file: SFThreadPoolIntentService.java

protected static PoolConfigurator asFixedThreadPool(final int threadCount){ return new PoolConfigurator(){ @Override public ExecutorService configure(){ return Executors.newFixedThreadPool(threadCount); } } ; }
Example 13
From project androidpn, under directory /androidpn-client/src/org/androidpn/client/.
Source file: NotificationService.java

public NotificationService(){ notificationReceiver=new NotificationReceiver(); connectivityReceiver=new ConnectivityReceiver(this); phoneStateListener=new PhoneStateChangeListener(this); executorService=Executors.newSingleThreadExecutor(); taskSubmitter=new TaskSubmitter(this); taskTracker=new TaskTracker(this); }
Example 14
From project androidquery, under directory /src/com/androidquery/callback/.
Source file: AbstractAjaxCallback.java

public static void execute(Runnable job){ if (fetchExe == null) { fetchExe=Executors.newFixedThreadPool(NETWORK_POOL); } fetchExe.execute(job); }
Example 15
From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.
Source file: RegistrySharedObject.java

/** * @since 3.0 */ public Future asyncGetRemoteServiceReferences(final ID[] idFilter,final String clazz,final RegularExpression filter){ ExecutorService executor=Executors.newCachedThreadPool(); return executor.submit(new Runnable(){ public void run(){ try { getRemoteServiceReferences(idFilter,clazz,filter); } catch ( InvalidSyntaxException e) { e.printStackTrace(); } } } ); }
Example 16
From project android_packages_apps_FileManager, under directory /src/org/openintents/filemanager/.
Source file: ThumbnailLoader.java

/** * Used for loading and decoding thumbnails from files. * @author PhilipHayes * @param context Current application context. */ public ThumbnailLoader(Context context){ mContext=context; purger=new Runnable(){ @Override public void run(){ Log.d(TAG,"Purge Timer hit; Clearing Caches."); clearCaches(); } } ; purgeHandler=new Handler(); mExecutor=Executors.newFixedThreadPool(POOL_SIZE); mBlacklist=new ArrayList<String>(); mSoftBitmapCache=new ConcurrentHashMap<String,SoftReference<Bitmap>>(MAX_CACHE_CAPACITY / 2); mHardBitmapCache=new LinkedHashMap<String,Bitmap>(MAX_CACHE_CAPACITY / 2,0.75f,true){ /** */ private static final long serialVersionUID=1347795807259717646L; @Override protected boolean removeEldestEntry( LinkedHashMap.Entry<String,Bitmap> eldest){ if (size() > MAX_CACHE_CAPACITY) { mSoftBitmapCache.put(eldest.getKey(),new SoftReference<Bitmap>(eldest.getValue())); return true; } else { return false; } } } ; }
Example 17
From project android_packages_apps_QuickSearchBox, under directory /src/com/android/quicksearchbox/.
Source file: QsbApplication.java

protected Factory<Executor> createExecutorFactory(final int numThreads){ final ThreadFactory threadFactory=getQueryThreadFactory(); return new Factory<Executor>(){ public Executor create(){ return Executors.newFixedThreadPool(numThreads,threadFactory); } } ; }
Example 18
From project any23, under directory /plugins/basic-crawler/src/main/java/org/apache/any23/plugin/crawler/.
Source file: SiteCrawler.java

/** * Starts the crawling process. * @param seed the starting URL for the crawler process. * @param filters filters to be applied to the crawler process. Can be <code>null</code>. * @param wait if <code>true</code> the process will wait for the crawler termination. * @throws Exception */ public synchronized void start(final URL seed,final Pattern filters,final boolean wait) throws Exception { SharedData.setCrawlData(seed.toExternalForm(),filters,Collections.synchronizedList(listeners)); controller.addSeed(seed.toExternalForm()); final Runnable internalRunnable=new Runnable(){ @Override public void run(){ controller.start(getWebCrawler(),getNumOfCrawlers()); } } ; if (wait) { internalRunnable.run(); } else { if (service != null) throw new IllegalStateException("Another service seems to run."); service=Executors.newSingleThreadExecutor(); service.execute(internalRunnable); } }
Example 19
From project aranea, under directory /server/src/main/java/no/dusken/aranea/web/spring/.
Source file: ChainedController.java

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

/** * This method is implemented with {@link java.util.concurrent.ScheduledExecutorService#scheduleWithFixedDelay(Runnable,long,long,TimeUnit)} */ @Override protected synchronized void schedule(Runnable runnable){ executor=Executors.newScheduledThreadPool(1,new ThreadFactory(){ @Override public Thread newThread( Runnable r){ Thread t=new Thread(r,"pollingConfigurationSource"); t.setDaemon(true); return t; } } ); executor.scheduleWithFixedDelay(runnable,initialDelayMillis,delayMillis,TimeUnit.MILLISECONDS); }
Example 21
From project Arecibo, under directory /collector/src/test/java/com/ning/arecibo/collector/.
Source file: TestEventCollectorServer.java

@BeforeMethod(alwaysRun=true) public void setUp() throws Exception { final String ddl=IOUtils.toString(TestEventCollectorServer.class.getResourceAsStream("/collector.sql")); helper.startMysql(); helper.initDb(ddl); Executors.newFixedThreadPool(1).submit(new Runnable(){ @Override public void run(){ try { server.start(); } catch ( Exception e) { Assert.fail(); } } } ); while (!server.isRunning()) { Thread.sleep(1000); } Assert.assertEquals(eventHandlers.size(),1); timelineEventHandler=(TimelineEventHandler)eventHandlers.get(0); }
Example 22
From project astyanax, under directory /src/main/java/com/netflix/astyanax/connectionpool/impl/.
Source file: SmaLatencyScoreStrategyImpl.java

public SmaLatencyScoreStrategyImpl(int updateInterval,int resetInterval,int windowSize,double badnessThreshold){ this.updateInterval=updateInterval; this.resetInterval=resetInterval; this.badnessThreshold=badnessThreshold; this.windowSize=windowSize; this.executor=Executors.newScheduledThreadPool(1,new ThreadFactoryBuilder().setDaemon(true).build()); this.instances=new NonBlockingHashSet<Instance>(); }
Example 23
From project atlas, under directory /src/main/java/com/ning/atlas/.
Source file: ActualDeployment.java

public void destroy(){ ListeningExecutorService es=MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()); List<LifecycleListener> listeners=environment.getListeners(); startDeployment(listeners); log.info("beginning unwind"); fire(Events.startUnwind,listeners); Set<Identity> identities=space.findAllIdentities(); Set<Identity> to_unwind=Sets.newHashSet(); for ( Identity identity : identities) { final Maybe<WhatWasDone> mwwd=space.get(identity.createChild("atlas","unwind"),WhatWasDone.class,Missing.RequireAll); if (mwwd.isKnown()) { to_unwind.add(identity); } } unwindAll(es,to_unwind); log.info("finished unwind"); fire(Events.finishUnwind,listeners); finishDeployment(listeners); es.shutdown(); }
Example 24
From project AudioBox.fm-JavaLib, under directory /audiobox.fm-core/src/main/java/fm/audiobox/configurations/.
Source file: DefaultConfiguration.java

public DefaultConfiguration(String appName,int major,int minor,int revision,ContentFormat requestFormat){ this.setApplicationName(appName); this.setVersion(major,minor,revision); this.setRequestFormat(requestFormat); this.executor=Executors.newSingleThreadExecutor(); this.setCacheManager(new DefaultCacheManager()); String version="unattended"; String ga_flag="S"; try { version=DefaultConfiguration.getProperty(PROP_PREFIX + "version"); ga_flag=version.contains(SNAPSHOT) ? ga_flag : "GA"; version=version.replace(SNAPSHOT,""); } catch ( FileNotFoundException e) { log.error("Environment properties file not found: " + e.getMessage()); } catch ( IOException e) { log.error("Unable to access the environment properties file: " + e.getMessage()); } mUserAgent="AudioBox.fm/" + version + " (Java; "+ ga_flag+ "; "+ System.getProperty("os.name")+ " "+ System.getProperty("os.arch")+ "; "+ System.getProperty("user.language")+ "; "+ System.getProperty("java.runtime.version")+ ") "+ System.getProperty("java.vm.name")+ "/"+ System.getProperty("java.vm.version")+ " "+ APP_NAME_PLACEHOLDER+ "/"+ VERSION_PLACEHOLDER; log.info("Configuration loaded"); }
Example 25
From project avro, under directory /lang/java/ipc/src/test/java/org/apache/avro/ipc/.
Source file: TestNettyServerConcurrentExecution.java

@Test(timeout=30000) public void test() throws Exception { final CountDownLatch waitLatch=new CountDownLatch(1); server=new NettyServer(new SpecificResponder(Simple.class,new SimpleImpl(waitLatch)),new InetSocketAddress(0),new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()),new ExecutionHandler(Executors.newCachedThreadPool())); server.start(); transceiver=new NettyTransceiver(new InetSocketAddress(server.getPort()),TestNettyServer.CONNECT_TIMEOUT_MILLIS); final Simple.Callback simpleClient=SpecificRequestor.getClient(Simple.Callback.class,transceiver); Assert.assertEquals(3,simpleClient.add(1,2)); new Thread(){ @Override public void run(){ setName(TestNettyServerConcurrentExecution.class.getSimpleName() + "Ack Thread"); try { waitLatch.await(); simpleClient.ack(); } catch ( InterruptedException e) { e.printStackTrace(); } } } .start(); String response=simpleClient.hello("wait"); Assert.assertEquals("wait",response); }
Example 26
From project aws-tasks, under directory /src/main/java/datameer/awstasks/aws/ec2/ssh/.
Source file: SshClientImpl.java

private void executeCallables(List<SshCallable> sshCallables) throws IOException { ExecutorService e=Executors.newCachedThreadPool(); List<Future<SshCallable>> futureList=Lists.newArrayListWithCapacity(sshCallables.size()); for ( SshCallable sshCallable : sshCallables) { futureList.add(e.submit(sshCallable)); } waitForSshCommandCompletion(futureList); }
Example 27
From project azkaban, under directory /azkaban/src/unit/azkaban/utils/process/.
Source file: ProcessTest.java

@Test public void testKill() throws Exception { ExecutorService executor=Executors.newFixedThreadPool(2); AzkabanProcess p1=new AzkabanProcessBuilder("sleep","10").build(); runInSeperateThread(executor,p1); assertTrue("Soft kill should interrupt sleep.",p1.softKill(5,TimeUnit.SECONDS)); p1.awaitCompletion(); AzkabanProcess p2=new AzkabanProcessBuilder("sleep","10").build(); runInSeperateThread(executor,p2); p2.hardKill(); p2.awaitCompletion(); assertTrue(p2.isComplete()); }
Example 28
From project b1-pack, under directory /standard/src/test/java/org/b1/pack/standard/common/.
Source file: SynchronousPipeTest.java

@Test public void test_read_write() throws Exception { ExecutorService service=Executors.newCachedThreadPool(); Future<Boolean> readerFuture=service.submit(new Callable<Boolean>(){ @Override public Boolean call() throws Exception { byte[] buffer=new byte[1000]; readerStarted=true; assertEquals(0,pipe.inputStream.read(buffer,5,0)); assertFalse(writerStarted); assertEquals(2,pipe.inputStream.read(buffer,10,2)); assertEquals("01",new String(buffer,10,2,Charsets.UTF_8)); assertTrue(writerStarted); assertEquals(8,pipe.inputStream.read(buffer,1,10)); assertEquals("23456789",new String(buffer,1,8,Charsets.UTF_8)); assertFalse(writerClosed); assertEquals(-1,pipe.inputStream.read(buffer,1,10)); assertTrue(writerClosed); return true; } } ); Thread.sleep(500); assertTrue(readerStarted); Future<Boolean> writerFuture=service.submit(new Callable<Boolean>(){ @Override public Boolean call() throws Exception { writerStarted=true; pipe.outputStream.write(TEST_BYTES); Thread.sleep(500); pipe.outputStream.close(); writerClosed=true; return true; } } ); assertTrue(readerFuture.get()); assertTrue(writerFuture.get()); }
Example 29
From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/event/.
Source file: EventManager.java

/** * Fire the specified event asynchronously. * @param < T > the result type * @param event the specified event * @return future result * @throws EventException event exception */ public <T>Future<T> fireEventAsynchronously(final Event<?> event) throws EventException { final ExecutorService executorService=Executors.newSingleThreadExecutor(); final FutureTask<T> futureTask=new FutureTask<T>(new Callable<T>(){ @Override public T call() throws Exception { synchronizedEventQueue.fireEvent(event); return null; } } ); executorService.execute(futureTask); return futureTask; }
Example 30
From project backup-plugin, under directory /src/main/java/org/jvnet/hudson/plugins/backup/.
Source file: BackupLink.java

public void doLaunchBackup(StaplerRequest req,StaplerResponse rsp) throws IOException { Hudson.getInstance().checkPermission(Hudson.ADMINISTER); if (task != null) { if (!task.isFinished()) { rsp.sendRedirect("backup"); return; } } BackupConfig configuration=getConfiguration(); String fileNameTemplate=configuration.getTargetDirectory() + File.separator + configuration.getFileNameTemplate(); String fileName=new FileNameManager().getFileName(fileNameTemplate,configuration); LOGGER.log(Level.INFO,"backup file name = {0} (generated from template :{1})",new Object[]{fileName,fileNameTemplate}); task=new BackupTask(configuration,getRootDirectory(),fileName,getBackupLogFile().getAbsolutePath()); Thread thread=Executors.defaultThreadFactory().newThread(task); thread.start(); rsp.sendRedirect("backup"); }
Example 31
From project bagheera, under directory /src/main/java/com/mozilla/bagheera/consumer/.
Source file: KafkaConsumer.java

public KafkaConsumer(String topic,Properties props,int numThreads){ LOG.info("# of threads: " + numThreads); executor=Executors.newFixedThreadPool(numThreads); workers=new ArrayList<Future<?>>(numThreads); ConsumerConfig consumerConfig=new ConsumerConfig(props); consumerConnector=kafka.consumer.Consumer.createJavaConsumerConnector(consumerConfig); streams=consumerConnector.createMessageStreamsByFilter(new Whitelist(topic),numThreads); consumed=Metrics.newMeter(new MetricName("bagheera","consumer",topic + ".consumed"),"messages",TimeUnit.SECONDS); }
Example 32
From project bbb-java, under directory /src/main/java/org/mconf/bbb/.
Source file: RtmpConnection.java

public boolean connect(){ if (factory == null) factory=new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()); bootstrap=new ClientBootstrap(factory); bootstrap.setPipelineFactory(pipelineFactory()); future=bootstrap.connect(new InetSocketAddress(options.getHost(),options.getPort())); future.addListener(this); return true; }
Example 33
From project be.norio.twunch.android, under directory /src/be/norio/twunch/android/util/.
Source file: ViewServer.java

/** * Starts the server. * @return True if the server was successfully created, or false if italready exists. * @throws IOException If the server cannot be created. * @see #stop() * @see #isRunning() * @see WindowManagerService#startViewServer(int) */ public boolean start() throws IOException { if (mThread != null) { return false; } mServer=new ServerSocket(mPort,VIEW_SERVER_MAX_CONNECTIONS,InetAddress.getByAddress(new byte[]{127,0,0,1})); mThread=new Thread(this,"Local View Server [port=" + mPort + "]"); mThreadPool=Executors.newFixedThreadPool(VIEW_SERVER_MAX_CONNECTIONS); mThread.start(); return true; }
Example 34
public static FileCollection scan(File base){ CopyOnWriteArrayList<FileEntry> entries=new CopyOnWriteArrayList<FileEntry>(); CopyOnWriteArrayList<String> errors=new CopyOnWriteArrayList<String>(); try { ExecutorService threadPool=Executors.newFixedThreadPool(4); constructEntries(base,null,threadPool,entries,errors); threadPool.shutdown(); for (int i=0; !threadPool.awaitTermination(1,TimeUnit.HOURS); i++) { log.warning("" + i + "hours passed by."); if (i > 24) { errors.add("waiting for too long:" + threadPool.shutdownNow()); break; } } } catch ( Exception e) { throw new BeeException(e).addPayload(errors.toArray()); } if (errors.size() > 0) { throw new BeeException("has errors:").addPayload(errors.toArray()); } FileCollection fileCollection=new FileCollection(); FileEntry[] array=entries.toArray(new FileEntry[entries.size()]); Arrays.sort(array); fileCollection.entries=array; return fileCollection; }
Example 35
From project big-data-plugin, under directory /test-src/org/pentaho/di/job/entries/hadoopjobexecutor/.
Source file: SecurityManagerStackTest.java

@Test public void randomized_executions() throws Exception { final SecurityManagerStack stack=new SecurityManagerStack(); final Random random=new Random(); NoExitSecurityManager test=new NoExitSecurityManager(null); SecurityManager original=System.getSecurityManager(); stack.setSecurityManager(test); final int NUM_TASKS=10; ExecutorService exec=Executors.newFixedThreadPool(NUM_TASKS); exec.invokeAll(Collections.nCopies(NUM_TASKS,new Callable<Void>(){ @Override public Void call() throws Exception { NoExitSecurityManager sm=new NoExitSecurityManager(null); try { Thread.sleep(random.nextInt(1000)); System.out.println("set: " + sm); stack.setSecurityManager(sm); Thread.sleep(random.nextInt(1000)); } catch ( Exception ex) { } finally { System.out.println("rm : \t" + sm); stack.removeSecurityManager(sm); } return null; } } )); exec.shutdown(); exec.awaitTermination(3,TimeUnit.SECONDS); assertEquals(test,System.getSecurityManager()); stack.removeSecurityManager(test); assertEquals(original,System.getSecurityManager()); }
Example 36
From project blogs, under directory /wicket6-native-websockets/src/main/java/com/wicketinaction/charts/.
Source file: WebSocketChart.java

@Override protected void onConnect(ConnectedMessage message){ super.onConnect(message); Record[] data=generateData(); UpdateTask updateTask=new UpdateTask(message.getApplication(),message.getSessionId(),message.getPageId(),data); Executors.newScheduledThreadPool(1).schedule(updateTask,1,TimeUnit.SECONDS); }
Example 37
From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/.
Source file: BlueprintExtender.java

public void start(BundleContext ctx){ LOGGER.debug("Starting blueprint extender..."); this.context=ctx; handlers=new NamespaceHandlerRegistryImpl(ctx); executors=Executors.newScheduledThreadPool(3,new BlueprintThreadFactory("Blueprint Extender")); eventDispatcher=new BlueprintEventDispatcher(ctx,executors); containers=new HashMap<Bundle,BlueprintContainerImpl>(); int stateMask=Bundle.INSTALLED | Bundle.RESOLVED | Bundle.STARTING| Bundle.ACTIVE| Bundle.STOPPING; bt=new RecursiveBundleTracker(ctx,stateMask,new BlueprintBundleTrackerCustomizer()); proxyManager=new SingleServiceTracker<ProxyManager>(ctx,ProxyManager.class,new SingleServiceListener(){ public void serviceFound(){ LOGGER.debug("Found ProxyManager service, starting to process blueprint bundles"); bt.open(); } public void serviceLost(){ } public void serviceReplaced(){ } } ); proxyManager.open(); parserServiceReg=ctx.registerService(ParserService.class.getName(),new ParserServiceImpl(handlers),new Hashtable<String,Object>()); try { ctx.getBundle().loadClass(QUIESCE_PARTICIPANT_CLASS); quiesceParticipantReg=ctx.registerService(QUIESCE_PARTICIPANT_CLASS,new BlueprintQuiesceParticipant(ctx,this),new Hashtable<String,Object>()); } catch ( ClassNotFoundException e) { LOGGER.info("No quiesce support is available, so blueprint components will not participate in quiesce operations"); } LOGGER.debug("Blueprint extender started"); }
Example 38
@Override public void start(BundleContext context) throws Exception { registerWorkspaceURLHandler(context); super.start(context); plugin=this; Logger.setPlugin(this); this.bundleContext=context; scheduler=Executors.newScheduledThreadPool(1); bndActivator=new Activator(); bndActivator.start(context); indexerTracker=new IndexerTracker(context); indexerTracker.open(); resourceIndexerTracker=new ResourceIndexerTracker(context,1000); resourceIndexerTracker.open(); registerWorkspaceServiceFactory(context); central=new Central(); runStartupParticipants(); }
Example 39
From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.
Source file: BoneCP.java

/** * Starts off threads released to statement release helpers. * @param suffix of pool */ protected void initStmtReleaseHelper(String suffix){ this.statementsPendingRelease=new BoundedLinkedTransferQueue<StatementHandle>(this.config.getMaxConnectionsPerPartition() * 3); int statementReleaseHelperThreads=this.config.getStatementReleaseHelperThreads(); if (statementReleaseHelperThreads > 0) { this.setStatementCloseHelperExecutor(Executors.newFixedThreadPool(statementReleaseHelperThreads,new CustomThreadFactory("BoneCP-statement-close-helper-thread" + suffix,true))); for (int i=0; i < statementReleaseHelperThreads; i++) { getStatementCloseHelperExecutor().execute(new StatementReleaseHelperThread(this.statementsPendingRelease,this)); } } }
Example 40
From project byteman, under directory /sample/src/org/jboss/byteman/sample/helper/.
Source file: ThreadHistoryMonitorHelper.java

/** * 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 41
From project CamelInAction-source, under directory /chapter10/client/src/test/java/camelinaction/.
Source file: JavaFutureTest.java

@Test public void testFutureWithDone() throws Exception { Callable<String> task=new Callable<String>(){ public String call() throws Exception { LOG.info("Starting to process task"); Thread.sleep(5000); LOG.info("Task is now done"); return "Camel rocks"; } } ; ExecutorService executor=Executors.newCachedThreadPool(); LOG.info("Submitting task to ExecutorService"); Future<String> future=executor.submit(task); LOG.info("Task submitted and we got a Future handle"); boolean done=false; while (!done) { done=future.isDone(); LOG.info("Is the task done? " + done); if (!done) { Thread.sleep(2000); } } String answer=future.get(); LOG.info("The answer is: " + answer); }
Example 42
From project capedwarf-green, under directory /connect/src/test/java/org/jboss/test/capedwarf/connect/support/.
Source file: SunHttpServerEmbedded.java

public void start() throws IOException { if (server != null) server.stop(0); InetSocketAddress isa=new InetSocketAddress("localhost",8080); server=HttpServer.create(isa,0); server.setExecutor(Executors.newCachedThreadPool()); server.start(); }
Example 43
From project Carolina-Digital-Repository, under directory /fcrepo-clients/src/main/java/edu/unc/lib/dl/fedora/.
Source file: FedoraDataService.java

public void init(){ CustomizableThreadFactory ctf=new CustomizableThreadFactory(); ctf.setThreadGroupName(threadGroupPrefix + "FDS"); ctf.setThreadNamePrefix(threadGroupPrefix + "FDSWorker-"); this.executor=Executors.newFixedThreadPool(maxThreads,ctf); }
Example 44
From project cas, under directory /cas-server-core/src/test/java/org/jasig/cas/monitor/.
Source file: DataSourceMonitorTests.java

@Test public void testObserve() throws Exception { final DataSourceMonitor monitor=new DataSourceMonitor(this.dataSource); monitor.setExecutor(Executors.newSingleThreadExecutor()); monitor.setValidationQuery("SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS"); final PoolStatus status=monitor.observe(); assertEquals(StatusCode.OK,status.getCode()); }
Example 45
From project cascading, under directory /src/core/cascading/management/.
Source file: UnitOfWorkExecutorStrategy.java

public List<Future<Throwable>> start(UnitOfWork unitOfWork,int maxConcurrentThreads,Collection<Callable<Throwable>> values) throws InterruptedException { executor=Executors.newFixedThreadPool(maxConcurrentThreads); List<Future<Throwable>> futures=executor.invokeAll(values); executor.shutdown(); return futures; }
Example 46
From project caustic, under directory /console/test/net/caustic/util/.
Source file: ScopeFactoryTest.java

@Test public void testUniquenessInSeveralThreads() throws Exception { final Set<Scope> uuids=Collections.synchronizedSet(new HashSet<Scope>()); final Set<String> uuidStrings=Collections.synchronizedSet(new HashSet<String>()); List<Future<Boolean>> futures=new ArrayList<Future<Boolean>>(); int numThreads=100; ExecutorService executor=Executors.newCachedThreadPool(); for (int i=0; i < numThreads; i++) { futures.add(executor.submit(new UUIDFactoryTestRunnable(factory,uuids,uuidStrings))); } for ( Future<Boolean> future : futures) { assertTrue(future.get()); } assertEquals("Generated non-unique hashing UUIDs.",NUM_TESTS * numThreads,uuids.size()); assertEquals("Generated UUIDs with duplicate String values.",NUM_TESTS * numThreads,uuidStrings.size()); }
Example 47
From project channel-directory, under directory /src/com/buddycloud/channeldirectory/search/handler/common/mahout/.
Source file: PostgreSQLRecommenderDataModel.java

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 48
From project chililog-server, under directory /src/main/java/org/chililog/server/pubsub/jsonhttp/.
Source file: JsonHttpService.java

/** * 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 49
From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/dataloader/.
Source file: MetricDataLoaderPool.java

public void load(ChukwaConfiguration conf,FileSystem fs,FileStatus[] fileList) throws IOException { if (executor == null) { try { this.size=Integer.parseInt(conf.get(DATA_LOADER_THREAD_LIMIT)); } catch ( Exception e) { this.size=1; } executor=Executors.newFixedThreadPool(size); } if (completion == null) { completion=new ExecutorCompletionService(executor); } try { for (int i=0; i < fileList.length; i++) { String filename=fileList[i].getPath().toUri().toString(); log.info("Processing: " + filename); completion.submit(new MetricDataLoader(conf,fs,filename)); } for (int i=0; i < fileList.length; i++) { completion.take().get(); } } catch ( Exception e) { log.error(ExceptionUtil.getStackTrace(e)); throw new IOException(); } }
Example 50
From project CineShowTime-Android, under directory /Libraries/GreenDroid/src/greendroid/app/.
Source file: GDApplication.java

public ExecutorService getExecutor(){ if (mExecutorService == null) { mExecutorService=Executors.newFixedThreadPool(CORE_POOL_SIZE,sThreadFactory); } return mExecutorService; }
Example 51
From project cleo, under directory /src/main/java/cleo/search/typeahead/.
Source file: MultiTypeahead.java

public MultiTypeahead(String name,List<Typeahead<E>> typeaheads,ExecutorService executorService){ this.name=name; this.typeaheads=typeaheads; this.typeaheadMap=new HashMap<String,Typeahead<E>>(); for ( Typeahead<E> ta : typeaheads) { typeaheadMap.put(ta.getName(),ta); } this.executor=(executorService != null) ? executorService : Executors.newFixedThreadPool(100,new TypeaheadTaskThreadFactory()); logger.info(name + " started"); }
Example 52
From project cloudhopper-commons-util, under directory /src/test/java/com/cloudhopper/commons/util/demo/.
Source file: Window2Main.java

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 53
From project cloudhopper-smpp, under directory /src/main/java/com/cloudhopper/smpp/impl/.
Source file: DefaultSmppServer.java

/** * Creates a new default SmppServer. * @param configuration The server configuration to create this server with * @param serverHandler The handler implementation for handling bind requestsand creating/destroying sessions. * @param executor The executor that IO workers will be executed with. AnExecutors.newCachedDaemonThreadPool() is recommended. The max threads will never grow more than configuration.getMaxConnections() if NIO sockets are used. * @param monitorExecutor The scheduled executor that all sessions will shareto monitor themselves and expire requests. If null monitoring will be disabled. */ public DefaultSmppServer(final SmppServerConfiguration configuration,SmppServerHandler serverHandler,ExecutorService executor,ScheduledExecutorService monitorExecutor){ this.configuration=configuration; this.channels=new DefaultChannelGroup(); this.serverHandler=serverHandler; this.bossThreadPool=Executors.newCachedThreadPool(); if (configuration.isNonBlockingSocketsEnabled()) { this.channelFactory=new NioServerSocketChannelFactory(this.bossThreadPool,executor,configuration.getMaxConnectionSize()); } else { this.channelFactory=new OioServerSocketChannelFactory(this.bossThreadPool,executor); } this.serverBootstrap=new ServerBootstrap(this.channelFactory); this.serverBootstrap.setOption("reuseAddress",configuration.isReuseAddress()); this.serverConnector=new SmppServerConnector(channels,this); this.serverBootstrap.getPipeline().addLast(SmppChannelConstants.PIPELINE_SERVER_CONNECTOR_NAME,this.serverConnector); this.bindTimer=new Timer(configuration.getName() + "-BindTimer0",true); this.transcoder=new DefaultPduTranscoder(new DefaultPduTranscoderContext()); this.sessionIdSequence=new AtomicLong(0); this.monitorExecutor=monitorExecutor; this.counters=new DefaultSmppServerCounters(); if (configuration.isJmxEnabled()) { registerMBean(); } }
Example 54
From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/azure/.
Source file: MicrosoftAzureCloudDriver.java

@Override public MachineDetails[] startManagementMachines(final long duration,final TimeUnit unit) throws TimeoutException, CloudProvisioningException { long endTime=System.currentTimeMillis() + unit.toMillis(duration); try { azureClient.createAffinityGroup(affinityGroup,location,endTime); azureClient.createVirtualNetworkSite(addressSpace,affinityGroup,networkName,endTime); azureClient.createStorageAccount(affinityGroup,storageAccountName,endTime); } catch ( final MicrosoftAzureException e) { throw new CloudProvisioningException(e); } catch ( InterruptedException e) { throw new CloudProvisioningException(e); } int numberOfManagementMachines=this.cloud.getProvider().getNumberOfManagementMachines(); final ExecutorService executorService=Executors.newFixedThreadPool(numberOfManagementMachines); try { return startManagementMachines(endTime,numberOfManagementMachines,executorService); } finally { executorService.shutdown(); } }
Example 55
From project clustermeister, under directory /provisioning/src/main/java/com/github/nethad/clustermeister/provisioning/ec2/.
Source file: AmazonNodeManager.java

public AmazonNodeManager(Configuration configuration){ this.configuration=configuration; loadConfiguration(configuration); this.executorService=MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()); this.contextManager=new ContextManager(awsWebApiCredentials,executorService); this.ec2Facade=new AwsEc2Facade(contextManager); this.credentialsManager=new CredentialsManager(configuration,contextManager); this.amazonInstanceManager=new AmazonInstanceManager(contextManager,ec2Facade,profiles,artifactsToPreload); }
Example 56
protected static void attempt(Runnable task){ ExecutorService executorService=Executors.newFixedThreadPool(1); executorService.submit(task); executorService.shutdown(); try { Thread.sleep(100); } catch ( InterruptedException e) { throw new RuntimeException(e); } }
Example 57
From project cometd, under directory /cometd-java/cometd-java-client/src/main/java/org/cometd/client/.
Source file: BayeuxClient.java

protected void initialize(){ Long backoffIncrement=(Long)getOption(BACKOFF_INCREMENT_OPTION); if (backoffIncrement == null || backoffIncrement <= 0) backoffIncrement=1000L; this.backoffIncrement=backoffIncrement; Long maxBackoff=(Long)getOption(MAX_BACKOFF_OPTION); if (maxBackoff == null || maxBackoff <= 0) maxBackoff=30000L; this.maxBackoff=maxBackoff; if (scheduler == null) { scheduler=Executors.newSingleThreadScheduledExecutor(); shutdownScheduler=true; } }
Example 58
From project commons-io, under directory /src/test/java/org/apache/commons/io/monitor/.
Source file: FileAlterationMonitorTestCase.java

/** * Test using a thread factory. */ public void testThreadFactory(){ try { long interval=100; listener.clear(); FileAlterationMonitor monitor=new FileAlterationMonitor(interval,observer); monitor.setThreadFactory(Executors.defaultThreadFactory()); assertEquals("Interval",interval,monitor.getInterval()); monitor.start(); checkCollectionsEmpty("A"); File file2=touch(new File(testDir,"file2.java")); checkFile("Create",file2,listener.getCreatedFiles()); listener.clear(); checkCollectionsEmpty("B"); file2.delete(); checkFile("Delete",file2,listener.getDeletedFiles()); listener.clear(); monitor.stop(); } catch ( Exception e) { e.printStackTrace(); fail("Threw " + e); } }
Example 59
From project commons-j, under directory /src/main/java/nerds/antelax/commons/net/pubsub/.
Source file: PubSubClient.java

PubSubClient(final ChannelHandler incomingInterceptor,final Predicate<Object> incomingFilter,final ExecutorService service,final NetworkConnectionLifecycleCallback lifecycleCallback,final int retryDelay,final TimeUnit retryUnits,final Collection<InetSocketAddress> servers){ Preconditions.checkArgument((incomingInterceptor == null && incomingFilter == null) || (incomingInterceptor != null && incomingFilter != null)); Preconditions.checkNotNull(service,"ExecutorService cannot be null"); Preconditions.checkNotNull(servers,"Must give at least one server address to connect to"); clientHandler=new ClientMessageHandler(service); bossService=Executors.newCachedThreadPool(); workerService=Executors.newCachedThreadPool(); factory=new NioClientSocketChannelFactory(bossService,workerService); bootstrap=new ClientBootstrap(factory); reconnectHandler=new RoundRobinReconnectHandler(bootstrap,retryDelay,retryUnits,lifecycleCallback,servers); final UpstreamMessageFilteringHandler filteringHandler=incomingFilter != null ? new UpstreamMessageFilteringHandler(incomingFilter) : null; final UUID ourSourceID=UUID.randomUUID(); logger.info("New client created with ID: {}",ourSourceID); final ChannelDownstreamHandler uuidPopulatingHandler=new SimpleChannelDownstreamHandler(){ @Override public void writeRequested( final ChannelHandlerContext ctx, final MessageEvent e) throws Exception { final Object o=e.getMessage(); if (o instanceof Message) { final Message m=(Message)o; if (m.sourceID() == null || m.sourceID().equals(Message.NO_UUID)) m.sourceID(ourSourceID); } super.writeRequested(ctx,e); } } ; bootstrap.setPipelineFactory(new ChannelPipelineFactory(){ @Override public ChannelPipeline getPipeline(){ if (incomingInterceptor != null && filteringHandler != null) return Channels.pipeline(reconnectHandler,MessageCodec.decoder(),MessageCodec.encoder(),uuidPopulatingHandler,filteringHandler,incomingInterceptor,clientHandler); else return Channels.pipeline(reconnectHandler,MessageCodec.decoder(),MessageCodec.encoder(),uuidPopulatingHandler,clientHandler); } } ); bootstrap.setOption("tcpNoDelay",true); bootstrap.setOption("keepAlive",true); logger.trace("New pub/sub client created w/ intercepting handler[{}], incoming filter[{}], lifecycle callback[{}], retry delay[{} {}], servers[{}]",asArray(incomingInterceptor,incomingFilter,lifecycleCallback,retryDelay,retryUnits,servers)); }
Example 60
From project components, under directory /soap/src/test/java/org/switchyard/component/soap/.
Source file: SOAPGatewayTest.java

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

protected void runOneQueue(String queueName,BlockingQueue<Long> queue,int producerThread,int consumerThread) throws Exception { final CyclicBarrier cyclicBarrier=new CyclicBarrier(producerThread + consumerThread + 1); final Producer[] producers=new Producer[producerThread]; for (int i=0; i < producerThread; i++) { producers[i]=new Producer(queue,cyclicBarrier,ITERATIONS / producerThread); } Consumer[] consumers=new Consumer[consumerThread]; for (int i=0; i < consumerThread; i++) { consumers[i]=new Consumer(queue,cyclicBarrier,ITERATIONS / consumerThread); } final ExecutorService pool=Executors.newFixedThreadPool(producerThread + consumerThread); System.gc(); for (int i=0; i < producerThread; i++) { pool.execute(producers[i]); } for (int i=0; i < consumerThread; i++) { pool.execute(consumers[i]); } cyclicBarrier.await(); long start=System.currentTimeMillis(); cyclicBarrier.await(); long opsPerSecond=(ITERATIONS * 1000L) / (System.currentTimeMillis() - start); System.out.println("\tBlockingQueue=" + queueName + " "+ opsPerSecond+ " ops/sec"); }
Example 62
From project CouchbaseMock, under directory /src/main/java/org/couchbase/mock/.
Source file: CouchbaseMock.java

public void start(){ nodeThreads=new ArrayList<Thread>(); for ( String s : getBuckets().keySet()) { Bucket bucket=getBuckets().get(s); bucket.start(nodeThreads); } try { boolean busy=true; do { if (port == 0) { ServerSocket server=new ServerSocket(0); port=server.getLocalPort(); server.close(); } try { httpServer=HttpServer.create(new InetSocketAddress(port),10); } catch ( BindException ex) { System.err.println("Looks like port " + port + " busy, lets try another one"); } busy=false; } while (busy); httpServer.createContext("/pools",new PoolsHandler(this)).setAuthenticator(authenticator); httpServer.setExecutor(Executors.newCachedThreadPool()); httpServer.start(); startupLatch.countDown(); } catch ( IOException ex) { Logger.getLogger(CouchbaseMock.class.getName()).log(Level.SEVERE,null,ex); System.exit(-1); } }
Example 63
From project Countandra, under directory /src/org/countandra/netty/.
Source file: NettyUtils.java

public static synchronized void startupNettyServer(int httpPort){ if (nettyStarted) return; nettyStarted=true; ServerBootstrap server=new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool())); server.setPipelineFactory(new CountandraHttpServerPipelineFactory()); server.bind(new InetSocketAddress(httpPort)); }
Example 64
From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/identity_server/.
Source file: IdentityServer.java

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

public void testReadLine() throws Exception { BaseProcessFactory factory=new BaseProcessFactory(){ @Override public BaseProcess create( String request){ return new BaseProcess(request){ @Override public void process( String request, ShellProcessContext processContext) throws IOException { String a=readLine("bar",true); processContext.write(new Text(a)); processContext.end(ShellResponse.ok()); } } ; } } ; Shell shell=new BaseShell(factory); Shell asyncShell=new AsyncShell(Executors.newSingleThreadExecutor(),shell); BaseProcessContext ctx=BaseProcessContext.create(asyncShell,"foo"); ctx.addLineInput("juu"); ctx.execute(); ShellResponse resp=ctx.getResponse(); assertInstance(ShellResponse.Ok.class,resp); assertEquals("barjuu",ctx.getOutput()); ctx.assertNoInput(); }
Example 66
From project curator, under directory /curator-examples/src/main/java/locking/.
Source file: LockingExample.java

public static void main(String[] args) throws Exception { final FakeLimitedResource resource=new FakeLimitedResource(); ExecutorService service=Executors.newFixedThreadPool(QTY); final TestingServer server=new TestingServer(); try { for (int i=0; i < QTY; ++i) { final int index=i; Callable<Void> task=new Callable<Void>(){ @Override public Void call() throws Exception { CuratorFramework client=CuratorFrameworkFactory.newClient(server.getConnectString(),new ExponentialBackoffRetry(1000,3)); try { client.start(); ExampleClientThatLocks example=new ExampleClientThatLocks(client,PATH,resource,"Client " + index); for (int j=0; j < REPETITIONS; ++j) { example.doWork(10,TimeUnit.SECONDS); } } catch ( Throwable e) { e.printStackTrace(); } finally { Closeables.closeQuietly(client); } return null; } } ; service.submit(task); } service.shutdown(); service.awaitTermination(10,TimeUnit.MINUTES); } finally { Closeables.closeQuietly(server); } }
Example 67
From project cxf-dosgi, under directory /samples/discovery/client/src/main/java/org/apache/cxf/dosgi/samples/discovery/consumer/.
Source file: Activator.java

public void start(BundleContext bc) throws Exception { tracker=new ServiceTracker(bc,DisplayService.class.getName(),null){ public Object addingService( ServiceReference reference){ Object svc=super.addingService(reference); if (svc instanceof DisplayService) { DisplayService d=(DisplayService)svc; System.out.println("Adding display: " + d.getID() + " ("+ d+ ")"); displays.put(d,d.getID()); } return svc; } public void removedService( ServiceReference reference, Object service){ String value=displays.remove(service); System.out.println("Removed display: " + value); super.removedService(reference,service); } } ; tracker.open(); scheduler=Executors.newScheduledThreadPool(1); Runnable printer=new Runnable(){ int counter=0; public void run(){ counter++; String text="some text " + counter; System.out.println("Sending text to displays: " + text); for (Iterator<Entry<DisplayService,String>> it=displays.entrySet().iterator(); it.hasNext(); ) { Entry<DisplayService,String> entry=it.next(); try { entry.getKey().displayText(text); } catch ( Throwable th) { System.out.println("Could not send message to display: " + entry.getValue()); } } } } ; handle=scheduler.scheduleAtFixedRate(printer,5,5,TimeUnit.SECONDS); }
Example 68
From project cytoscape-plugins, under directory /org.openbel.cytoscape.navigator/src/org/openbel/cytoscape/navigator/task/.
Source file: AbstractSearchKamTask.java

private List<KamNode> searchKAMNodes(){ ExecutorService e=Executors.newSingleThreadExecutor(); Future<List<KamNode>> future=e.submit(buildCallable()); while (!(future.isDone() || future.isCancelled()) && !e.isShutdown()) { try { if (halt) { e.shutdownNow(); future.cancel(true); } Thread.sleep(100); } catch ( InterruptedException ex) { halt=true; } } if (future.isCancelled()) { return null; } try { return future.get(); } catch ( InterruptedException ex) { log.warn("Error searching kam nodes",ex); return null; } catch ( ExecutionException ex) { log.warn("Error searching kam nodes",ex); return null; } }
Example 69
From project datasalt-utils, under directory /src/contrib/java/org/apache/solr/common/cloud/.
Source file: DefaultConnectionStrategy.java

@Override public void reconnect(final String serverAddress,final int zkClientTimeout,final Watcher watcher,final ZkUpdate updater) throws IOException { log.info("Starting reconnect to ZooKeeper attempts ..."); executor=Executors.newScheduledThreadPool(1); executor.schedule(new Runnable(){ private int delay=1000; public void run(){ log.info("Attempting the connect..."); boolean connected=false; try { updater.update(new SolrZooKeeper(serverAddress,zkClientTimeout,watcher)); log.info("Reconnected to ZooKeeper"); connected=true; } catch ( Exception e) { log.error("",e); log.info("Reconnect to ZooKeeper failed"); } if (connected) { executor.shutdownNow(); } else { if (delay < 240000) { delay=delay * 2; } executor.schedule(this,delay,TimeUnit.MILLISECONDS); } } } ,1000,TimeUnit.MILLISECONDS); }
Example 70
From project dcm4che, under directory /dcm4che-tool/dcm4che-tool-dcmqrscp/src/main/java/org/dcm4che/tool/dcmqrscp/.
Source file: DcmQRSCP.java

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 71
From project Dempsy, under directory /lib-dempsyimpl/src/main/java/com/nokia/dempsy/container/.
Source file: MpContainer.java

public void startEvictionThread(long evictionFrequency,TimeUnit timeUnit){ if (0 == evictionFrequency || null == timeUnit) { logger.warn("Eviction Thread cannot start with zero frequency or null TimeUnit {} {}",evictionFrequency,timeUnit); return; } if (prototype != null && prototype.isEvictableSupported()) { evictionScheduler=Executors.newSingleThreadScheduledExecutor(); evictionScheduler.scheduleWithFixedDelay(new Runnable(){ public void run(){ evict(); } } ,evictionFrequency,evictionFrequency,timeUnit); } }
Example 72
From project DigitbooksExamples, under directory /DigitbooksExamples/src/fr/digitbooks/android/examples/chapitre06/.
Source file: AsynchronousListActivity.java

private void sendFetchImageMessage(ImageView view){ final int imageId=(Integer)view.getTag(); ImageFetcher imageFetcher=new ImageFetcher(view,imageId); if (mPoolExecutors == null) { mPoolExecutors=Executors.newFixedThreadPool(NUMBER_OF_THREADS); } mPoolExecutors.execute(imageFetcher); }
Example 73
From project DirectMemory, under directory /server/directmemory-server-client/src/main/java/org/apache/directmemory/server/client/providers/httpclient/.
Source file: HttpClientDirectMemoryHttpClient.java

@Override public Future<DirectMemoryResponse> asyncPut(final DirectMemoryRequest request) throws DirectMemoryException { return Executors.newSingleThreadExecutor().submit(new Callable<DirectMemoryResponse>(){ @Override public DirectMemoryResponse call() throws Exception { return put(request); } } ); }
Example 74
/** */ public JmmDNSImpl(){ super(); _networkListeners=Collections.synchronizedSet(new HashSet<NetworkTopologyListener>()); _knownMDNS=new ConcurrentHashMap<InetAddress,JmDNS>(); _services=new ConcurrentHashMap<String,ServiceInfo>(20); _ListenerExecutor=Executors.newSingleThreadExecutor(); _jmDNSExecutor=Executors.newCachedThreadPool(); _timer=new Timer("Multihommed mDNS.Timer",true); (new NetworkChecker(this,NetworkTopologyDiscovery.Factory.getInstance())).start(_timer); }
Example 75
From project dozer, under directory /core/src/test/java/org/dozer/.
Source file: DozerBeanMapperTest.java

@Test public void shouldInitializeOnce() throws Exception { final CallTrackingMapper mapper=new CallTrackingMapper(); ExecutorService executorService=Executors.newFixedThreadPool(10); final CountDownLatch latch=new CountDownLatch(THREAD_COUNT); HashSet<Callable<Object>> callables=new HashSet<Callable<Object>>(); for (int i=0; i < THREAD_COUNT; i++) { callables.add(new Callable<Object>(){ public Object call() throws Exception { latch.countDown(); latch.await(); Mapper processor=mapper.getMappingProcessor(); assertNotNull(processor); return null; } } ); } executorService.invokeAll(callables); assertEquals(1,mapper.getCalls()); assertTrue(exceptions.isEmpty()); }
Example 76
From project dragon, under directory /hadoop-dragon-core/src/main/java/org/apache/hadoop/realtime/fs/.
Source file: DefaultWatchService.java

DefaultWatchService(){ scheduledExecutor=Executors.newSingleThreadScheduledExecutor(new ThreadFactory(){ @Override public Thread newThread( Runnable r){ Thread t=new Thread(r); t.setDaemon(true); return t; } } ); }
Example 77
From project droid-fu, under directory /src/main/java/com/github/droidfu/imageloader/.
Source file: ImageLoader.java

/** * This method must be called before any other method is invoked on this class. Please note that when using ImageLoader as part of {@link WebImageView} or {@link WebGalleryAdapter}, then there is no need to call this method, since those classes will already do that for you. This method is idempotent. You may call it multiple times without any side effects. * @param context the current context */ public static synchronized void initialize(Context context){ if (executor == null) { executor=(ThreadPoolExecutor)Executors.newFixedThreadPool(DEFAULT_POOL_SIZE); } if (imageCache == null) { imageCache=new ImageCache(25,expirationInMinutes,DEFAULT_POOL_SIZE); imageCache.enableDiskCache(context,ImageCache.DISK_CACHE_SDCARD); } }
Example 78
From project drools-mas, under directory /examples/drools-mas-emergency-agent-client/src/test/java/org/drools/mas/.
Source file: EmergencyAgentServiceRemoteTest.java

@Test public void multiThreadTest() throws InterruptedException { final SyncDialogueHelper helper=new SyncDialogueHelper(endpoint); final int EMERGENCY_COUNT=45; final int THREAD_COUNT=10; Collection<Callable<Void>> tasks=new ArrayList<Callable<Void>>(); for (int i=0; i < EMERGENCY_COUNT; i++) { final Emergency emergency=new Emergency("Emergency" + i,new Date(),"Fire" + i,10); tasks.add(new Callable<Void>(){ public Void call() throws Exception { helper.invokeInform("me","you",emergency); helper.invokeRequest("coordinateEmergency",new LinkedHashMap<String,Object>()); helper.getReturn(false); return null; } } ); } ExecutorService executorService=Executors.newFixedThreadPool(THREAD_COUNT); List<Future<Void>> futures=executorService.invokeAll(tasks); assertEquals(futures.size(),EMERGENCY_COUNT); }
Example 79
From project drools-planner, under directory /drools-planner-benchmark/src/main/java/org/drools/planner/benchmark/core/.
Source file: DefaultPlannerBenchmark.java

public void benchmarkingStarted(){ startingSystemTimeMillis=System.currentTimeMillis(); startingTimestamp=new Date(); if (solverBenchmarkList == null || solverBenchmarkList.isEmpty()) { throw new IllegalArgumentException("The solverBenchmarkList (" + solverBenchmarkList + ") cannot be empty."); } initBenchmarkDirectoryAndSubdirs(); for ( SolverBenchmark solverBenchmark : solverBenchmarkList) { solverBenchmark.benchmarkingStarted(); } for ( ProblemBenchmark problemBenchmark : unifiedProblemBenchmarkList) { problemBenchmark.benchmarkingStarted(); } executorService=Executors.newFixedThreadPool(parallelBenchmarkCount); failureCount=0; firstFailureSingleBenchmark=null; averageProblemScale=null; favoriteSolverBenchmark=null; benchmarkTimeMillisSpend=-1L; logger.info("Benchmarking started: solverBenchmarkList size ({}), parallelBenchmarkCount ({}).",solverBenchmarkList.size(),parallelBenchmarkCount); }
Example 80
From project eik, under directory /plugins/info.evanchik.eclipse.karaf.workbench/src/main/java/info/evanchik/eclipse/karaf/workbench/internal/.
Source file: KarafMBeanProvider.java

/** * Constructs an {@link MBeanProvider} that opens a connection to a{@link MBeanServerConnection} * @param jmxServiceDescriptor the {@link JMXServiceDescriptor} which was used to make theconnection to the JMX end point * @param connector the {@link JMXConnector} that represents the JMX connection * @throws IOException if the connection to the MBean Server cannot be made */ public KarafMBeanProvider(final JMXServiceDescriptor jmxServiceDescriptor,final JMXConnector connector) throws IOException { this.connector=connector; this.jmxServiceDescriptor=jmxServiceDescriptor; this.mbeanServer=connector.getMBeanServerConnection(); this.connectionHandler=Executors.newSingleThreadExecutor(); this.connector.addConnectionNotificationListener(this,null,null); }
Example 81
private GeneralThreadPool(){ if (Config.THREAD_P_TYPE_GENERAL == 1) { _executor=Executors.newFixedThreadPool(Config.THREAD_P_SIZE_GENERAL); } else if (Config.THREAD_P_TYPE_GENERAL == 2) { _executor=Executors.newCachedThreadPool(); } else { _executor=null; } _scheduler=Executors.newScheduledThreadPool(SCHEDULED_CORE_POOL_SIZE,new PriorityThreadFactory("GerenalSTPool",Thread.NORM_PRIORITY)); _pcScheduler=Executors.newScheduledThreadPool(_pcSchedulerPoolSize,new PriorityThreadFactory("PcMonitorSTPool",Thread.NORM_PRIORITY)); }
Example 82
From project encog-java-core, under directory /src/main/java/org/encog/util/concurrency/.
Source file: EngineConcurrency.java

/** * Construct a concurrency object. */ public EngineConcurrency(){ Runtime runtime=Runtime.getRuntime(); int threads=runtime.availableProcessors(); if (threads > 1) threads++; this.executor=Executors.newFixedThreadPool(threads); }
Example 83
From project enterprise, under directory /com/src/main/java/org/neo4j/com/.
Source file: Server.java

public Server(T requestTarget,final int port,StringLogger logger,int frameLength,byte applicationProtocolVersion,int maxNumberOfConcurrentTransactions,int oldChannelThreshold,TxChecksumVerifier txVerifier,int chunkSize){ assertChunkSizeIsWithinFrameSize(chunkSize,frameLength); this.requestTarget=requestTarget; this.frameLength=frameLength; this.chunkSize=chunkSize; this.applicationProtocolVersion=applicationProtocolVersion; this.msgLog=logger; this.txVerifier=txVerifier; this.oldChannelThresholdMillis=oldChannelThreshold * 1000; executor=Executors.newCachedThreadPool(); targetCallExecutor=Executors.newCachedThreadPool(new NamedThreadFactory(getClass().getSimpleName() + ":" + port)); unfinishedTransactionExecutor=Executors.newScheduledThreadPool(2); channelFactory=new NioServerSocketChannelFactory(executor,executor,maxNumberOfConcurrentTransactions); silentChannelExecutor=Executors.newSingleThreadScheduledExecutor(); silentChannelExecutor.scheduleWithFixedDelay(silentChannelFinisher(),5,5,TimeUnit.SECONDS); bootstrap=new ServerBootstrap(channelFactory); bootstrap.setPipelineFactory(this); Channel channel; try { channel=bootstrap.bind(new InetSocketAddress(port)); } catch ( ChannelException e) { msgLog.logMessage("Failed to bind server to port " + port,e); executor.shutdown(); throw e; } channelGroup=new DefaultChannelGroup(); channelGroup.add(channel); msgLog.logMessage(getClass().getSimpleName() + " communication server started and bound to " + port,true); }
Example 84
From project event-collector, under directory /event-collector/src/main/java/com/proofpoint/event/collector/.
Source file: BatchProcessor.java

public BatchProcessor(String name,BatchHandler<T> handler,int maxBatchSize,int queueSize){ Preconditions.checkNotNull(name,"name is null"); Preconditions.checkNotNull(handler,"handler is null"); Preconditions.checkArgument(queueSize > 0,"queue size needs to be a positive integer"); Preconditions.checkArgument(maxBatchSize > 0,"max batch size needs to be a positive integer"); this.handler=handler; this.maxBatchSize=maxBatchSize; this.queue=new ArrayBlockingQueue<T>(queueSize); this.executor=Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat(format("batch-processor-%s",name)).build()); }
Example 85
From project example-projects, under directory /exo-jcr-example/src/test/java/org/example/.
Source file: HelloBeanTest.java

@Test public void testSayHello_String(){ ExecutorService executor1=Executors.newSingleThreadExecutor(); ExecutorService executor2=Executors.newSingleThreadExecutor(); for (int i=0; i < 1; i++) { executor1.execute(new HelloTask("root")); executor2.execute(new HelloTask("john")); } executor1.shutdown(); executor2.shutdown(); try { executor1.awaitTermination(30,TimeUnit.SECONDS); executor2.awaitTermination(30,TimeUnit.SECONDS); } catch ( InterruptedException e) { e.printStackTrace(); } assertTrue(true); }
Example 86
From project fast-http, under directory /src/main/java/org/neo4j/smack/pipeline/.
Source file: RingBufferWorkPipeline.java

public void start(){ if (handlers.isEmpty()) throw new IllegalStateException("No Handlers configured on Pipeline"); final int numEventProcessors=handlers.size(); workers=Executors.newFixedThreadPool(numEventProcessors,new DaemonThreadFactory(nameForThreads)); ringBuffer=new RingBuffer<E>(eventFactory,new MultiThreadedClaimStrategy(bufferSize),new BusySpinWaitStrategy()); WorkProcessor<E> processor=null; for ( WorkHandler<E> handler : handlers) { processor=scheduleEventProcessor(processor,handler); processors.add(processor); } ringBuffer.setGatingSequences(processor.getSequence()); }
Example 87
From project filemanager, under directory /FileManager/src/org/openintents/filemanager/.
Source file: ThumbnailLoader.java

/** * Used for loading and decoding thumbnails from files. * @author PhilipHayes * @param context Current application context. */ public ThumbnailLoader(Context context){ mContext=context; purger=new Runnable(){ @Override public void run(){ Log.d(TAG,"Purge Timer hit; Clearing Caches."); clearCaches(); } } ; purgeHandler=new Handler(); mExecutor=Executors.newFixedThreadPool(POOL_SIZE); mBlacklist=new ArrayList<String>(); mSoftBitmapCache=new ConcurrentHashMap<String,SoftReference<Bitmap>>(MAX_CACHE_CAPACITY / 2); mHardBitmapCache=new LinkedHashMap<String,Bitmap>(MAX_CACHE_CAPACITY / 2,0.75f,true){ /** */ private static final long serialVersionUID=1347795807259717646L; @Override protected boolean removeEldestEntry( LinkedHashMap.Entry<String,Bitmap> eldest){ if (size() > MAX_CACHE_CAPACITY) { mSoftBitmapCache.put(eldest.getKey(),new SoftReference<Bitmap>(eldest.getValue())); return true; } else { return false; } } } ; }
Example 88
From project finch, under directory /src/com/bourke/finch/adapters/lazylist/.
Source file: ImageLoader.java

public ImageLoader(Activity a){ mActivity=a; mContext=a.getApplicationContext(); mFileCache=new FileCache(mContext); executorService=Executors.newFixedThreadPool(5); }
Example 89
From project fire-samples, under directory /cache-demo/src/main/java/demo/vmware/commands/.
Source file: CommandGetAllRegions.java

/** * Retrieve the contents for all regions, one region per task executor */ @Override public CommandResult run(ConfigurableApplicationContext mainContext,List<String> parameters){ Map<String,GemfireTemplate> allRegionTemplates=CommandRegionUtils.getAllGemfireTemplates(mainContext); ExecutorService taskExecutor=Executors.newFixedThreadPool(allRegionTemplates.size()); Collection tasks=new ArrayList<RegionFetcher>(); CommandTimer timer=new CommandTimer(); for ( String key : allRegionTemplates.keySet()) { GemfireTemplate oneTemplate=allRegionTemplates.get(key); if (parallelFetch) { tasks.add(new RegionFetcher(oneTemplate.getRegion().getName(),0,oneTemplate)); } else { fetchOneRegion(oneTemplate.getRegion().getName(),5,oneTemplate); } } if (parallelFetch) { try { List<Future<?>> futures=taskExecutor.invokeAll(tasks); taskExecutor.shutdown(); LOG.info("Fetched " + futures.size() + " regions in threads"); } catch ( InterruptedException e) { e.printStackTrace(); } } timer.stop(); return new CommandResult(null,"Loading all regions took " + timer.getTimeDiffInSeconds() + " seconds"); }
Example 90
From project flazr, under directory /src/main/java/com/flazr/rtmp/client/.
Source file: RtmpClient.java

public static void connect(final ClientOptions options){ final ClientBootstrap bootstrap=getBootstrap(Executors.newCachedThreadPool(),options); final ChannelFuture future=bootstrap.connect(new InetSocketAddress(options.getHost(),options.getPort())); future.awaitUninterruptibly(); if (!future.isSuccess()) { logger.error("error creating client connection: {}",future.getCause().getMessage()); } future.getChannel().getCloseFuture().awaitUninterruptibly(); bootstrap.getFactory().releaseExternalResources(); }