2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.pap.main.comm;
23 import org.junit.After;
24 import org.junit.Before;
27 * Super class for tests that run a background thread.
29 public abstract class Threaded {
32 * Max time to wait, in milliseconds, for a thread to terminate or for a message to be
35 public static final long MAX_WAIT_MS = 5000;
38 * The current background thread.
40 private Thread thread;
43 * Indicates that a test is about to begin.
45 * @throws Exception if an error occurs
48 public void setUp() throws Exception {
53 * Invokes the "stopper" function to tell the background thread to exit and then waits
54 * for it to terminate.
56 * @throws Exception if an error occurs
59 public void tearDown() throws Exception {
65 * Signals the background thread to stop.
67 * @throws Exception if an error occurs
69 protected abstract void stopThread() throws Exception;
72 * Starts a background thread.
74 * @param runner what should be executed in the background thread
75 * @throws IllegalStateException if a background thread is already running
77 protected void startThread(Runnable runner) {
79 throw new IllegalStateException("a background thread is already running");
82 thread = new Thread(runner);
83 thread.setDaemon(true);
88 * Interrupts the background thread.
90 protected void interruptThread() {
95 * Waits for the background thread to stop.
97 * @return {@code true} if the thread has stopped, {@code false} otherwise
98 * @throws InterruptedException if this thread is interrupted while waiting
100 protected boolean waitStop() throws InterruptedException {
101 if (thread != null) {
102 Thread thread2 = thread;
105 thread2.join(MAX_WAIT_MS);
107 return !thread2.isAlive();