BAEL-1029 - deep20jain@gmail.com - An Introduction to Atomic Variables in Java (#2269)

* Adding test classes for java atomic variables

* Updating counter with atomic integer

* Adding reason for ignoring test
This commit is contained in:
deep20jain
2017-07-18 09:38:19 +05:30
committed by Zeger Hendrikse
parent 2ce547d4cd
commit afa82c0d28
4 changed files with 105 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
package com.baeldung.concurrent.atomic;
public class SafeCounterWithLock {
int counter;
public int getValue() {
return counter;
}
public synchronized void increment() {
counter++;
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.concurrent.atomic;
import java.util.concurrent.atomic.AtomicInteger;
public class SafeCounterWithoutLock {
AtomicInteger counter = new AtomicInteger(0);
public int getValue() {
return counter.get();
}
public void increment() {
while(true) {
int existingValue = getValue();
int newValue = existingValue + 1;
if(counter.compareAndSet(existingValue, newValue)) {
return;
}
}
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.concurrent.atomic;
public class UnsafeCounter {
int counter;
public int getValue() {
return counter;
}
public void increment() {
counter++;
}
}