使用Java队列来处理日志信息(线程池的使用)
一:ThreadPoolExecutor的重要参数
corePoolSize:核心线程数
核心线程会一直存活,及时没有任务需要执行
当线程数小于核心线程数时,即使有线程空闲,线程池也会优先创建新线程处理
设置allowCoreThreadTimeout=true(默认false)时,核心线程会超时关闭
queueCapacity:任务队列容量(阻塞队列)
当核心线程数达到最大时,新任务会放在队列中排队等待执行
maxPoolSize:最大线程数
当线程数>=corePoolSize,且任务队列已满时。线程池会创建新线程来处理任务
当线程数=maxPoolSize,且任务队列已满时,线程池会拒绝处理任务而抛出异常
keepAliveTime:线程空闲时间
当线程空闲时间达到keepAliveTime时,线程会退出,直到线程数量=corePoolSize
如果allowCoreThreadTimeout=true,则会直到线程数量=0
allowCoreThreadTimeout:允许核心线程超时
rejectedExecutionHandler:任务拒绝处理器
两种情况会拒绝处理任务:
当线程数已经达到maxPoolSize,切队列已满,会拒绝新任务
当线程池被调用shutdown()后,会等待线程池里的任务执行完毕,再shutdown。如果在调用shutdown()和线程池真正shutdown之间提交任务,会拒绝新任务
线程池会调用rejectedExecutionHandler来处理这个任务。如果没有设置默认是AbortPolicy,会抛出异常
ThreadPoolExecutor类有几个内部实现类来处理这类情况:
AbortPolicy 丢弃任务,抛运行时异常
CallerRunsPolicy 执行任务
DiscardPolicy 忽视,什么都不会发生
DiscardOldestPolicy 从队列中踢出最先进入队列(最后一个执行)的任务
实现RejectedExecutionHandler接口,可自定义处理器
二、ThreadPoolExecutor执行顺序:
线程池按以下行为执行任务
当线程数小于核心线程数时,创建线程。
当线程数大于等于核心线程数,且任务队列未满时,将任务放入任务队列。
当线程数大于等于核心线程数,且任务队列已满
若线程数小于最大线程数,创建线程
若线程数等于最大线程数,抛出异常,拒绝任务
三、如何设置参数
默认值
corePoolSize=1
queueCapacity=Integer.MAX_VALUE
maxPoolSize=Integer.MAX_VALUE
keepAliveTime=60s
allowCoreThreadTimeout=false
rejectedExecutionHandler=AbortPolicy()
如何来设置
需要根据几个值来决定
tasks :每秒的任务数,假设为500~1000
taskcost:每个任务花费时间,假设为0.1s
responsetime:系统允许容忍的最大响应时间,假设为1s
做几个计算
corePoolSize = 每秒需要多少个线程处理?
threadcount = tasks/(1/taskcost) =tasks*taskcout = (500~1000)*0.1 = 50~100 个线程。corePoolSize设置应该大于50
根据8020原则,如果80%的每秒任务数小于800,那么corePoolSize设置为80即可
queueCapacity = (coreSizePool/taskcost)*responsetime
计算可得 queueCapacity = 80/0.1*1 = 80。意思是队列里的线程可以等待1s,超过了的需要新开线程来执行
切记不能设置为Integer.MAX_VALUE,这样队列会很大,线程数只会保持在corePoolSize大小,当任务陡增时,不能新开线程来执行,响应时间会随之陡增。
maxPoolSize = (max(tasks)- queueCapacity)/(1/taskcost)
计算可得 maxPoolSize = (1000-80)/10 = 92
(最大任务数-队列容量)/每个线程每秒处理能力 = 最大线程数
rejectedExecutionHandler:根据具体情况来决定,任务不重要可丢弃,任务重要则要利用一些缓冲机制来处理
keepAliveTime和allowCoreThreadTimeout采用默认通常能满足
以上都是理想值,实际情况下要根据机器性能来决定。如果在未达到最大线程数的情况机器cpu load已经满了,则需要通过升级硬件(呵呵)和优化代码,降低taskcost来处理。
日志的队列: LogQueue.java
package com.tencent.queuedemo.queue; import com.tencent.queuedemo.moudel.LogEntity; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * 操作日志的队列 */ public class LogQueue { //队列大小 public static final int QUEUE_MAX_SIZE = 100; /** * 消息入队 * @param logEntity * @return */ public static void push(LogEntity logEntity) throws Exception { //队列已满时,会阻塞队列,直到未满 blockingQueue.put(logEntity); } /** * 消息出队 * @return */ public static LogEntity poll() { LogEntity result = null; try { //队列为空时会阻塞队列,直到不是空 result = blockingQueue.take(); } catch (InterruptedException e) { e.printStackTrace(); } return result; } /** * 获取队列大小 * @return */ public static int size() { return blockingQueue.size(); } /** * 设置核心池大小,也就是能允许同时运行的线程数,corePoolSize 表示允许线程池中允许同时运行的最大线程数。 */ static int corePoolSize = 100; /** 表示线程没有任务时最多保持多久然后停止。默认情况下,只有线程池中线程数大于corePoolSize 时,keepAliveTime 才会起作用。 换句话说,当线程池中的线程数大于corePoolSize,并且一个线程空闲时间达到了keepAliveTime,那么就是shutdown。 * */ static long keepActiveTime = 200; /** * 线程池允许创建的最大线程数。如果队列满了,并且已创建的线程数小于最大线程数,则线程池会再创建新的线程执行任务。 * 值得注意的是,如果使用了无界的任务队列这个参数就没用了。 */ static int maximumPoolSize = 300; static TimeUnit timeUnit = TimeUnit.SECONDS; /**创建ThreadPoolExecutor线程池对象,并初始化该对象的各种参数 * */ public static ThreadPoolExecutor executor = null; /** 初始化阻塞队列 * */ public static BlockingQueue<LogEntity> blockingQueue = null; static{ /** * 这是日志队列,用来实际操作的 */ blockingQueue = new LinkedBlockingQueue<>(QUEUE_MAX_SIZE); /** *queue:workQueue必须是BlockingQueue阻塞队列。当线程池中的线程数超过它的corePoolSize的时候,线程会进入阻塞队列进行阻塞等待。通过workQueue,线程池实现了阻塞功能 */ /** * 这个只是线程池的阻塞队列 */ executor = new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepActiveTime,timeUnit,new LinkedBlockingQueue<Runnable>(100)); } /** * 初始化线程池 * @return */ /*public static ThreadPoolExecutor createThreadPool(){ if(executor == null){ executor = new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepActiveTime,timeUnit,blockingQueue); } return executor; }*/ }
生产日志,每次访问就记录一次日志
package com.tencent.queuedemo.controller; import com.tencent.queuedemo.moudel.LogEntity; import com.tencent.queuedemo.queue.LogQueue; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import java.util.Date; import java.util.concurrent.BlockingQueue; @Controller public class LogController { @GetMapping("/visit/{url}") public void visitLog(@PathVariable("url") String url){ LogEntity logEntity = new LogEntity(); logEntity.setVisitTime(new Date()); logEntity.setVisitUrl(url); System.out.println("访问的信息:"+logEntity.toString()); //将任务加入到队列中去 BlockingQueue<LogEntity> blockingQueue = LogQueue.blockingQueue; try { blockingQueue.put(logEntity); } catch (InterruptedException e) { e.printStackTrace(); } } }
日志的实体类
package com.tencent.queuedemo.moudel; import java.util.Date; /** * 日志实体 */ public class LogEntity { /** * 访问的时间 */ private Date visitTime; /** * 访问的url */ private String visitUrl; public Date getVisitTime() { return visitTime; } public void setVisitTime(Date visitTime) { this.visitTime = visitTime; } public String getVisitUrl() { return visitUrl; } public void setVisitUrl(String visitUrl) { this.visitUrl = visitUrl; } @Override public String toString() { return "LogEntity{" + "visitTime=" + visitTime + ", visitUrl='" + visitUrl + '\'' + '}'; } }
线程放到线程池
package com.tencent.queuedemo.thread; import com.tencent.queuedemo.moudel.LogEntity; import org.springframework.stereotype.Component; /** * 日志线程类,将日志保存到队列中 */ @Component public class LogThread implements Runnable { private LogEntity logEntity; public LogThread() { } public LogThread(LogEntity logEntity) { this.logEntity = logEntity; } @Override public void run() { try { System.out.println("这是在将日志保存到队列中去:"+logEntity.toString()); } catch (Exception e) { e.printStackTrace(); } } }
package com.tencent.queuedemo.timer; import com.tencent.queuedemo.moudel.LogEntity; import com.tencent.queuedemo.queue.LogQueue; import com.tencent.queuedemo.thread.LogThread; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.concurrent.ThreadPoolExecutor; @Component @EnableScheduling public class LogTimer { @Scheduled(cron = "0/59 * * * * ? ") //每5秒执行一次 public void saveLog(){ /** * 定点循环执行队列中的任务 */ while(true){ //获取到阻塞队列 //获取到线程池 ThreadPoolExecutor threadPool = LogQueue.executor; LogEntity entity = LogQueue.poll(); //执行队列中的任务 if(null != entity){ System.out.println("hah,队列的大小:"+LogQueue.size()); threadPool.submit(new LogThread(entity)); } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具