Java
Concurrency Utilities
Common utilities in the concurrency package.
By EZ4Code Team
concurrentconcurrency
Code
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
// ExecutorService
ExecutorService executor = Executors.newFixedThreadPool(4);
Future<Integer> future = executor.submit(() -> {
Thread.sleep(1000);
return 42;
});
Integer result = future.get(2, TimeUnit.SECONDS);
executor.shutdown();
// CompletableFuture
CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World")
.thenAccept(System.out::println);
// AtomicInteger
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();
counter.compareAndSet(1, 10);
// CountDownLatch
CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
new Thread(() -> { latch.countDown(); }).start();
}
latch.await();Explanation
java.util.concurrent provides thread pools, Future, atomic variables, and other concurrency utilities.
More Java Snippets
String Operations and StringBuilder
Manipulate strings with split, join, substring, and StringBuilder in Java.
Stream API
Process collections using the Stream API.
Lambda Expressions
Simplify code with Lambda expressions.
Optional
Handle null values elegantly.
Collection Operations
Common operations on List, Set, and Map.
Exception Handling
try-catch-finally and custom exceptions.