Background: I am running automation tests in parallel. Multiple browsers get launch in the same number of threads i.e. 1 browser is 1 thread, using forking in pom.xml.
Below plugin in pom.xml creates an equal number of Parallel**IT.class as thread(fork) count is.
All these classes are executed at once parallel. So, it seems whenever I create a volatile variable or AtomicInteger each thread creates its own of these and so concept sharing a variable across multiple threads is not working.
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven.failsafe.plugin}</version>
<configuration>
<systemPropertyVariables>
<webdriver.base.url>${webdriver.base.url}</webdriver.base.url>
</systemPropertyVariables>
<argLine>
-javaagent:${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar
</argLine>
<forkCount>5</forkCount>
<reuseForks>true</reuseForks>
<includes>
<include>**/Parallel*IT.class</include>
</includes>
<perCoreThreadCount>true</perCoreThreadCount>
<properties>
<property>
<name>listener</name>
<value>ru.yandex.qatools.allure.junit.AllureRunListener</value>
</property>
</properties>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
I want only 1 thread to access the "prepare test data" function and set flag to false, when other threads see flag as false they do not attempt to prepare test data.
I am following a tutorial https://www.youtube.com/watch?v=WH5UvQJizH0 to implement synchronization using a volatile variable. Maybe I am making some mistake, but all threads are printing System.out.println("Preparing test data");
Try 1: Volatile and Synchronization
volatile boolean flag = false;
public synchronized void setFlagTofalse(){
System.out.println("Inside sync block");
this.flag = true;
}
// works before class only once
private EventHandler<TestRunStarted> prepareTestData = event -> {
if(flag==false) {
System.out.println("Preparing test data");
setFlagTofalse();
}
};
Try 2: Atomic and Synchronization
AtomicInteger flag = new AtomicInteger(0);
private EventHandler<TestRunStarted> prepareTestData = event -> {
if(flag.get()==0) {
System.out.println("Preparing test data");
value.incrementAndGet();
}