4人参与 • 2026-03-18 • Java
核心结论先明确:
singleton),即一个beandefinition对应一个实例,这个实例会被所有线程共享。无状态(stateless):对象没有可变的成员变量,每次调用仅依赖入参和方法内的局部变量,调用结束后不保留任何信息。
如果bean中没有成员变量(或只有不可变成员变量,如final修饰),仅包含方法逻辑(无状态),则天然线程安全。
// 无状态bean:线程安全
@component
public class statelessservice {
// 无成员变量,仅提供方法逻辑
public int calculate(int a, int b) {
return a + b;
}
}
原因:所有线程调用calculate方法时,仅使用方法内的局部变量(栈私有,线程隔离),没有共享状态。
有状态(stateful):对象包含「可变的成员变量 / 属性」,这些变量会记录对象的「状态」,且这个状态会被多次调用共享。
如果bean包含可变成员变量,多线程并发修改/读取时会出现线程安全问题(如脏读、数据覆盖)。
// 有状态bean:线程不安全
@component
public class statefulservice {
// 共享可变状态:所有线程共享这个变量
private int count = 0;
public void increment() {
// 非原子操作:读取-修改-写入,多线程下会出现计数错误
count++;
}
public int getcount() {
return count;
}
}
测试验证(多线程调用):
@springboottest
public class beanthreadsafetest {
@autowired
private statefulservice statefulservice;
@test
public void teststatefulbean() throws interruptedexception {
// 1000个线程并发调用increment
executorservice executor = executors.newfixedthreadpool(10);
for (int i = 0; i < 1000; i++) {
executor.submit(statefulservice::increment);
}
executor.shutdown();
executor.awaittermination(1, timeunit.minutes);
// 预期1000,实际大概率小于1000(线程安全问题)
system.out.println("最终计数:" + statefulservice.getcount());
}
}
针对「有状态bean」的线程安全问题,核心思路是消除或隔离共享可变状态,常见方案:
将可变状态移到方法内部(局部变量属于线程私有),彻底避免共享。
@component
public class improvedservice {
// 移除共享成员变量
public int increment(int init) {
// 局部变量:每个线程独立
int count = init;
count++;
return count;
}
}
如果必须保留成员变量,用juc的线程安全类替代普通变量:
@component
public class threadsafeservice {
// 原子类:保证自增操作的原子性
private atomicinteger count = new atomicinteger(0);
public void increment() {
// 原子操作,无需加锁
count.incrementandget();
}
public int getcount() {
return count.get();
}
}
对共享变量的操作加锁,保证同一时间只有一个线程执行:
@component
public class lockservice {
private int count = 0;
// 方法加锁:简单但性能较低(锁粒度大)
public synchronized void increment() {
count++;
}
// 或使用reentrantlock(灵活控制锁粒度)
private lock lock = new reentrantlock();
public void incrementwithlock() {
lock.lock();
try {
count++;
} finally {
lock.unlock(); // 必须在finally释放锁
}
}
}
将bean的作用域改为prototype(每次获取bean都创建新实例),每个线程使用独立实例,自然避免共享:
// prototype作用域:每次注入/获取都是新实例
@component
@scope("prototype")
public class prototypeservice {
private int count = 0;
public void increment() {
count++;
}
}
⚠️ 注意:prototype bean的生命周期由用户管理(spring不负责销毁),需注意内存泄漏;且如果是通过依赖注入(如@autowired),需结合objectfactory/applicationcontext获取新实例,否则可能仍复用同一个实例。
到此这篇关于彻底理解 spring 单例线程安全问题的文章就介绍到这了,更多相关spring 单例线程安全内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论