Java Code Examples for java.util.concurrent.ThreadPoolExecutor#DiscardOldestPolicy

The following examples show how to use java.util.concurrent.ThreadPoolExecutor#DiscardOldestPolicy . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DataEventManager.java    From incubator-retired-gossip with Apache License 2.0 6 votes vote down vote up
public DataEventManager(MetricRegistry metrics) {
  perNodeDataHandlers = new CopyOnWriteArrayList<>();
  perNodeDataHandlerQueue = new ArrayBlockingQueue<>(DataEventConstants.PER_NODE_DATA_QUEUE_SIZE);
  perNodeDataEventExecutor = new ThreadPoolExecutor(
          DataEventConstants.PER_NODE_DATA_CORE_POOL_SIZE,
          DataEventConstants.PER_NODE_DATA_MAX_POOL_SIZE,
          DataEventConstants.PER_NODE_DATA_KEEP_ALIVE_TIME_SECONDS, TimeUnit.SECONDS,
          perNodeDataHandlerQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
  
  sharedDataHandlers = new CopyOnWriteArrayList<>();
  sharedDataHandlerQueue = new ArrayBlockingQueue<>(DataEventConstants.SHARED_DATA_QUEUE_SIZE);
  sharedDataEventExecutor = new ThreadPoolExecutor(DataEventConstants.SHARED_DATA_CORE_POOL_SIZE,
          DataEventConstants.SHARED_DATA_MAX_POOL_SIZE,
          DataEventConstants.SHARED_DATA_KEEP_ALIVE_TIME_SECONDS, TimeUnit.SECONDS,
          sharedDataHandlerQueue, new ThreadPoolExecutor.DiscardOldestPolicy());
  
  metrics.register(DataEventConstants.PER_NODE_DATA_SUBSCRIBERS_SIZE,
          (Gauge<Integer>) () -> perNodeDataHandlers.size());
  metrics.register(DataEventConstants.PER_NODE_DATA_SUBSCRIBERS_QUEUE_SIZE,
          (Gauge<Integer>) () -> perNodeDataHandlerQueue.size());
  metrics.register(DataEventConstants.SHARED_DATA_SUBSCRIBERS_SIZE,
          (Gauge<Integer>) () -> sharedDataHandlers.size());
  metrics.register(DataEventConstants.SHARED_DATA_SUBSCRIBERS_QUEUE_SIZE,
          (Gauge<Integer>) () -> sharedDataHandlerQueue.size());
  
}
 
Example 2
Source File: ThreadPoolExecutorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * executor using DiscardOldestPolicy drops oldest task if saturated.
 */
public void testSaturatedExecute4() {
    final CountDownLatch done = new CountDownLatch(1);
    LatchAwaiter r1 = awaiter(done);
    LatchAwaiter r2 = awaiter(done);
    LatchAwaiter r3 = awaiter(done);
    final ThreadPoolExecutor p =
        new ThreadPoolExecutor(1, 1,
                               LONG_DELAY_MS, MILLISECONDS,
                               new ArrayBlockingQueue<Runnable>(1),
                               new ThreadPoolExecutor.DiscardOldestPolicy());
    try (PoolCleaner cleaner = cleaner(p, done)) {
        assertEquals(LatchAwaiter.NEW, r1.state);
        assertEquals(LatchAwaiter.NEW, r2.state);
        assertEquals(LatchAwaiter.NEW, r3.state);
        p.execute(r1);
        p.execute(r2);
        assertTrue(p.getQueue().contains(r2));
        p.execute(r3);
        assertFalse(p.getQueue().contains(r2));
        assertTrue(p.getQueue().contains(r3));
    }
    assertEquals(LatchAwaiter.DONE, r1.state);
    assertEquals(LatchAwaiter.NEW, r2.state);
    assertEquals(LatchAwaiter.DONE, r3.state);
}
 
Example 3
Source File: ServerServiceImpl.java    From pmq with Apache License 2.0 6 votes vote down vote up
@Override
public void startBroker() {
	if (startFlag.compareAndSet(false, true)) {
		isBroker=true;
		executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(50),
				SoaThreadFactory.create("ServerServiceImpl", true), new ThreadPoolExecutor.DiscardOldestPolicy());
		updateHeartBeat();
		executor.execute(() -> {
			while (isRunning) {
				try {
					updateHeartBeat();
				} catch (Exception e) {
					log.error("ServerServiceImpl_updateHeartBeat_error", e);
				}
				Util.sleep(soaConfig.getServerHeartbeat() * 1000);
			}
		});
	}

}
 
