2013-02-25 26 views
1

我已經在Glassfish 3.1.2.2ConcurrentModificationException的雖然@Lock(LockType.READ)註釋

,並通過閱讀()我得到了下面的代碼ConcurrentModificationException的Java EE應用程序:

private Set<MonitoredService> connectedServices = new HashSet<MonitoredService>(); 

@Override @Lock(LockType.WRITE) 
public void addConnectedService(MonitoredService service) { 
    if (!connectedServices.contains(service)) { 
     connectedServices.add(service); 
    } 
} 

@Override @Lock(LockType.READ) 
public Set<MonitoredService> getConnectedServices() { 
    return Collections.unmodifiableSet(new HashSet<MonitoredService>(connectedServices)); 
} 

我曾想過Lock註釋關心集合上的同步訪問?

+0

你能顯示ConcurrentModificationException的堆棧跟蹤嗎? Lock的包是什麼? – gogognome 2013-02-25 13:07:12

+0

謝謝,我會將HashMap更改爲Collections.synchronizedSet(..)。沒有Glassfish鎖定。 – DSmelanskij 2013-02-25 13:24:14

+0

您當前的方式在讀取主要訪問模式的情況下可提供更高的吞吐量。如果我是你,我會更努力工作:) – 2013-02-25 13:44:47

回答

1

僅僅因爲該功能是同步的並不意味着實際的集合是同步的。你無法保證其他東西不會修改connectedServices,即使它在單身人士身上。如果你真的需要一個同步採集使用:

Collections.synchronizedSet(...); 
+0

這是一個私人收藏,所以保證就在那裏。 – 2013-02-25 13:18:13

+0

hm好的,我曾認爲Glassfish令人驚歎,它沒有同步設置:) 謝謝! – DSmelanskij 2013-02-25 13:23:19

+0

@MarkoTopolnik不是真的,你可以使用反射和私人消失。當然,這是關於反思迂腐:) – Woot4Moo 2013-02-25 13:35:43