Issue
Trying to test that one of my classes can handle being accessed on multiple threads. I have a JUnit test in which I have created a class to implement Runnable
and run my class.
When I run execute, it reaches a line in the run() method and just exits on that thread without reporting back any issue, I've wrapped it with Try-Catch(Throwable), but still no sign of what's gone wrong.
Here's my code:
class ConcurrencyTests {
class ConcurrentComponentTracker implements Runnable {
private String component;
ConcurrentComponentTracker(String component) {
this.component = component;
}
@Override
public void run() {
try {
System.out.printf("Component to track: [%s]\n", component);
ParserHandler parserHandler = new ParserHandler();
System.out.println(parserHandler.componentTracker(component));
}
catch (Throwable t) {
t.printStackTrace();
}
}
}
@Test
void runRunner() {
ExecutorService executor = Executors.newFixedThreadPool(4);
String[] componentsToTrack = {"x", "y", "z"};
executor.execute(new ConcurrentComponentTracker(componentsToTrack[0]));
executor.execute(new ConcurrentComponentTracker(componentsToTrack[1]));
executor.execute(new ConcurrentComponentTracker(componentsToTrack[2]));
}
}
And the output:
Component to track: [x]
Component to track: [y]
Component to track: [z]
It just seems to exit on the ParserHandler instantiation line without reporting anything. When attempting to debug and step into that line, it just skips to the end without letting my inspect the ParserHandler class instantiation.
Solution
Whomever answered in a comment and then deleted it solved the problem for me. My main JUnit thread wasn't waiting for the other threads to finish. So I tacked on these lines to the end and it worked as expected:
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
}
catch (InterruptedException e) {
e.printStackTrace();
}
Answered By - notfreshprince
Answer Checked By - Willingham (JavaFixing Volunteer)