Junior — Middle
How can you estimate the number of processed records in the main thread considering the work of multiple threads?
sobes.tech AI
Answer from AI
To determine the number of processed records in the main thread when working with multiple threads in Java, thread-safe mechanisms for counting should be used.
One common approach is to use the AtomicInteger class from the java.util.concurrent.atomic package. Each thread, after processing a record, increments this counter, and the main thread can retrieve the current value at any moment.
Example:
import java.util.concurrent.atomic.AtomicInteger;
public class Processor {
private AtomicInteger processedCount = new AtomicInteger(0);
public void processRecord() {
// process record
processedCount.incrementAndGet();
}
public int getProcessedCount() {
return processedCount.get();
}
}
Thus, the main thread can call getProcessedCount() to find out how many records have been processed by all threads together.