Junior — Middle
Can you give examples of well-designed classes for multithreading?
sobes.tech AI
Answer from AI
Well-designed classes for multithreading in Java typically follow thread-safety principles and minimize locking. Here are some examples:
- Immutable classes — objects whose state does not change after creation. Such classes are automatically thread-safe.
public final class ImmutablePoint {
private final int x;
private final int y;
public ImmutablePoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
}
- Classes using synchronized or Lock for access control:
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
- Using classes from java.util.concurrent:
ConcurrentHashMap— thread-safe hash table implementation.AtomicInteger— atomic counter without locks.
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicCounter {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet();
}
public int getCount() {
return count.get();
}
}
- Using ExecutorService to manage threads:
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
// task
});
executor.shutdown();
In summary, a well-designed class for multithreading should minimize state, use immutability, atomic operations, or properly synchronize access to shared resources.