[英]Using the same EntityManager across multiple threads
我有一個JPA環境,其中有一個應用程序管理的EntityManager。 我手動創建了entityManagerFactory,並從中創建了EntityManager。 我想在多個線程中使用相同的EntityManager。 該文檔說EntityManager不是線程安全的,但是我所有的操作只能通過EntityManager進行讀取,而不會進行任何寫操作。 我還對緩存中的數據設置了超時以確保一致性。 在這種情況下,可以跨線程使用EntityManager的相同實例嗎? 還是在線程之間使用同一EntityManager會產生任何副作用/錯誤數據。
謝謝
可以肯定,只要鎖定EntityManager
在任何你通過使用實例synchronized
。
所以不要寫
em.persist(...);
寫
synchronized (em) {
em.persist(...);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.