基本上我有一个简单的新闻应用程序,现在我想有新闻列表自动更新为所有用户,每当有人添加或删除新闻,它有点工作,但有时我得到ConcurrentModificationException,我只是需要在编写此方法的帮助:
@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;
}堆栈跟踪:
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)发布于 2017-07-29 21:51:45
您可以使用arraylist来同时写入数据和获取数据。在这一点上,ArrayList将失败。您需要一个管理并发访问的列表实现:
你可以像这样创建你的列表: ArrayList<>());
一样使用真正的并发列表
无论如何,像这样拉是非常危险的-你会遇到网络超时,你还会在while true上用很多线程循环杀死你的服务器(在你的代码中没有等待!)。
一种更好的方法是使用ServerSideEvent (SSE)和事件系统。
这里有一篇关于如何使用spring https://golb.hplar.ch/p/Server-Sent-Events-with-Spring做到这一点的文章
它管理一个事件系统,使监听器和生产者完全解耦。
https://stackoverflow.com/questions/45389734
复制相似问题