/*
 * Copyright 2014-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.session.data;

import java.util.HashMap;
import java.util.Map;

import org.springframework.context.ApplicationListener;
import org.springframework.session.events.AbstractSessionEvent;

public class SessionEventRegistry implements ApplicationListener<AbstractSessionEvent> {
	private Map<String, AbstractSessionEvent> events = new HashMap<>();
	private Map<String, Object> locks = new HashMap<>();

	public void onApplicationEvent(AbstractSessionEvent event) {
		String sessionId = event.getSessionId();
		this.events.put(sessionId, event);
		Object lock = getLock(sessionId);
		synchronized (lock) {
			lock.notifyAll();
		}
	}

	public void clear() {
		this.events.clear();
		this.locks.clear();
	}

	public boolean receivedEvent(String sessionId) throws InterruptedException {
		return waitForEvent(sessionId) != null;
	}

	@SuppressWarnings("unchecked")
	public <E extends AbstractSessionEvent> E getEvent(String sessionId)
			throws InterruptedException {
		return (E) waitForEvent(sessionId);
	}

	@SuppressWarnings("unchecked")
	private <E extends AbstractSessionEvent> E waitForEvent(String sessionId)
			throws InterruptedException {
		Object lock = getLock(sessionId);
		synchronized (lock) {
			if (!this.events.containsKey(sessionId)) {
				lock.wait(10000);
			}
		}
		return (E) this.events.get(sessionId);
	}

	private Object getLock(String sessionId) {
		synchronized (this.locks) {
			Object lock = this.locks.get(sessionId);
			if (lock == null) {
				lock = new Object();
				this.locks.put(sessionId, lock);
			}
			return lock;
		}
	}
}

@@ -705,16 +705,106 @@
 til.Map;
+%0Aimport java.util.concurrent.ConcurrentHashMap;%0Aimport java.util.concurrent.ConcurrentMap;
 %0A%0Aimport
@@ -1077,32 +1077,42 @@
 p%3C%3E();%0A%09private 
+Concurrent
 Map%3CString, Obje
@@ -1119,32 +1119,42 @@
 ct%3E locks = new 
+Concurrent
 HashMap%3C%3E();%0A%0A%09p
@@ -2127,189 +2127,72 @@
 %7B%0A%09%09
-synchronized (this.locks) %7B%0A%09%09%09Object lock = this.locks.get(sessionId);%0A%09%09%09if (lock == null) %7B%0A%09%09%09%09lock = new Object();%0A%09%09%09%09this.locks.put(sessionId, lock);%0A%09%09%09%7D%0A%09%09%09return lock;%0A%09%09%7D
+return this.locks.computeIfAbsent(sessionId, k -%3E new Object());
 %0A%09%7D%0A

Simplify `Map.get` and conditional calls