Example 4
Source File: ThreadPoolTest.java    From java-study with Apache License 2.0 6 votes vote down vote up
/**
	 * ThreadPoolExecutor线程池
	 */
	private  static void threadPoolExecutor() {
		int corePoolSize=5;
		int maximumPoolSize=10;
		long keepAliveTime=2L;
		// 线程核心数,最大线程数,线程缓存时间,时间格式,缓存队列 ,线程工厂,拒绝策略
		ThreadPoolExecutor tpx=new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, 
				TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
				Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardOldestPolicy());
		
		  for (int i = 1; i <= 10; i++) {  
	            try {  
	                // 产生一个任务,并将其加入到线程池  
	                String task = "task@ " + i;  
//	                System.out.println("put " + task);  
	                tpx.execute(new MyThread(task));  
	                // 便于观察,等待一段时间  
	                Thread.sleep(20);  
	            } catch (Exception e) {  
	                e.printStackTrace();  
	            }  
	        }  
	}
 
Example 5
Source File: ClientAppRegisterInstanceController.java    From radar with Apache License 2.0 6 votes vote down vote up
@PostConstruct
private void init() {
	initMetric();
	threadSize = soaConfig.getRegisterInstanceThreadSize();
	executor = new ThreadPoolExecutor(threadSize, threadSize, 0L, TimeUnit.MILLISECONDS,
			new LinkedBlockingQueue<Runnable>(50), SoaThreadFactory.create("registerInstance", true),
			new ThreadPoolExecutor.DiscardOldestPolicy());
	soaConfig.registerChanged(new Runnable() {
		@Override
		public void run() {
			if (threadSize != soaConfig.getRegisterInstanceThreadSize()) {
				threadSize = soaConfig.getRegisterInstanceThreadSize();
				log.info("RegisterInstanceThreadSize_Changed_{}", threadSize);
				executor.setMaximumPoolSize(threadSize);
				executor.setCorePoolSize(threadSize);
			}
		}
	});
	executor.execute(() -> {
		registerInstance();
	});
}
 
