Using a single Java 8 Consumer as a Runnable Callback - is it thread safe?

I have ScheduledThreadPoolExecutorwith 4 active threads. It is filled with many tasks, where each task processes a piece of elements.

Each task should have 3 callbacks: start, end, and one after each processed item.

Each callback triggers an update in my database. This is a very long task.


Here is an example code snippet that should illustrate what I'm doing:

public static void main(String[] args) throws InterruptedException {
    ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(4);

    Consumer<String> processed = (String o) -> {
            System.err.println("PROCESSED: " + o);
            try { Thread.sleep(10); }
            catch (Exception e) { e.printStackTrace(); }
    };

    for(int i=0; i<10; i++) {
        executor.schedule(
                new ChunkTask("task"+i, processed),
                500,
                TimeUnit.MILLISECONDS
        );
    }

}


public static class ChunkTask implements Runnable {
    String taskId;
    Consumer<String> processedCallback;

    public ChunkTask(String taskId, Consumer<String> processedCallback) {
        this.taskId = taskId;
        this.processedCallback = processedCallback;
    }

    @Override
    public void run() {
        for(int i=0; i<50; i++) {
            processedCallback.accept(taskId+" "+i);
        }
    }
}

I just omitted the start and end callbacks because it is basically the same as the processed callback.


As you can see, I am creating a separate object Consumer. Which has Thread.sleep(10)to simulate access to the database. This object is called by all 4 threads in parallel.

, . -, Consumer - , . , .

?


EDIT: , . . .

+4
1

, , . , , System.err, .

, , , System.err. , , .

+2

All Articles