真的,`ThreadLocal` 比 `@RequestScope` 更高效吗?

huangapple 未分类评论52阅读模式
英文:

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&lt;MyPojo&gt; pojo = new ThreadLocal&lt;MyPojo&gt;() {
          public MyPojo initialValue(){
               return new MyPojo();
          }
    }

  @Around(&quot;controllers()&quot;)
 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?

huangapple
  • 本文由 发表于 2020年5月30日 06:20:34
  • 转载请务必保留本文链接:https://java.coder-hub.com/62095405.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定