Example 6
Source File: ServiceTest.java    From pmq with Apache License 2.0 6 votes vote down vote up
private void sendMessage(MqClient.MqClientBase mqClientBase, List<String> topicNames) {
	// 初始化线程
	executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(10),
			SoaThreadFactory.create("mq-all-process-test", true), new ThreadPoolExecutor.DiscardOldestPolicy());
	executorStart = true;
	// 异步一直发消息
	executor.execute(new Runnable() {
		@Override
		public void run() {
			while (executorStart) {
				try {
					for (String topicName : topicNames) {
						send(mqClientBase, topicName);
					}
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	});
}
 
Example 7
Source File: DataProcessThreadFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private DataProcessThreadFactory() {
	/** 
     * Param:  
     * corePoolSize - 池中所保存的线程数,包括空闲线程。  
     * maximumPoolSize - 池中允许的最大线程数(采用LinkedBlockingQueue时没有作用)。  
     * keepAliveTime -当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间,线程池维护线程所允许的空闲时间。  
     * unit - keepAliveTime参数的时间单位,线程池维护线程所允许的空闲时间的单位:秒 。  
     * workQueue - 执行前用于保持任务的队列(缓冲队列)。此队列仅保持由execute 方法提交的 Runnable 任务。  
     * RejectedExecutionHandler -线程池对拒绝任务的处理策略(重试添加当前的任务,自动重复调用execute()方法) 
     */
	threadpool = new ThreadPoolExecutor( 20, 40, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.DiscardOldestPolicy() );
}
 
Example 8
Source File: DiscoveryClientTest.java    From radar with Apache License 2.0 5 votes vote down vote up
@Test(expected = TimeoutException.class)
public void testRegisterInstanceRetry() throws InterruptedException, ExecutionException, TimeoutException {
	RadarClientConfig config = new RadarClientConfig(rgUrl);

	RadarInstance instanceRadar = RadarInstance.getBuilder()
			// 设置实例ID,可以为空
			.withCandInstanceId("262a15e7-6b60-432d-abdb-e939fff2fd76")
			// 设置环境名称
			.withClusterName("dc1.prd")
			// 设置AppId
			.withCandAppId("10010001")
			// 设置AppName
			.withAppName("RegistryInstanceRetry")
			// 设置IP地址
			.withHost("10.1.30.2")
			// 设置端口
			.withPort(0).build();

	DiscoveryClient client = DiscoveryClient.getInstance();

	ThreadPoolExecutor executors = new ThreadPoolExecutor(1, 1, 3L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100),
			SoaThreadFactory.create("DiscoveryClientTest", true), new ThreadPoolExecutor.DiscardOldestPolicy());
	Future<Boolean> f = executors.submit(new Callable<Boolean>() {
		@Override
		public Boolean call() throws NoSuchFieldException, IllegalAccessException {
			// 启动客户端
			client.setConfig(config);
			Field field = client.getClass().getDeclaredField("isStartUp");
			field.setAccessible(true);
			field.set(client, new AtomicBoolean(false));
			// 启动客户端
			client.register(instanceRadar);
			return true;
		}
	});
	f.get(5, TimeUnit.SECONDS);
}
 
Example 9
Source File: ThreadPoolExecutorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * execute using DiscardOldestPolicy drops task on shutdown
 */
public void testDiscardOldestOnShutdown() {
    final ThreadPoolExecutor p =
        new ThreadPoolExecutor(1, 1,
                               LONG_DELAY_MS, MILLISECONDS,
                               new ArrayBlockingQueue<Runnable>(1),
                               new ThreadPoolExecutor.DiscardOldestPolicy());

    try { p.shutdown(); } catch (SecurityException ok) { return; }
    try (PoolCleaner cleaner = cleaner(p)) {
        TrackedNoOpRunnable r = new TrackedNoOpRunnable();
        p.execute(r);
        assertFalse(r.done);
    }
}
 
Example 10
Source File: DataProcessThreadFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private DataProcessThreadFactory() {
	/** 
     * Param:  
     * corePoolSize - 池中所保存的线程数,包括空闲线程。  
     * maximumPoolSize - 池中允许的最大线程数(采用LinkedBlockingQueue时没有作用)。  
     * keepAliveTime -当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间,线程池维护线程所允许的空闲时间。  
     * unit - keepAliveTime参数的时间单位,线程池维护线程所允许的空闲时间的单位:秒 。  
     * workQueue - 执行前用于保持任务的队列(缓冲队列)。此队列仅保持由execute 方法提交的 Runnable 任务。  
     * RejectedExecutionHandler -线程池对拒绝任务的处理策略(重试添加当前的任务,自动重复调用execute()方法) 
     */
	threadpool = new ThreadPoolExecutor( 20, 40, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.DiscardOldestPolicy() );
}
 
Example 11
Source File: UiQueueService.java    From pmq with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
	if (startFlag.compareAndSet(false, true)) {
		lastUpdateTime = System.currentTimeMillis() - soaConfig.getMqReportInterval() * 2;
		executor = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(50),
				SoaThreadFactory.create("UiQueueService", true), new ThreadPoolExecutor.DiscardOldestPolicy());
		executor.execute(() -> {
			while (isRunning) {
				try {
					if (System.currentTimeMillis() - lastAccessTime < soaConfig.getMqReportInterval()
							|| System.currentTimeMillis() - lastAccessTime > 1000 * 60 * 60 * 60) {
						if (System.currentTimeMillis() - lastUpdateTime > soaConfig.getMqReportInterval()) {
							initCache();
							initMessageCount();
							if (queueListAvg.get().size() > 0) {
								lastUpdateTime = System.currentTimeMillis();
								lastAccessTime = System.currentTimeMillis() - soaConfig.getMqReportInterval() * 2;
							}
						}
					}
				} catch (Exception e) {
					log.error("UiQueueServiceImpl_initCache_error", e);
				}
				if (queueListAvg.get().size() == 0) {
					Util.sleep(10 * 1000);
				} else {
					Util.sleep(2000);
				}
			}
		});
	}
}
 
