2017-07-29 112 views
1

基本上我有一個簡單的新聞應用程序,現在我想有新聞列表自動更新所有用戶每當有人添加或刪除新聞時,它有點工作,但有時我得到ConcurrentModificationException,我只需要編寫此方法的幫助:春季長輪詢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) 
+0

你指定在哪一行發生異常? – Lino

+0

它發生在newsService類和getAllnews()方法中,但沒關係,因爲我認爲我寫這個poll()方法錯了,問題可能就在那裏...... –

+0

你可以添加堆棧跟蹤到你的問題嗎?因爲我的方法沒有看到任何錯誤 – Lino

回答

0

您使用ArrayList將數據寫入和concurently獲取數據。 ArrayList將會失敗。你需要的是管理concurent訪問List實現:

無論如何,拉一樣,是非常危險的 - 你會打網絡超時,你還會殺了你有很多線程的循環上,而真正的服務器(上你的代碼沒有等待!)。

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

這裏做的是帶彈簧https://golb.hplar.ch/p/Server-Sent-Events-with-Spring

它管理事件系統,使聽衆和生產完全分離後。

+0

感謝您的建議,但我希望儘可能簡單,您是否認爲可以對其進行重構以使其更好,更有效? –

+0

已編輯添加conware問題。 – wargre