Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

ConcurrentModificationException on a synchronized set

807607Sep 18 2006 — edited Dec 12 2006
Thanks to anyone who can help me here - I'm very confused.

I have a class WebAppUtility that looks like this:

private static Set<HttpSession> openSessions = Collections
			.synchronizedSet(new HashSet<HttpSession>());
	
	public static void addSession(HttpSession session) {
		synchronized(openSessions){
			openSessions.add(session);
		}
	}
	
	public static boolean removeSession(HttpSession session) {
		synchronized(openSessions){
			return openSessions.remove(session);
		}
	}
	public static Set<String> getLoggedInUsers() throws Exception {
		Set<String> set = new HashSet<String>();
		synchronized (openSessions) {
			for(Iterator i = openSessions.iterator(); i.hasNext();){
				HttpSession session = (HttpSession)i.next();
                              //grab attribute from session here and stick in "set"
			}
		}
		return set;
	}
Somehow when I have many users logging in and out I'm getting a ConcurrentModificationException under the getLoggedInUsers method:

java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:787)
at java.util.HashMap$KeyIterator.next(HashMap.java:823)
at com.studentuniverse.utility.WebAppUtility.getLoggedInUsers(WebAppUtility.java:68)

Line 68 is the one that looks like:
HttpSession session = (HttpSession)i.next();
Am I misusing the synchronizedSet in some way? Please guide me to proper threaded Set usage! Thank you very much.

_kris
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 9 2007
Added on Sep 18 2006
5 comments
1,771 views