I am running multiple JUnit tests in parallel classes using Maven. I have clean up tasks that need to happen after all JUnit tests run. To handle this clean up, I am adding a shut down hook to a few tests. The shut down hook correctly executes when I am not running parallel, but I don't see the output (see example) from the shut down hook when I run parallel. Is there something I am doing wrong? Does the JVM exit using System.exit
when executing in JUnit tests in parallel?
According to the Surfire documentation documentation, the parallel threads are executed in the same process, so I would expect Runtime.getRuntime to be the same process even if it is called between different tests and threads. Maven Surfire Plugin - Fork Options and Parallel Test Execution
The important thing to remember with the parallel option is: the concurrency happens within the same JVM process. That is efficient in terms of memory and execution time, but you may be more vulnerable towards race conditions or other unexpected and hard to reproduce behavior.
Here is an example from my unit test:
@Test
public void test()
{
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
System.out.println("Test clean up triggered");
}
});
}
Here is the relevant portion of my pom:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<parallel>classes</parallel>
<threadCount>10</threadCount>
</configuration>
</plugin>
Edited:
The problem is fixed when I add my shut down hook in the @BeforeClass
method. When I add it in the @Test
method, I have the problem. I would like to be able to add the hook at any time.