Skip to content
This repository has been archived by the owner on Apr 21, 2023. It is now read-only.

Fixed the synchronization strategy in ExecutorServiceProvider #1470

Merged
merged 1 commit into from
May 8, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@
*/
package org.eclipse.xtext.ide;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.eclipse.xtext.util.DisposableRegistry;
import org.eclipse.xtext.util.IDisposable;

import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
Expand All @@ -25,33 +26,26 @@
* <p>
* In some situations it is necessary to use multiple instances of executor services in order to avoid deadlocks. That
* can be achieved with the {@link #get(String)}�method, which will return a different instance for each key.
* </p>
*/
@Singleton
public class ExecutorServiceProvider implements Provider<ExecutorService>, IDisposable {

private final Map<String, ExecutorService> instanceCache = Collections
.synchronizedMap(new HashMap<String, ExecutorService>());

@Inject
public void registerTo(DisposableRegistry disposableRegistry) {
disposableRegistry.register(this);
}

private final Map<String, ExecutorService> instanceCache = Maps.newHashMapWithExpectedSize(3);

@Override
public ExecutorService get() {
return get(null);
}

public ExecutorService get(String key) {
ExecutorService result = instanceCache.get(key);
if (result == null) {
synchronized (instanceCache) {
result = instanceCache.get(key);
if (result == null) {
result = createInstance(key);
instanceCache.put(key, result);
}
}
}
return result;
return instanceCache.computeIfAbsent(key, this::createInstance);
}

protected ExecutorService createInstance(String key) {
Expand All @@ -60,9 +54,11 @@ protected ExecutorService createInstance(String key) {

@Override
public void dispose() {
for (ExecutorService executorService : instanceCache.values()) {
executorService.shutdown();
synchronized (instanceCache) {
for (ExecutorService executorService : instanceCache.values()) {
executorService.shutdown();
}
instanceCache.clear();
}
instanceCache.clear();
}
}