首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring long polling ConcurrentModificationException

Spring long polling ConcurrentModificationException
EN

Stack Overflow用户
提问于 2017-07-29 21:17:18
回答 1查看 196关注 0票数 1

基本上我有一个简单的新闻应用程序,现在我想有新闻列表自动更新为所有用户,每当有人添加或删除新闻,它有点工作,但有时我得到ConcurrentModificationException,我只是需要在编写此方法的帮助:

代码语言:javascript
复制
@GetMapping("/pollnews")
@ResponseBody
public DeferredResult<ModelAndView> poll(Model model){
    DeferredResult<ModelAndView> result = new DeferredResult<>();
    new Thread(new Runnable() {

        @Override
        public void run() {
            while(true){
                if(changeOccured){
                    changeOccured = false;
                    model.addAttribute("news", newsService.getAllNews());
                    result.setResult(new ModelAndView("partial"));
                    break;
                }
            }
        }
    }).start();
    return result;
}

堆栈跟踪:

代码语言:javascript
复制
Exception in thread "Thread-13" java.util.ConcurrentModificationException
at java.util.ArrayList.sort(ArrayList.java:1456)
at com.newsapp.SpringNews.Service.NewsService.getAllNews(NewsService.java:25)
at com.newsapp.SpringNews.Controller.ViewController$1.run(ViewController.java:125)
at java.lang.Thread.run(Thread.java:748)
EN

回答 1

Stack Overflow用户

发布于 2017-07-29 21:51:45

您可以使用arraylist来同时写入数据和获取数据。在这一点上,ArrayList将失败。您需要一个管理并发访问的列表实现:

你可以像这样创建你的列表: ArrayList<>());

  • or
  • ( List<..> list=Collections.synchronizedList你可以像http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CopyOnWriteArrayList.html

一样使用真正的并发列表

无论如何,像这样拉是非常危险的-你会遇到网络超时,你还会在while true上用很多线程循环杀死你的服务器(在你的代码中没有等待!)。

一种更好的方法是使用ServerSideEvent (SSE)和事件系统。

这里有一篇关于如何使用spring https://golb.hplar.ch/p/Server-Sent-Events-with-Spring做到这一点的文章

它管理一个事件系统,使监听器和生产者完全解耦。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45389734

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档