JAVA并行流导致的 No thread-bound request found

来源:互联网 发布:w7内外网转换软件 编辑:程序博客网 时间:2024/06/05 14:27

问题重现

开发环境依旧是就一水的Spring,可在我的其他的博客找到内容。
之前开发的接口一直都是好好运行的,后来突发奇想,一拍脑门,把所有的流处理 ( stream) 改成了并行流 ( parallelStream) ,心想着这么着,处理速度应该还能上一个档次,但是,也觉得会出现一些问题,之前想的是会不会不同步之类的.没想到报应来得这么快.

因为项目还在研发阶段,所以本着偷懒的原则,把加载配置信息写成了通过 getServletContext 获得实际路径,然后通过流读取文件,为了获得 getServletContext ,所以难免就需要添加 HttpServletRequest 参数,然后,又为了省事,就在 Service 里自动注入了 HttpServletRequest 了.本来一切相安,结构,手贱,把流处理全换成了并行流.

错误信息

java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
开始的时候,一直关注这个,以为是出现了多个,然而并没有考虑这个多个到底是问题在哪.
很是迷茫了一下会儿.
后来向下看,果不其然,看到了lambda………..报应来了.
一看实际代码,

@Autowiredprivate HttpServletRequest request;list.parallelStream().forEach(action -> {    GetPhotoPath(request, 一些其他参数);  });

定睛一看,完蛋,果然就是这个并行流的问题.
改成普通的流处理,问题解决!

阅读全文
0 0
原创粉丝点击