Merge pull request #4000 from eugenp/issue-2433

fix volatile test
This commit is contained in:
Loredana Crusoveanu 2018-04-14 19:04:32 +03:00 committed by GitHub
commit 42360c980d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 17 additions and 33 deletions

View File

@ -1,55 +1,36 @@
package com.baeldung.concurrent.volatilekeyword;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.*;
public class SharedObjectManualTest {
private SharedObject sharedObject;
private int valueReadByThread2;
private int valueReadByThread3;
@Before
public void setUp() {
sharedObject = new SharedObject();
}
@Test
public void whenOneThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException {
SharedObject sharedObject = new SharedObject();
Thread writer = new Thread(() -> sharedObject.increamentCount());
writer.start();
Thread.sleep(100);
Thread readerOne = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
valueReadByThread2 = sharedObject.getCount();
int valueReadByThread2 = sharedObject.getCount();
assertEquals(1, valueReadByThread2);
});
readerOne.start();
Thread readerTwo = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
valueReadByThread3 = sharedObject.getCount();
int valueReadByThread3 = sharedObject.getCount();
assertEquals(1, valueReadByThread3);
});
readerTwo.start();
assertEquals(1, valueReadByThread2);
assertEquals(1, valueReadByThread3);
}
@Test
public void whenTwoThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException {
SharedObject sharedObject = new SharedObject();
Thread writerOne = new Thread(() -> sharedObject.increamentCount());
writerOne.start();
Thread.sleep(100);
@ -58,14 +39,17 @@ public class SharedObjectManualTest {
writerTwo.start();
Thread.sleep(100);
Thread readerOne = new Thread(() -> valueReadByThread2 = sharedObject.getCount());
Thread readerOne = new Thread(() -> {
int valueReadByThread2 = sharedObject.getCount();
assertEquals(2, valueReadByThread2);
});
readerOne.start();
Thread readerTwo = new Thread(() -> valueReadByThread3 = sharedObject.getCount());
Thread readerTwo = new Thread(() -> {
int valueReadByThread3 = sharedObject.getCount();
assertEquals(2, valueReadByThread3);
});
readerTwo.start();
assertEquals(2, valueReadByThread2);
assertEquals(2, valueReadByThread3);
}
}