Junior — Middle
Can you name the main primitives and tools provided in the java.util.concurrent package for organizing multithreaded execution?
sobes.tech AI
Answer from AI
The java.util.concurrent package contains several primitives and tools for organizing multithreaded execution:
- Executor and ExecutorService — interfaces for managing thread pools and asynchronous task execution.
- Future and CompletableFuture — for obtaining the result of asynchronous computations.
- CountDownLatch — allows one or more threads to wait until other threads complete certain actions.
- CyclicBarrier — synchronizes multiple threads, making them wait for each other.
- Semaphore — limits the number of threads that can access a resource simultaneously.
- ReentrantLock — an advanced locking mechanism with the ability to attempt lock acquisition and timeout.
- Concurrent Collections (e.g., ConcurrentHashMap, CopyOnWriteArrayList) — thread-safe collections.
- Atomic Variables (AtomicInteger, AtomicLong, etc.) — for atomic operations on variables without using locks.
Example of using ExecutorService:
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> {
System.out.println("Task executed in a separate thread");
});
executor.shutdown();