2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2023 Nordix Foundation.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pap.main.comm;
24 import org.junit.jupiter.api.AfterEach;
25 import org.junit.jupiter.api.BeforeEach;
28 * Super class for tests that run a background thread.
30 public abstract class Threaded {
33 * Max time to wait, in milliseconds, for a thread to terminate or for a message to be
36 public static final long MAX_WAIT_MS = 5000;
39 * The current background thread.
41 private Thread thread;
44 * Indicates that a test is about to begin.
46 * @throws Exception if an error occurs
49 public void setUp() throws Exception {
54 * Invokes the "stopper" function to tell the background thread to exit and then waits
55 * for it to terminate.
57 * @throws Exception if an error occurs
60 public void tearDown() throws Exception {
66 * Signals the background thread to stop.
68 * @throws Exception if an error occurs
70 protected abstract void stopThread() throws Exception;
73 * Starts a background thread.
75 * @param runner what should be executed in the background thread
76 * @throws IllegalStateException if a background thread is already running
78 protected void startThread(Runnable runner) {
80 throw new IllegalStateException("a background thread is already running");
83 thread = new Thread(runner);
84 thread.setDaemon(true);
89 * Interrupts the background thread.
91 protected void interruptThread() {
96 * Waits for the background thread to stop.
98 * @return {@code true} if the thread has stopped, {@code false} otherwise
99 * @throws InterruptedException if this thread is interrupted while waiting
101 protected boolean waitStop() throws InterruptedException {
102 if (thread != null) {
103 Thread thread2 = thread;
106 thread2.join(MAX_WAIT_MS);
108 return !thread2.isAlive();