Example 12
Source File: UiQueueOffsetService.java    From pmq with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
	if (startFlag.compareAndSet(false, true)) {
		lastUpdateTime = System.currentTimeMillis() - soaConfig.getMqReportInterval() * 2;
		executor = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(50),
				SoaThreadFactory.create("UiQueueOffsetService", true),
				new ThreadPoolExecutor.DiscardOldestPolicy());
		executor.execute(() -> {
			while (isRunning) {
				try {
					if (System.currentTimeMillis() - lastAccessTime < soaConfig.getMqReportInterval()
							|| System.currentTimeMillis() - lastAccessTime > 1000 * 60 * 60 * 60) {
						if (System.currentTimeMillis() - lastUpdateTime > soaConfig.getMqReportInterval()) {
							initCache();
							if (queueOffsetVos.get().size() > 0) {
								lastUpdateTime = System.currentTimeMillis();
								lastAccessTime = System.currentTimeMillis() - soaConfig.getMqReportInterval() * 2;
							}
						}
					}
				} catch (Exception e) {
					log.error("UiQueueOffsetServiceImpl_initCache_error", e);
				}
				if (queueOffsetVos.get().size() == 0) {
					Util.sleep(10 * 1000);
				} else {
					Util.sleep(1000);
				}
			}
		});
	}
}
 
Example 13
Source File: UiTopicService.java    From pmq with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
	if (startFlag.compareAndSet(false, true)) {
		lastUpdateTime = System.currentTimeMillis() - soaConfig.getMqReportInterval() * 2;
		executor = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(50),
				SoaThreadFactory.create("UiTopicService", true), new ThreadPoolExecutor.DiscardOldestPolicy());
		executor.execute(() -> {
			while (isRunning) {
				try {
					if (System.currentTimeMillis() - lastAccessTime < soaConfig.getMqReportInterval()
							|| System.currentTimeMillis() - lastAccessTime > 1000 * 60 * 60 * 60) {
						if (System.currentTimeMillis() - lastUpdateTime > soaConfig.getMqReportInterval()) {
							initCache();
							if (uiQueueService.getQueueListCount().size() > 0) {
								lastUpdateTime = System.currentTimeMillis();
								lastAccessTime = System.currentTimeMillis() - soaConfig.getMqReportInterval() * 2;
							}
						}
					}
				} catch (Exception e) {
					log.error("UiQueueServiceImpl_initCache_error", e);
				}
				if (uiQueueService.getQueueListCount().size() == 0) {
					Util.sleep(10 * 1000);
				} else {
					Util.sleep(2 * 1000);
				}
			}
		});
	}
}
 
Example 14
Source File: MqCheckService.java    From pmq with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
	if (startFlag.compareAndSet(false, true)) {
		this.executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
				new LinkedBlockingQueue<Runnable>(100), SoaThreadFactory.create("MqCheckService", true),
				new ThreadPoolExecutor.DiscardOldestPolicy());
		isStop = false;
		runStatus = false;
		executor.execute(new Runnable() {
			@Override
			public void run() {
				while (!isStop) {
					runStatus = true;
					Transaction transaction = Tracer.newTransaction("mq-group", "check");
					try {
						checkData();
						transaction.setStatus(Transaction.SUCCESS);
					} catch (Exception e) {
						transaction.setStatus(e);
					} finally {
						transaction.complete();
					}
					runStatus = false;
					Util.sleep(120000);
				}
			}
		});
	}
}
 
Example 15
Source File: ConsumerPollingService.java    From pmq with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
	if (startFlag.compareAndSet(false, true)) {
		isStop = false;
		runStatus = false;
		executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(100),
				SoaThreadFactory.create("ConsumerPollingService", true),
				new ThreadPoolExecutor.DiscardOldestPolicy());
		executor.execute(new Runnable() {
			@Override
			public void run() {
				while (!isStop) {
					TraceMessageItem traceMessageItem = new TraceMessageItem();
					runStatus = true;
					try {
						traceMessageItem.status = "suc";
						longPolling();
					} catch (Exception e) {
						// e.printStackTrace();
						traceMessageItem.status = "fail";
						Util.sleep(1000);
					}
					traceMsg.add(traceMessageItem);
					runStatus = false;
				}
			}
		});
	}
}
 
