Thread-safety guarantees that no two threads can simultaneously access or modify some shared data. However, if two or more operations need to be performed safely, it becomes necessary to enforce atomicity. It is possible for two threads to read some shared value, independently perform operations on it and induce a race condition while storing the final result. Programmers usually For example, programmers sometimes assume that a thread-safe Collection
does not require explicit synchronization which can be is a misleading practicethought. It follows that using a thread-safe Collection
by itself may not ensure program correctness.
Noncompliant Code Example
This noncompliant code example is comprised of an ArrayList
collection which is non-thread-safe by default. There is, however, a way around this drawback. Most thread-unsafe classes have a synchronized thread-safe version, for example, Collections.synchronizedList
is a good substitute for ArrayList
and Collections.synchronizedMap
is a good alternative to HashMap
. One The atomicity pitfall described in the coming lines, remains to be addressed even when the particular Collection
offers thread-safety benefits.
Wiki Markup |
---|
The operations within a thread's {{run()}} method are non-atomic. That is, it is possible for the first thread to operate on data that it does not expect. The superfluous data may be fed in by other threads whilst the first thread is still executing. Conversely, as the {{toArray()}} method produces a copy of the parameter, it is possible that the first thread operateswill operate on stale data \[[JavaThreads 04|AA. Java References#JavaThreads 04]\]. The code's output, consisting of varying array lengths, signifiesindicates a race condition. Such omissions can be pernicious in methods that use complex mathematical formulas. |
Code Block |
---|
|
class RaceCollection implements Runnable {
private List<InetAddress> ips = Collections.synchronizedList(new ArrayList<InetAddress>());
public void addIPAddress(InetAddress ia) {
synchronized(ips) {
ips.add(ia);
}
}
public void removeIPAddress(InetAddress ia) {
synchronized(ips) {
ips.remove(ia);
}
}
public void nonAtomic() throws InterruptedException {
InetAddress[] ia;
synchronized(ips) {
ia = (InetAddress[]) ips.toArray(new InetAddress[0]);
}
// This statement should be in the synchronized block above
System.out.println("Number of IPs: " + ia.length);
}
public void run() {
try {
addIPAddress(InetAddress.getLocalHost());
nonAtomic();
} catch (UnknownHostException e) { /* Forward to handler */ }
catch (InterruptedException e) { /* Forward to handler */ }
}
public static void main(String[] args) {
RaceCollection rc1 = new RaceCollection();
for(int i = 0;i<2; i < 2; i++) {
new Thread(rc1).start();
}
}
}
|
Compliant Solution
Wiki Markup |
---|
To eliminate the race condition, ensure atomicity. This can be achieved by including all statements that use the array list within the synchronized block. This technique is also called client-side locking. \[[Goetz 06|AA. Java References#Goetz 06]\] |
...
Code Block |
---|
|
class CompositeCollection implements Runnable {
private List<InetAddress> ips = Collections.synchronizedList(new ArrayList<InetAddress>());
public CompositeCollection(List<InetAddress> list) {
this.ips = list;
}
public synchronized void addIPAddress(InetAddress ia) {
ips.add(ia);
}
//* otherOther methods */
public synchronized void atomic() throws InterruptedException {
InetAddress[] ia;
ia = (InetAddress[]) ips.toArray(new InetAddress[0]);
System.out.println("Number of IPs: " + ia.length);
}
}
|
...
Code Block |
---|
|
public class KeyedCounter {
private Map<String, Integer> map =
Collections.synchronizedMap(new HashMap<String, Integer>());
public void increment(String key) {
Integer old = map.get(key);
int value = (old == null) ? 1 : old.intValue() + 1;
map.put(key, value);
}
public Integer getCount(String key) {
return map.get(key);
}
}
|
...
Code Block |
---|
|
public class KeyedCounter {
private final ConcurrentMap<String, AtomicInteger> map =
new ConcurrentHashMap<String, AtomicInteger>();
public void increment(String key) {
AtomicInteger value = new AtomicInteger(0);
AtomicInteger old = map.putIfAbsent(key, value);
if (old != null) {
value = old;
}
value.incrementAndGet(); // incrementIncrement the value atomically
}
public Integer getCount(String key) {
AtomicInteger value = map.get(key);
return (value == null) ? null : value.get();
}
}
|
...