@Test public void testSagaTypeTakenIntoConsiderationWhenCheckingForSagasInCreation() throws InterruptedException { manager = new AnnotatedSagaManager( sagaRepository, new SimpleEventBus(), MyOtherTestSaga.class, MyTestSaga.class); ExecutorService executorService = Executors.newFixedThreadPool(8); for (int i = 0; i < 100; i++) { executorService.execute( new HandleEventTask(GenericEventMessage.asEventMessage(new StartingEvent("id" + i)))); executorService.execute( new HandleEventTask( GenericEventMessage.asEventMessage(new OtherStartingEvent("id" + i)))); } executorService.shutdown(); executorService.awaitTermination(10, TimeUnit.SECONDS); for (int i = 0; i < 100; i++) { assertEquals( "MyTestSaga missing for id" + i, 1, repositoryContents("id" + i, MyTestSaga.class).size()); assertEquals( "MyOtherTestSaga missing for id" + i, 1, repositoryContents("id" + i, MyOtherTestSaga.class).size()); } }
@Test @PresetData(PresetData.DataSet.NO_ANONYMOUS_READACCESS) public void testFailedRunnableResetsContext() throws Exception { Runnable r = new Runnable() { public void run() { SecurityContextHolder.setContext(nullContext); throw new RuntimeException("Simulate a failure"); } }; SecurityContextHolder.setContext(systemContext); try { wrappedService.execute(r); } catch (AssertionError expectedException) { // Assert the current context is once again ACL.SYSTEM assertEquals(systemContext, SecurityContextHolder.getContext()); } SecurityContextHolder.setContext(userContext); try { wrappedService.execute(r); } catch (AssertionError expectedException) { // Assert the current context is once again the userContext assertEquals(userContext, SecurityContextHolder.getContext()); } }
private void startSource() throws JMSException { // start the source connection sourceConn.start(); started = true; if (maxBatchTime != -1) { if (JMSBridgeImpl.trace) { HornetQJMSServerLogger.LOGGER.trace("Starting time checker thread"); } timeChecker = new BatchTimeChecker(); executor.execute(timeChecker); batchExpiryTime = System.currentTimeMillis() + maxBatchTime; if (JMSBridgeImpl.trace) { HornetQJMSServerLogger.LOGGER.trace("Started time checker thread"); } } executor.execute(new SourceReceiver()); if (JMSBridgeImpl.trace) { HornetQJMSServerLogger.LOGGER.trace("Started " + this); } }
/** * @author ldm @Description: 抓取企业工商类信息 * @param @param name:企业名称 或 统一社会信用代码或注册号 * @return void * @throws * @date 2016年2月4日 上午11:59:22 */ public static void catchData(String name) { String[] re = queryCom(name); // final String nbxh = re[0]; // final String qylx = re[1]; final String nbxh = "20e38b8b4d194cc8014d1e12e97f6374"; final String qylx = "8173D03BDAA53D4E34282E704327D289"; final Long qyId = spider_jbxx(nbxh, qylx); System.out.println(qyId); ExecutorService executorService = Executors.newFixedThreadPool(4); executorService.execute( new Runnable() { public void run() { spider_jyyc(nbxh, qylx, qyId); } }); executorService.execute( new Runnable() { public void run() { spider_xzcf(nbxh, qylx, qyId); } }); executorService.execute( new Runnable() { public void run() { spider_yzwf(nbxh, qylx, qyId); } }); executorService.execute( new Runnable() { public void run() { spider_cccj(nbxh, qylx, qyId); } }); }
public static void main(String[] args) throws Exception { ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < 5; i++) exec.execute(new Task()); exec.execute(new Task2()); Timer timer = new Timer(); timer.scheduleAtFixedRate( new TimerTask() { boolean prod = true; public void run() { if (prod) { System.out.print("\nnotify() "); Task.blocker.prod(); prod = false; } else { System.out.print("\nnotifyAll() "); Task.blocker.prodAll(); prod = true; } } }, 400, 400); // Run every .4 second TimeUnit.SECONDS.sleep(5); // Run for a while... timer.cancel(); System.out.println("\nTimer canceled"); TimeUnit.MILLISECONDS.sleep(500); System.out.print("Task2.blocker.prodAll() "); Task2.blocker.prodAll(); TimeUnit.MILLISECONDS.sleep(500); System.out.println("\nShutting down"); exec.shutdownNow(); // Interrupt all tasks }
public void execute() { executorService.execute(task); executorService.execute(task); executorService.execute(task); executorService.shutdown(); System.out.println("---"); }
@Test public void testRedisToNats() throws Exception { System.clearProperty(RedisPubSubPlugin.CONFIG_URL); Connector c = new Connector(); ExecutorService executor = Executors.newFixedThreadPool(6); RedisPublisher rp = new RedisPublisher("rp", "Export_NATS", 5); NatsSubscriber ns = new NatsSubscriber("ns", "Import.Redis", 5); // start the connector executor.execute(c); // start the subsciber app executor.execute(ns); // wait for subscriber to be ready. ns.waitUntilReady(); // let the connector start Thread.sleep(2000); // start the publisher executor.execute(rp); // wait for the subscriber to complete. ns.waitForCompletion(); Assert.assertTrue("Invalid count", ns.getMessageCount() == 5); c.shutdown(); }
@Test public void testDeadLockWithNotify() throws Throwable { int size = 10; final ExecutorService es = new ThreadPoolExecutor( size * 2, Integer.MAX_VALUE, 30, TimeUnit.SECONDS, new SynchronousQueue()); ((ThreadPoolExecutor) es).prestartAllCoreThreads(); for (int i = 0; i < size; i++) es.execute(new WriteSpaceWithNotifyTask("WriteTask1-" + i, sp1, sp2)); for (int i = 0; i < size; i++) es.execute(new WriteSpaceWithNotifyTask("WriteTask2-" + i, sp2, sp1)); long stamp = System.currentTimeMillis(); while (((ThreadPoolExecutor) es).getActiveCount() > 0) { if (System.currentTimeMillis() - stamp < 10000) { ISOUtil.sleep(100); continue; } es.shutdownNow(); fail("Probably death-lock detected"); return; } printAvg(t1, "Avg. write: "); // es.shutdown(); es.shutdownNow(); es.awaitTermination(5, TimeUnit.SECONDS); }
/** {@inheritDoc} */ @Override public void onApplicationEvent(AgentMappingsUpdateEvent event) { Map<Long, AgentCacheEntry> agentCacheMap = nextGenInstrumentationManager.getAgentCacheMap(); // iterate all caches for (AgentCacheEntry agentCacheEntry : agentCacheMap.values()) { ConfigurationHolder configurationHolder = agentCacheEntry.getConfigurationHolder(); Environment cachedEnvironment = configurationHolder.getEnvironment(); PlatformIdent platformIdent = platformIdentDao.load(agentCacheEntry.getId()); try { // see what 's the new environment for the agent Environment environment = configurationResolver.getEnvironmentForAgent( platformIdent.getDefinedIPs(), platformIdent.getAgentName()); // fire job only if we have new environment or we were not bounded to any // environment if ((null == cachedEnvironment) || !ObjectUtils.equals(cachedEnvironment.getId(), environment.getId())) { EnvironmentMappingUpdateJob mappingUpdateJob = mappingUpdateJobFactory.getObject(); mappingUpdateJob.setEnvironment(environment); mappingUpdateJob.setAgentCacheEntry(agentCacheEntry); executor.execute(mappingUpdateJob); } } catch (BusinessException e) { // if we have exception by resolving new environment run job with no new // environment EnvironmentMappingUpdateJob mappingUpdateJob = mappingUpdateJobFactory.getObject(); mappingUpdateJob.setAgentCacheEntry(agentCacheEntry); executor.execute(mappingUpdateJob); } } }
protected synchronized void initializeQueue(String host, String queueName, Integer port) throws InterruptedException { final String bind = "tcp://" + host + ":" + port; _log.warn("binding to " + bind); if (_context == null) { _context = ZMQ.context(1); } if (_socket != null) { _executorService.shutdownNow(); _heartbeatService.shutdownNow(); Thread.sleep(1 * 1000); _log.warn("_executorService.isTerminated=" + _executorService.isTerminated()); _socket.close(); _executorService = Executors.newFixedThreadPool(1); _heartbeatService = Executors.newFixedThreadPool(1); } _socket = _context.socket(ZMQ.PUB); _socket.connect(bind); _executorService.execute(new SendThread(_socket, queueName)); _heartbeatService.execute(new HeartbeatThread(HEARTBEAT_INTERVAL)); _log.debug("Inference output queue is sending to " + bind); _initialized = true; }
public static void main(String[] args) { // 创建一个可重用固定线程数的线程池 ExecutorService pool = Executors.newFixedThreadPool(2); // 创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口 Thread t1 = new MyThread(); Thread t2 = new MyThread(); Thread t3 = new MyThread(); Thread t4 = new MyThread(); Thread t5 = new MyThread(); // 将线程放入池中进行执行 pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); // 关闭线程池 pool.shutdown(); }
public static void main(String[] args) { final BlockingQueue<Character> bq; bq = new ArrayBlockingQueue<Character>(26); final ExecutorService executor = Executors.newFixedThreadPool(2); Runnable producer = () -> { for (char ch = 'A'; ch <= 'Z'; ch++) { try { bq.put(ch); System.out.printf("%c produced by " + "producer.%n", ch); } catch (InterruptedException ie) { } } }; executor.execute(producer); Runnable consumer = () -> { char ch = '\0'; do { try { ch = bq.take(); System.out.printf("%c consumed by " + "consumer.%n", ch); } catch (InterruptedException ie) { } } while (ch != 'Z'); executor.shutdownNow(); }; executor.execute(consumer); }
public static void main(String[] args) throws InterruptedException { Car car = new Car(); ExecutorService exec = Executors.newCachedThreadPool(); exec.execute(new WaxOn(car)); exec.execute(new WaxOff(car)); TimeUnit.SECONDS.sleep(1); exec.shutdownNow(); }
public static void main(String[] args) throws Exception { Car car = new Car(); ExecutorService exec = Executors.newCachedThreadPool(); exec.execute(new WaxOff(car)); exec.execute(new WaxOn(car)); TimeUnit.SECONDS.sleep(5); // Run for a while... exec.shutdownNow(); // Interrupt all tasks }
@Test public void testNatsSubjectFanIntoRedis() throws Exception { int count = 5; String config = "{" + "\"nats_to_redis_map\" : [" + "{" + "\"subject\" : \"Export.Redis1\"," + "\"channel\" : \"Import_NATS\"" + "}," + "{" + "\"subject\" : \"Export.Redis2\"," + "\"channel\" : \"Import_NATS\"" + "}," + "{" + "\"subject\" : \"Export.Redis3\"," + "\"channel\" : \"Import_NATS\"" + "}" + "]" + "}"; System.setProperty(RedisPubSubPlugin.CONFIG_URL, generateContentFile(config)); Connector c = new Connector(); ExecutorService executor = Executors.newFixedThreadPool(10); NatsPublisher np1 = new NatsPublisher("np1", "Export.Redis1", count); NatsPublisher np2 = new NatsPublisher("np2", "Export.Redis2", count); NatsPublisher np3 = new NatsPublisher("np3", "Export.Redis3", count); RedisSubscriber rs1 = new RedisSubscriber("rs1", "Import_NATS", count * 3); // start the subsciber apps executor.execute(rs1); // wait for subscribers to be ready. rs1.waitUntilReady(); // start the connector executor.execute(c); Thread.sleep(1000); ; // start the publishers executor.execute(np1); executor.execute(np2); executor.execute(np3); // wait for the subscribers to complete. rs1.waitForCompletion(); Assert.assertTrue("Invalid count", rs1.getMessageCount() == (count * 3)); c.shutdown(); }
/** * Get notified of change of job status. Executed in context of uploader thread * * @param jobId the id of the job * @param status the status of the job */ public void setUploadStatus(String jobId, Status status) { UploadJob uj = jobs.get(jobId); if (uj == null) { s_logger.warn("setUploadStatus for jobId: " + jobId + ", status=" + status + " no job found"); return; } TemplateUploader tu = uj.getTemplateUploader(); s_logger.warn("Upload Completion for jobId: " + jobId + ", status=" + status); s_logger.warn( "UploadedBytes=" + tu.getUploadedBytes() + ", error=" + tu.getUploadError() + ", pct=" + tu.getUploadPercent()); switch (status) { case ABORTED: case NOT_STARTED: case UNRECOVERABLE_ERROR: // Delete the entity only if its a volume. TO DO - find a better way of finding it a volume. if (uj.getTemplateUploader().getUploadLocalPath().indexOf("volume") > -1) { uj.cleanup(); } break; case UNKNOWN: return; case IN_PROGRESS: s_logger.info("Resuming jobId: " + jobId + ", status=" + status); tu.setResume(true); threadPool.execute(tu); break; case RECOVERABLE_ERROR: threadPool.execute(tu); break; case UPLOAD_FINISHED: tu.setUploadError("Upload success, starting install "); String result = postUpload(jobId); if (result != null) { s_logger.error("Failed post upload script: " + result); tu.setStatus(Status.UNRECOVERABLE_ERROR); tu.setUploadError("Failed post upload script: " + result); } else { s_logger.warn( "Upload completed successfully at " + new SimpleDateFormat().format(new Date())); tu.setStatus(Status.POST_UPLOAD_FINISHED); tu.setUploadError( "Upload completed successfully at " + new SimpleDateFormat().format(new Date())); } // Delete the entity only if its a volume. TO DO - find a better way of finding it a volume. if (uj.getTemplateUploader().getUploadLocalPath().indexOf("volume") > -1) { uj.cleanup(); } break; default: break; } }
public void addMigration(KeyExtent tablet, Runnable migrationHandler) { if (tablet.isRootTablet()) { migrationHandler.run(); } else if (tablet.isMeta()) { defaultMigrationPool.execute(migrationHandler); } else { migrationPool.execute(migrationHandler); } }
public static void main(String[] args) { // TODO Auto-generated method stub ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < 5; i++) { exec.execute(new SimplePriorities(Thread.MIN_PRIORITY)); } exec.execute(new SimplePriorities(Thread.MAX_PRIORITY)); exec.shutdown(); }
public static void main(String[] args) { CountDownLatch latch = new CountDownLatch(3); ExecutorService executor = Executors.newCachedThreadPool(); executor.execute(new worker("yan", latch)); executor.execute(new worker("luo", latch)); executor.execute(new worker("hong", latch)); executor.execute(new Boss(latch)); executor.shutdown(); }
public void executeReadAhead(KeyExtent tablet, Runnable task) { if (tablet.isRootTablet()) { task.run(); } else if (tablet.isMeta()) { defaultReadAheadThreadPool.execute(task); } else { readAheadThreadPool.execute(task); } }
@Test public void testPollLong() throws Exception { TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2); final HazelcastInstance[] instances = factory.newInstances(); final HazelcastInstance h1 = instances[0]; final HazelcastInstance h2 = instances[1]; final IQueue q1 = h1.getQueue("default"); final IQueue q2 = h2.getQueue("default"); final CountDownLatch offerLatch = new CountDownLatch(2 * 100); Thread.sleep(1000); new Thread( new Runnable() { public void run() { for (int i = 0; i < 100; i++) { if (q1.offer("item")) { offerLatch.countDown(); } if (q2.offer("item")) { offerLatch.countDown(); } } } }) .start(); assertOpenEventually(offerLatch); final ExecutorService es = Executors.newFixedThreadPool(50); final CountDownLatch latch = new CountDownLatch(200); Thread.sleep(3000); for (int i = 0; i < 100; i++) { es.execute( new Runnable() { public void run() { try { if ("item".equals(q1.poll(5, TimeUnit.SECONDS))) { latch.countDown(); } } catch (InterruptedException e) { e.printStackTrace(); } } }); es.execute( new Runnable() { public void run() { try { if ("item".equals(q2.poll(5, TimeUnit.SECONDS))) { latch.countDown(); } } catch (InterruptedException e) { e.printStackTrace(); } } }); } assertOpenEventually(latch); es.shutdown(); }
public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); executor.execute(new DepositTask()); executor.execute(new WithdrawTask()); executor.shutdown(); System.out.println("Thread 1 \t\tThread 2\t\tBalance"); }
public void executeMajorCompaction(KeyExtent tablet, Runnable compactionTask) { if (tablet.isRootTablet()) { rootMajorCompactionThreadPool.execute(compactionTask); } else if (tablet.isMeta()) { defaultMajorCompactionThreadPool.execute(compactionTask); } else { majorCompactionThreadPool.execute(compactionTask); } }
/** Loads a new {@code WorkerEngine.java}. */ public void load(boolean isLive) { SERVICE_EXECUTOR.execute(ONDEMAND_SERVICE); SERVICE_EXECUTOR.execute(LOGIN_SERVICE); WORKER_EXECUTOR.execute(MAINTANANENCE); if (isLive) { // Only update the player count on the live server // WORKER_EXECUTOR.execute(P_COUNT); } invoke(UPDATER); logger.info("Loaded the Game Engine."); }
public void initializeExecutors() { if (namingService != null) { namingExecutor = Executors.newSingleThreadExecutor(); namingExecutor.execute(namingService); } if (serverHandler != null) { serverExecutor = Executors.newSingleThreadExecutor(); serverExecutor.execute(serverHandler); } }
public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < 100; i++) { if (i % 2 == 0) { executorService.execute(new Priority(Thread.MAX_PRIORITY, i)); } else { executorService.execute(new Priority(Thread.MIN_PRIORITY, i)); } } }
public static void main(String[] args) { ///////////////////////////////////////////////////////////////////////////// // FixedThreadPool ///////////////////////////////////////////////////////////////////////////// { // 常に10スレッドをプールするExecutorServiceを生成 ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10); // タスクを実行 fixedThreadPool.execute(new TestThread()); fixedThreadPool.execute(new TestThread()); // すべてのタスクが終了したらExecutorServiceをシャットダウン fixedThreadPool.shutdown(); } ///////////////////////////////////////////////////////////////////////////// // CachedThreadPool ///////////////////////////////////////////////////////////////////////////// { // 必要に応じてスレッドのプール数が変化するExecutorServiceを生成 ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); // タスクを実行 cachedThreadPool.execute(new TestThread()); cachedThreadPool.execute(new TestThread()); // すべてのタスクが終了したらExecutorServiceをシャットダウン cachedThreadPool.shutdown(); } ///////////////////////////////////////////////////////////////////////////// // ScheduledThreadPool ///////////////////////////////////////////////////////////////////////////// { // 実行間隔を指定してタスクを実行可能なScheduledExecutorServiceを生成 // (プールするスレッドの最小数は5に指定) ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); // タスクを実行 scheduledThreadPool.schedule( new Runnable() { @Override public void run() { System.out.println("Executed"); } }, 3, TimeUnit.SECONDS); // すべてのタスクが終了したらScheduledExecutorServiceをシャットダウン scheduledThreadPool.shutdown(); } }
public void executeSplit(KeyExtent tablet, Runnable splitTask) { if (tablet.isMeta()) { if (tablet.isRootTablet()) { log.warn("Saw request to split root tablet, ignoring"); return; } defaultSplitThreadPool.execute(splitTask); } else { splitThreadPool.execute(splitTask); } }
/** * Obtains an array of <code>Document</code>s to be processed by {@link * ConfigManager#FACES_CONFIG_PROCESSOR_CHAIN}. * * @param sc the <code>ServletContext</code> for the application to be processed * @param providers <code>List</code> of <code>ConfigurationResourceProvider</code> instances that * provide the URL of the documents to parse. * @param executor the <code>ExecutorService</code> used to dispatch parse request to * @param validating flag indicating whether or not the documents should be validated * @return an array of <code>DocumentInfo</code>s */ private static DocumentInfo[] getConfigDocuments( ServletContext sc, List<ConfigurationResourceProvider> providers, ExecutorService executor, boolean validating) { List<FutureTask<Collection<URI>>> urlTasks = new ArrayList<FutureTask<Collection<URI>>>(providers.size()); for (ConfigurationResourceProvider p : providers) { FutureTask<Collection<URI>> t = new FutureTask<Collection<URI>>(new URITask(p, sc)); urlTasks.add(t); if (executor != null) { executor.execute(t); } else { t.run(); } } List<FutureTask<DocumentInfo>> docTasks = new ArrayList<FutureTask<DocumentInfo>>(providers.size() << 1); int i = 0, j = 0; for (FutureTask<Collection<URI>> t : urlTasks) { try { Collection<URI> l = t.get(); for (URI u : l) { FutureTask<DocumentInfo> d = new FutureTask<DocumentInfo>(new ParseTask(validating, u)); docTasks.add(d); if (executor != null) { executor.execute(d); } else { d.run(); } j++; } } catch (InterruptedException ignored) { } catch (Exception e) { throw new ConfigurationException(e); } i++; } List<DocumentInfo> docs = new ArrayList<DocumentInfo>(docTasks.size()); for (FutureTask<DocumentInfo> t : docTasks) { try { docs.add(t.get()); } catch (ExecutionException e) { throw new ConfigurationException(e); } catch (InterruptedException ignored) { } } return docs.toArray(new DocumentInfo[docs.size()]); }
public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); CountDownLatch latch = new CountDownLatch(SIZE); for (int i = 0; i < 10; i++) { exec.execute(new WaitTask(latch)); } for (int i = 0; i < SIZE; i++) { exec.execute(new TaskPortion(latch)); } System.out.println("launch all tasks"); exec.shutdown(); }