模拟高并发下Tomcat线程不安全现场记录<一>

1. 所需工具

  1. 集成开发工具(我的是STS)
  2. Tomcat,用来模拟真实请求响应服务(我的是Spring Boot内置有Tomcat)

2. 代码

  1. ThreadInsecurity类,主要用来提供服务,这里的服务也很简单。全局变量的累加,每请求一次就加3000;100以内的每次增加都会休眠100ms(为什么要休眠?为了模拟耗时的写入操作,以达到线程不安全现象。这是符合现实情况的)。
package thread;

import java.util.ArrayList;
import java.util.List;

public class ThreadInsecurity {

private static List<byte[]> byteList = new ArrayList<>();
    
    public static void clear() {
        if (!byteList.isEmpty()) {
            System.out.println("开始清除byteList数据");
            byteList.clear();
        }        
    }
    
    public static List<byte[]> getByteList() {
        return byteList;
    }

    public static String addByte() {
                  
        int count = 0;
        while (count < 3000) {
            
            if (count < 100) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            
            byteList.add(new byte[4096 * 10]);
                        
            count++;
        }
        
        String value = "Thread=" + Thread.currentThread().getName() + ", byteList's HashCode=" + byteList.hashCode() + ", size=" + byteList.size();
        
        System.out.println(value);
        
        return value;
    }

}

  1. controller,提供服务,url是http://localhost:1010/sprintboot/thread_insecurity。
package com.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import thread.ThreadInsecurity;

@RestController
public class ThreadController {

    @RequestMapping("/thread_insecurity")
    public String threadInsecurity() {
        System.out.println("The front-end request is received and the thread, " + Thread.currentThread().getName() + " is started!");
        String value = ThreadInsecurity.addByte();
        return value;
    }
}

3. 测试与分析

我是用浏览器快速连续发起6次请求(如何做到呢?先打开窗口把url复制进去,不要回车,连续打开复制6个,这样子做完,再快速的回车—切换窗口—回车),几乎可以说是同时发起请求。
看看前端连续发起6次请求图片:
在这里插入图片描述

看看STS里的Console:
在这里插入图片描述
需要说明一下,我发起这连续的6次请求之前是有发起过4次请求的,即从size=12000(3000*4)开始。
从图片可以知道:Tomcat是使用线程池的,里面有10个nio线程(这个可以使用JConsole验证);看最后那4次size不是整数了。说明线程不安全,简单解释就是全局变量是存放在方法区的,这是线程共享的。多线程做写入操作就会有线程不安全问题。

4. 结论

在类中有静态全局变量,且这个变量存在写入操作时就要考虑线程安全问题了。下次我们看看如何解决这个非线程安全问题。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值