initial commit for BAEL-5185 (#11484)

* initial commit for BAEL-5185

* fixed issues

* fixed issues

* Added Junit test case

Co-authored-by: Vartika_Nigam <Vartika_Nigam@dellteam.com>
This commit is contained in:
Vartika Nigam 2021-12-30 07:43:09 +05:30 committed by GitHub
parent 3321472ee7
commit eb49143a48
2 changed files with 60 additions and 0 deletions

View File

@ -0,0 +1,47 @@
package com.baeldung.volatilekeywordthreadsafety;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
public class VolatileVarNotThreadSafe {
private static final Logger LOG = LoggerFactory.getLogger(VolatileVarNotThreadSafe.class);
private static volatile int count = 0;
private static final int MAX_LIMIT = 1000;
public static void increment() {
count++;
}
public static int getCount() {
return count;
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for(int index=0; index<MAX_LIMIT; index++) {
increment();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for(int index=0; index<MAX_LIMIT; index++) {
increment();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
LOG.info("value of counter variable: "+count);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.volatilekeywordthreadsafety;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class VolatileVarNotThreadSafeUnitTest {
@Test
public void whenCalledMainMethod_thenIncrementCount() throws InterruptedException {
VolatileVarNotThreadSafe.main(null);
Assertions.assertTrue(VolatileVarNotThreadSafe.getCount() > 0);
}
}