The JDK provides a set of thread safe classes such as ConcurrentHashMap, ConcurrentLinkedQueue, and AtomicInteger.
Are these classes required for synchronization on thisto implement their thread-safe behavior?
Provided that they can perform our own synchronized operations on these objects and mix them with the built-in ones?
In other words, it is safe:
ConcurrentMap<Integer, Account> accounts
= new ConcurrentHashMap<Integer, Account>();
synchronized(accounts) {
if (!accounts.containsKey(id)) {
Account account = new Account();
accounts.put(id, account);
}
}
And in another thread
accounts.get(id);
Please note that the simple synchronized block above can probably be replaced with putIfAbsent (), but I can see other cases where synchronizing on an object can be useful.