Move code to core-java-modules/core-java-concurrency-advanced-3Add

Add missing 'Unit' in test name
This commit is contained in:
mthomas
2020-03-31 04:43:06 -05:00
parent 9df752d3ed
commit 92ce5cb8d4
2 changed files with 6 additions and 6 deletions

View File

@@ -0,0 +1,34 @@
package com.baeldung.atomicstampedreference;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;
public class SafeAccount {
private AtomicInteger stamp = new AtomicInteger(0);
private AtomicStampedReference<Integer> balance = new AtomicStampedReference<>(0, 0);
public int getBalance() {
return this.balance.get(new int[1]);
}
public int getStamp() {
int[] stamps = new int[1];
this.balance.get(stamps);
return stamps[0];
}
public boolean deposit(int funds) {
int[] stamps = new int[1];
int current = this.balance.get(stamps);
int newStamp = this.stamp.incrementAndGet();
return this.balance.compareAndSet(current, current + funds, stamps[0], newStamp);
}
public boolean withdrawal(int funds) {
int[] stamps = new int[1];
int current = this.balance.get(stamps);
int newStamp = this.stamp.incrementAndGet();
return this.balance.compareAndSet(current, current - funds, stamps[0], newStamp);
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.atomicstampedreference;
import org.junit.Assert;
import org.junit.Test;
public class ThreadSafeAccountUnitTest {
@Test
public void givenMultiThread_whenSafeAccount_thenSetBalance() throws InterruptedException {
SafeAccount account = new SafeAccount();
Thread t = new Thread(() -> {
while (!account.withdrawal(100))
Thread.yield();
});
t.start();
Assert.assertTrue(account.deposit(100));
t.join(1_000);
Assert.assertFalse(t.isAlive());
Assert.assertSame(0, account.getBalance());
}
}