Trying to play with chatGPT I requested to generate a java code that uses backpressure when running high intensive tasks.
This is what I’ve received, and I find it a good start point
import java.util.concurrent.*;
public class BackPressureExample {
private static final int MAX_QUEUE_SIZE = 10;
private static final int MAX_CONCURRENT_TASKS = 4;
private static final int NUM_TASKS = 20;
public static void main(String[] args) {
// Create a bounded blocking queue with a capacity of MAX_QUEUE_SIZE
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(MAX_QUEUE_SIZE);
// Create a new executor service with a fixed pool of MAX_CONCURRENT_TASKS threads
ExecutorService executor = new ThreadPoolExecutor(MAX_CONCURRENT_TASKS, MAX_CONCURRENT_TASKS,
0L, TimeUnit.MILLISECONDS, queue);
// Submit NUM_TASKS tasks to the executor, with backpressure
for (int i = 0; i < NUM_TASKS; i++) {
try {
// Wait until there is available space in the queue
queue.put(new Task(i));
} catch (InterruptedException e) {
System.err.println("Task submission interrupted: " + e.getMessage());
}
}
// Shutdown the executor and wait for all tasks to complete
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
System.err.println("Tasks interrupted: " + e.getMessage());
}
System.out.println("All tasks completed");
}
private static class Task implements Runnable {
private int id;
public Task(int id) {
this.id = id;
}
public void run() {
System.out.println("Task " + id + " started by thread " + Thread.currentThread().getName());
try {
// Perform some work
Thread.sleep(1000);
} catch (InterruptedException e) {
System.err.println("Task " + id + " interrupted: " + e.getMessage());
}
System.out.println("Task " + id + " completed by thread " + Thread.currentThread().getName());
}
}
}