遗漏任务

软件测试经验与教训 48/49/50/51/52/53/54/85/72/73/79/102/103/112/113/127/128/129/137/140/148/273

private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); /** * 请求队列(线程安全) * 线程安全存储前端请求 */ private final BlockingQueue<FutureTask<?>> requestQueue = new LinkedBlockingQueue<>(); private final AtomicBoolean isProcessing = new AtomicBoolean(false); /** * 前端调用入口(线程安全) * @param callable * @return 返回一个Future,用于获取结果 */ public <T> Future<T> addRequest(Callable<T> callable) { FutureTask<T> task = new FutureTask<>(callable); // 1. 处理队列满的情况 if (!requestQueue.offer(task)) { throw new RejectedExecutionException("任务队列已满"); } // 2. 确保单一线程处理队列(双重检查锁) if (!isProcessing.get()) { synchronized (this) { if (!isProcessing.compareAndSet(false, true)) { executorService.execute(this::processQueue); } } } return task; } /** * poll() 非阻塞取任务避免线程挂起 * System.err.println("处理异常: " + e.getMessage()); */ private void processQueue() { try { while (!Thread.currentThread().isInterrupted()) { // 3. 阻塞式获取任务(避免空轮询) FutureTask<?> task = requestQueue.poll(500, TimeUnit.MILLISECONDS); if (task == null) break; try { task.run(); // 同步执行任务 } catch (Exception e) { System.err.println("处理异常: " + e.getMessage()); } } } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } finally { isProcessing.set(false); // 4. 重置处理状态 // 5. 检查遗漏任务(并发场景) if (!requestQueue.isEmpty()) { synchronized (this) { if (isProcessing.compareAndSet(false, true)) { executorService.execute(this::processQueue); } } } } }检查是否有问题
10-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值