Classes from java.util.concurrent.atomic package allow us to use single variables concurrently without blocking access to them. The typical usage example is increasing the counter that is modified by many threads.
Instead of using the synchronized block, that blocks the access to the counter:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private long counter = 0; | |
private final Object mutex = new Object(); | |
public void incrementCounter() { | |
synchronized (mutex) { | |
counter++; | |
} | |
} |
or the synchronized method equivalent to the block with 'synchronized(this)':
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public synchronized void incrementCounter() { | |
counter++; | |
} |
you can use AtomicLong class, that guarantees non-blocking access:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private AtomicLong counter = new AtomicLong(); | |
public void incrementCounter() { | |
counter.incrementAndGet(); | |
} |
Method incrementAndGet() besides incrementing counter's value, returns it.
Another typical usage is providing non-blocking access to an object, that is shared by many threads. Instead of synchronizing getter/setters methods:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private Object resource = new Object(); | |
public synchronized Object getResource() { | |
return resource; | |
} | |
public synchronized void setResource(Object resource) { | |
this.resource = resource; | |
} |
you can use AtomicReference class:
No comments:
Post a Comment