Quiz: Thread Safety in Java: Thread-Safe Classes and Collections
Study the lesson first: Thread Safety in Java: Thread-Safe Classes and Collections
Total: 8 questions
1. What is thread safety in Java?
What is thread safety in Java?
Thread safety is the property of a class to behave correctly when several threads access the same object at the same time, without any extra synchronization by the calling code. The result must be the same as for some sequential execution of those calls: no updates are lost, and readers never see the object in a half-updated state.
The problem comes only from shared mutable state. A class without fields, a class whose fields are all final and of immutable types, and a method's local variables are thread-safe without a single lock. The term applies to a class as a whole: the JDK documentation calls ConcurrentHashMap, AtomicInteger and StringBuffer thread-safe, but not ArrayList, HashMap or StringBuilder.
2. How do you make a class thread-safe in Java?
How do you make a class thread-safe in Java?
There are six main approaches:
- No shared state (stateless) - the class works only with parameters and local variables.
- Immutability - the state is set in the constructor and never changes:
String,Integer,LocalDate. - Thread confinement - the object is reachable by one thread only;
ThreadLocalgives each thread its own copy (in thread pools it must be cleaned up withremove()). - Synchronization - methods and blocks that touch shared fields are
synchronizedon one monitor. - Atomic classes -
AtomicInteger,AtomicLong,AtomicReference; only one variable is atomic. - Thread-safe collections -
ConcurrentHashMap,CopyOnWriteArrayList,BlockingQueue.
The first three remove the cause of the race; the rest protect shared mutable data. In practice they are combined: a service without fields accepts immutable objects and keeps its cache in a ConcurrentHashMap.
3. How do you create an immutable class in Java, and why is it thread-safe?
How do you create an immutable class in Java, and why is it thread-safe?
An immutable object can't change after it is created, so it can be passed between threads without synchronization. Five rules:
- declare the class
final; - make all fields
private final; - provide no setters or other methods that change fields;
- copy mutable objects received in the constructor (lists, arrays,
Date) - a defensive copy, for exampleList.copyOf(items); - don't let getters hand out mutable internal objects.
A record satisfies the first three rules automatically, but stores a list it receives as is - make the defensive copy in a compact constructor. On top of that, JLS 17.5 guarantees that after the constructor finishes, any thread sees the correct values of final fields, as long as the constructor didn't let this escape.
4. What is AtomicInteger, and how does CAS (compare-and-set) work?
What is AtomicInteger, and how does CAS (compare-and-set) work?
AtomicInteger from java.util.concurrent.atomic (Java 5) performs operations on a single int atomically and without locks: incrementAndGet() returns the new value, getAndIncrement() the old one, and get()/set() give visibility like volatile.
Under the hood it uses the CPU's CAS instruction: compareAndSet(expect, update) writes the new value only if the current one still equals the expected one, and returns true or false. Any operation on a single variable can be made atomic with a CAS loop or with updateAndGet(fn); on contention the function is called again, so it must have no side effects.
A thread that loses a CAS doesn't go to sleep; it retries immediately. For a counter that many threads increment all the time, Java 8 added LongAdder: it spreads the sum across several cells and adds them up when you read it.
5. What thread-safe collections are there in Java, and how do they differ?
What thread-safe collections are there in Java, and how do they differ?
Three kinds:
- Legacy synchronized classes
VectorandHashtable(Java 1.0): every method issynchronizedonthis. Not formally@Deprecated, but used only in legacy code. - Wrappers
Collections.synchronizedList/Set/Map: one lock for the whole collection; iteration must be wrapped insynchronized (list)by hand, otherwise aConcurrentModificationExceptionis possible. java.util.concurrentcollections:ConcurrentHashMap(per-bin locks plus CAS, reads don't block, nonull),CopyOnWriteArrayList(copies the array on every change, snapshot iterator - for frequent reads and rare writes),ConcurrentLinkedQueue,BlockingQueueimplementations. Their iterators don't throwConcurrentModificationException.
New code uses the third group. There is no separate ConcurrentHashSet - ConcurrentHashMap.newKeySet() gives you a thread-safe set.
6. Why doesn't a thread-safe class make your code thread-safe? What is check-then-act?
Why doesn't a thread-safe class make your code thread-safe? What is check-then-act?
A thread-safe class guarantees that each individual call is atomic, but not a sequence of calls. "Check, then act" (check-then-act) or "read, modify, write" code built from several methods is still a race: another thread can change the object between the calls. For example, a get() + put() pair on a ConcurrentHashMap in two threads loses updates without a single exception.
The fix is one atomic operation instead of two: merge(key, 1, Integer::sum) or compute() for counters, computeIfAbsent() for a cache (the function runs at most once per key), putIfAbsent() when the value is already computed. For a Vector, the isEmpty() + remove(0) pair can be wrapped in synchronized (vector) because it locks on its own monitor; for a ConcurrentHashMap this trick is useless.
7. What is the difference between StringBuilder and StringBuffer, ArrayList and Vector, HashMap and ConcurrentHashMap?
What is the difference between StringBuilder and StringBuffer, ArrayList and Vector, HashMap and ConcurrentHashMap?
In each pair the first class is not thread-safe and is faster in a single thread, while the second is synchronized:
StringBuilder/StringBuffer- same API, everyStringBuffermethod issynchronized. ChooseStringBuilder: a string is almost always built by one thread.ArrayList/Vector-Vectoris synchronized as a whole and doubles in size when it grows,ArrayListgrows by 1.5x.ArrayListin a single thread,CopyOnWriteArrayListfor frequent reads from many threads.HashMap/ConcurrentHashMap-HashMapallows anullkey andnullvalues, whileConcurrentHashMapandHashtablethrowNullPointerException.ConcurrentHashMapfor shared access,Hashtableonly in legacy code.
The right interview answer is usually not "use the synchronized one" but "a regular class in a single thread, a class from java.util.concurrent for shared access": synchronizing every method doesn't save compound operations.
8. What are the @ThreadSafe and @GuardedBy annotations, and are they part of the JDK?
What are the @ThreadSafe and @GuardedBy annotations, and are they part of the JDK?
@ThreadSafe, @NotThreadSafe, @Immutable and @GuardedBy document how a class behaves in a multithreaded environment. @GuardedBy("this") on a field means it is read and written only under the named monitor.
They are not part of the JDK: they come from Brian Goetz's book "Java Concurrency in Practice" and are added with the net.jcip:jcip-annotations library (package net.jcip.annotations); the same names exist in javax.annotation.concurrent from com.google.code.findbugs:jsr305. The annotations synchronize nothing on their own. Compile-time checks come from Error Prone: accessing a @GuardedBy field without the named monitor becomes a build error.