Sobes.tech
Junior — Middle

How to implement counting processed records when using multithreading?

sobes.tech AI

Answer from AI

When using multithreading to count processed records, it is important to ensure correct synchronization of access to the counter to avoid race conditions.

One simple way is to use thread-safe classes from the java.util.concurrent.atomic package, such as AtomicInteger:

import java.util.concurrent.atomic.AtomicInteger;

public class RecordProcessor {
    private AtomicInteger processedCount = new AtomicInteger(0);

    public void processRecord(Record record) {
        // process the record
        // ...

        // safely increment the counter
        processedCount.incrementAndGet();
    }

    public int getProcessedCount() {
        return processedCount.get();
    }
}

If a thread pool is used, each thread calls processRecord, and the counter will be correctly incremented without locks.

Alternatively, synchronized blocks or other synchronization mechanisms can be used, but AtomicInteger is simpler and more efficient for such tasks.