Example 16
Source File: SimpleActiveGossiper.java    From incubator-retired-gossip with Apache License 2.0 5 votes vote down vote up
public SimpleActiveGossiper(GossipManager gossipManager, GossipCore gossipCore,
                            MetricRegistry registry) {
  super(gossipManager, gossipCore, registry);
  scheduledExecutorService = Executors.newScheduledThreadPool(2);
  workQueue = new ArrayBlockingQueue<Runnable>(1024);
  threadService = new ThreadPoolExecutor(1, 30, 1, TimeUnit.SECONDS, workQueue,
          new ThreadPoolExecutor.DiscardOldestPolicy());
}
 
Example 17
Source File: ThreadPoolExecutorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * execute using DiscardOldestPolicy drops task on shutdown
 */
public void testDiscardOldestOnShutdown() {
    final ThreadPoolExecutor p =
        new ThreadPoolExecutor(1, 1,
                               LONG_DELAY_MS, MILLISECONDS,
                               new ArrayBlockingQueue<Runnable>(1),
                               new ThreadPoolExecutor.DiscardOldestPolicy());

    try { p.shutdown(); } catch (SecurityException ok) { return; }
    try (PoolCleaner cleaner = cleaner(p)) {
        TrackedNoOpRunnable r = new TrackedNoOpRunnable();
        p.execute(r);
        assertFalse(r.done);
    }
}
 
Example 18
Source File: AlbianThreadPoolService.java    From Albianj2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void loading()
        throws RuntimeException, AlbianParserException {
    threadPool = new ThreadPoolExecutor(
            KernelSetting.getThreadPoolCoreSize(),
            KernelSetting.getThreadPoolMaxSize(), 300, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(KernelSetting
                    .getThreadPoolMaxSize()
                    - KernelSetting.getThreadPoolCoreSize()),
            new ThreadPoolExecutor.DiscardOldestPolicy());
    super.loading();
}
 
Example 19
Source File: DelimitedListDialog.java    From StringManipulation with Apache License 2.0 4 votes vote down vote up
DelimitedListDialog(DelimitedListAction action, Editor editor) {
	this.action = action;
	this.editor = editor;

	//max 1 concurrent task + max 1 in queue
	executor = new ThreadPoolExecutor(1, 1,
		60, TimeUnit.SECONDS,
		new ArrayBlockingQueue<Runnable>(1),
		new DefaultThreadFactory("StringManipulation.DelimitedListDialog", true),
		new ThreadPoolExecutor.DiscardOldestPolicy());


	this.previewEditor = IdeUtils.createEditorPreview("", false);
	this.previewPanel.add(previewEditor.getComponent());
	previewEditor.getComponent().setPreferredSize(new Dimension(0, 200));

	AtomicBoolean allSelectionsEmpty = new AtomicBoolean(true);
	editor.getCaretModel().runForEachCaret(caret -> allSelectionsEmpty.set(allSelectionsEmpty.get() && !caret.hasSelection()));
	if (allSelectionsEmpty.get()) {
		sourceClipboard.setSelected(true);
	}

	final DocumentAdapter documentAdapter = new DocumentAdapter() {
		@Override
		protected void textChanged(@NotNull DocumentEvent documentEvent) {
			renderPreview();
		}
	};
	sourceDelimiter.getDocument().addDocumentListener(documentAdapter);
	destDelimiter.getDocument().addDocumentListener(documentAdapter);
	quote.getDocument().addDocumentListener(documentAdapter);
	unquote.getDocument().addDocumentListener(documentAdapter);
	sourceClipboard.addChangeListener(e -> renderPreview());
	sourceSelection.addChangeListener(e -> renderPreview());
	autoQuote.addChangeListener(e -> renderPreview());
	autoQuote.addChangeListener(e -> {
		quote.setEditable(!autoQuote.isSelected());
		if (quote.isEditable()) {
			if (quote.getText().equals("<auto>")) {
				quote.setText("");
			}
			quote.requestFocus();
		}
	});
	renderPreview();
}
 
Example 20
Source File: ExecutorConfiguration.java    From porcupine with Apache License 2.0 4 votes vote down vote up
public Builder discardOldestPolicy() {
    configuration.rejectedExecutionHandler = new ThreadPoolExecutor.DiscardOldestPolicy();
    return this;
}