I have a database table and you need to process records from it 5 at a time while the application is running. So it looks like this:
- Get a record that has not yet been processed or is not being processed now by other threads.
- Handle this (this is a lengthy process that depends on your internet connection so that it can timeout / throw errors).
- Go to the next entry. When the end of the beginning of the table from the beginning is reached.
I do not have much experience with threads, so I see two possible strategies:
Approach A.
1.Create a new ExecutorService:
ExecutorService taskExecutor = Executors.newFixedThreadPool(5);
2. Add to it 5 tasks:
for (int i = 0; i < 5; i++) { taskExecutor.execute(new MyTask()); }
3. Each task will be an infinite loop, which: reads a record from a table, processes it, and then receives another record.
The problems with this approach are how to inform other threads about which records are being processed over time. To do this, I can either use the "status" field in the table, or simply use some CopyOnWriteArraySet instance that contains the current processing identifiers.
Approach B.
1. Create the same service provider:
ExecutorService taskExecutor = Executors.newFixedThreadPool(5);
2. Have an infinite loop that selects the records that need to be processed and passes them to the executor:
while (true) { //get next record here taskExecutor.execute(new MyTask(record)); //monitor the queue and wait until some thread is done processing, //so I can add another record }
3. Each task processes one record.
The problem with this approach is that I need to add tasks to the executor queue more slowly than they are processed to prevent them from accumulating over time. This means that I need to track not only the tasks that are currently running, but also when they are running, so I can add new entries to the queue.
Personally, I think the first approach is better (easier), but I feel the second is right. What do you think? Or maybe I should do something completely different?
I can also use Spring or Quartz libraries if necessary.
Thanks.