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:
committed by
Zeger Hendrikse
parent
2ce547d4cd
commit
afa82c0d28
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.concurrent.atomic;
|
||||
|
||||
public class SafeCounterWithLock {
|
||||
int counter;
|
||||
|
||||
public int getValue() {
|
||||
return counter;
|
||||
}
|
||||
|
||||
public synchronized void increment() {
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.concurrent.atomic;
|
||||
|
||||
public class UnsafeCounter {
|
||||
int counter;
|
||||
|
||||
public int getValue() {
|
||||
return counter;
|
||||
}
|
||||
|
||||
public void increment() {
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user