Is there any difference between AtomicReference and Synchronized?
E.G.
public class Internet {
AtomicReference address;
public String g
A synchronized
method/block blocks all access to that method/block from other threads while one thread is performing the method.
An Atomic...
can be accessed by many threads at once - there are usually CAS access methods available for them to help with high-speed access.
As such - they are completely different but they can sometimes be used to solve parallel accessibility issues.
These two classes use the two different methods to return a steadily increasing number such that the same number will never be delivered twice. The AtomicInteger
version will run faster in a high-load environment. The one using synchronized
will work in Java 4 and older.
public class Incremental1 {
private AtomicInteger n = new AtomicInteger();
public Integer nextNumber() {
// Use the Atomic CAS function to increment the number.
return n.getAndIncrement();
}
}
public class Incremental2 {
private int n = 0;
public synchronized Integer nextNumber() {
// No two threads can get in here at the same time.
return n++;
}
}