aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/language-web/src/test/java/tools/refinery/language/web/tests/AwaitTerminationExecutorServiceProvider.java
blob: 630549d46ec26a229a69c62f30e7b0d0e5ae9f9f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
 * SPDX-FileCopyrightText: 2021-2023 The Refinery Authors <https://refinery.tools/>
 *
 * SPDX-License-Identifier: EPL-2.0
 */
package tools.refinery.language.web.tests;

import com.google.inject.Singleton;
import tools.refinery.language.web.xtext.VirtualThreadExecutorServiceProvider;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;

@Singleton
public class AwaitTerminationExecutorServiceProvider extends VirtualThreadExecutorServiceProvider {
	private final List<RestartableCachedThreadPool> servicesToShutDown = new ArrayList<>();

	@Override
	protected ExecutorService createInstance(String key) {
		var instance = new RestartableCachedThreadPool(() -> super.createInstance(key));
		synchronized (servicesToShutDown) {
			servicesToShutDown.add(instance);
		}
		return instance;
	}

	public void waitForAllTasksToFinish() {
		synchronized (servicesToShutDown) {
			for (var executorService : servicesToShutDown) {
				executorService.waitForAllTasksToFinish();
			}
		}
	}

	@Override
	public void dispose() {
		super.dispose();
		synchronized (servicesToShutDown) {
			for (var executorService : servicesToShutDown) {
				executorService.waitForTermination();
			}
			servicesToShutDown.clear();
		}
	}
}