I have a suite of tests (4 so far) that share a common base class. One of the methods is a @BeforeClass setup() method.
This method has a synchronized block that should run ONLY once. The structure is:
public class ServiceTestBase extends TestNgBase {
public static volatile boolean serverInitialized = false;
public void setup() throws InitializationException {
synchronized (ServiceTestBase.class) {
if (ServiceTestBase.serverInitialized == false) {
System.out.println("ProcessName:" + ManagementFactory.getRuntimeMXBean().getName());
System.out.println("Seeding server configuration: instanceId = " + this);
.... //Do stuff only once
ServiceTestBase.serverInitialized = true; //Set Flag to skip
}
The mvn command is:
mvn test -D test=ServiceTest* -P wp-dev
Based on the output below, all instances are running in the same process and *should* be using the same class loader (right?) and thus be synchronizing on the same Class object, yet the code runs 4 times, once for each of the 4 test classes that inherit from ServiceTestBase.
ProcessName:55372@workstation1
Seeding server configuration: instanceId = ServiceTestEntitlements@354dc2e6
.... Doing some stuff for the first time
ProcessName:55372@workstation1
Seeding server configuration: instanceId = ServiceTestDatabase@67409450
.... Doing some stuff for the second time ... SHOULD NOT DO THIS
ProcessName:55372@workstation1
Seeding server configuration: instanceId = ServiceTestUpdate@5413e967
.... Doing some stuff for the third time ... SHOULD NOT DO THIS
ProcessName:55372@workstation1
Seeding server configuration: instanceId = ServiceTestHealth@71b1c270
.... Doing some stuff for the fourth time ... SHOULD NOT DO THIS
I can't see what I'm missing. I tried just creating a static lock object to synchronize on instead of the Class object itself with the same results.
Any insight is MUCH appreciated.