原创

为什么我的 ExecutorService 中的多个线程尝试处理同一任务? [关闭]

温馨提示:
本文最后更新于 2024年04月12日,已超过 37 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

I wrote a class to asynchronously process tasks in java from a table in my database called task. I want to use multiple threads to each process a different row in the database. The problem I'm having is that multiple threads are trying to process the same task. Each thread should only ever be trying to process one unique task. I'm a bit of a concurrency novice so would appreciate some better understanding.

Here's the async task processor.

public class AsyncTaskProcessor implements Trigger, Runnable, ErrorHandler {

    @Autowired
    private TaskProcessor taskProcessor;

    @Autowired
    private TaskDao taskDao;

    private boolean lastRunHadTask = false;

    @Override
    @Transactional
    public void run() {
        var optTask = taskDao.findNextUnprocessed();
        if (optTask.isPresent()) {
            var task = optTask.get();
            log.info("Processing task... taskId: {}", task.getId());
            try {
                taskProcessor.process(task);
            } catch (Exception e) {
                log.warn("Error processing task... taskId: {}", task.getId(), e);
                // handle exception
            }
        }
        lastRunHadTask = optTask.isPresent();
    }

And I submit tasks to it by creating a new task in my database. Here's the taskProcessor.process() from the run() of the previous code snippet.

public class TaskProcessor {

    @Autowired
    private TaskDao taskDao;


    private ExecutorService executorService = Executors.newFixedThreadPool(10);
    
    void process(Task task) {
        if (task.getType().equals(Task.Type.FOO.nameLowerCase())) {
            executorService.submit(() -> {
                // process task
                // update task in db
                taskDao.update(task);
            });
        }
    }

What's going on here that's causing multiple threads to try and process the same task?

正文到此结束
热门推荐
本文目录