高并发系统谨防被一行日志击垮

一、同步打印日志中的坑

1.1 高并发场景下 logback 造成线程泄露

调用 logback 去打印日志的时候是会加锁的,加锁的位置在:

// ch.qos.logback.core.OutputStreamAppender#writeBytesprivate void writeBytes(byte[] byteArray) throws IOException {
      if (byteArray != null && byteArray.length != 0) {
          this.lock.lock();        try {
              this.outputStream.write(byteArray);            if (this.immediateFlush) {
                  this.outputStream.flush();            }        } finally {
              this.lock.unlock();        }
    }}

复制代码

这就意味着同一个 appender 的日志写是串行的,在高并发的场景下因为有锁的争用现象,所以看似很简单的一行日志,耗费的时间却不少。接下来我们在本地简单的模拟一下高并发的场景,并记录打一行日志的耗时是多少

public static void main(String[] args) {
      ExecutorService threadPool = new ThreadPoolExecutor(500, 750, 20, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1),                                                        new ThreadFactoryBuilder().setNameFormat("test-log-thread").build(), new ThreadPoolExecutor.CallerRunsPolicy());    for (int i = 0; i < 750; i++) {
          LoggerExecutor commonExecutor = new LoggerExecutor();        threadPool.submit(commonExecutor);    }}static class LoggerExecutor implements Runnable {
      @SneakyThrows    @Override    public void run() {
          while (true) {
              long start = System.currentTimeMillis();            logger.info("log info message at {}", System.currentTimeMillis());            long end = System.currentTimeMillis();            long time = end - start;            System.out.println(time);        }    }}

复制代码

需要说明的是,现实中高并发的请求应当用一个线程池向另一个线程池反复提交任务来模拟,这里我们简化了这个过程。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值