英文:
Is really threadlocal more efficient than @RequestScope?
问题
我知道,几年前,ThreadLocal
在某种程度上更好,但现在我想知道在最新版本的 Spring Boot 中(我正在使用 2.2.6 版本),这段代码:
@Bean
@RequestScope
public MyPojo(){
return new MyPojo();
}
是否真的比以下代码更高效:
public class MyControllerAspect{
private static final ThreadLocal<MyPojo> pojo = new ThreadLocal<MyPojo>() {
public MyPojo initialValue(){
return new MyPojo();
}
}
@Around("controllers()")
public void doFilterInternal(HttpServletRequest request, HttpServletResponse servletResponse,
try {
//inject mypojo and do stuff
}finally{
pojo.remove(); //clean resources
}
这两段代码基本上看起来和 Spring 已经在做的事情很相似,我觉得我只是在重新发明轮子,可能吗?
或者是后面的代码真的更高效一些?
英文:
I know that, some years ago, threadlocal was better but now I'm wondering if in the latest versions of spring boot (I'm using 2.2.6) this code here:
@Bean
@RequestScope
public MyPojo(){
return new MyPojo();
}
Is really more efficient than:
public class MyControllerAspect{
private static final ThreadLocal<MyPojo> pojo = new ThreadLocal<MyPojo>() {
public MyPojo initialValue(){
return new MyPojo();
}
}
@Around("controllers()")
public void doFilterInternal(HttpServletRequest request, HttpServletResponse servletResponse,
try {
//inject mypojo and do stuff
}finally{
pojo.remove(); //clean resources
}
It pretty much seems the same thing Spring would already do, I feel like I'm just re-inventing the wheel could it be?
Or is this last code somewhat really more efficient?
专注分享java语言的经验与见解,让所有开发者获益!
评论