将runnables作为Spring组件创建是一种不好的做法吗?

时间:2017-12-05 08:09:37

标签: java spring multithreading threadpoolexecutor

这是我第一次使用Spring并发,我有一段代码使用Spring进行并发计算。这是代码:

@Component
public class AppScheduler {

    //@Autowired DAOs or services.

    private ThreadPoolExecutor executor;

    private AbstractApplicationContext context;

    @PostConstruct
    public void init() {
        executor = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(10));
        context = new AnnotationConfigApplicationContext(VtmDispatcherConfig.class);
    }

    @Scheduled(fixedDelay = 60 * 1000)
    //at rejection break the execution.
    public void appEntry() {
        //fetch some records from db 
        for (Record rec : records) {
            try {
                executeTransactionally(rec);
            } catch (RejectedExecutionException ex) {
                break;
            }
        }
    }

    @Transactional
    //Creates runnable tasks, makes some db operations and passes task to the thread pool
    private void executeTransactionally(Record rec) {
        ARunnableTask aRunnableTask = (ARunnableTask) context.getBean("aRunnableTask");
        aRunnableTask.setParameter(rec.param);
        //some db operations...
        tempTableExecutorPool.execute(aRunnableTask);
    }
}

此处,预定代码从db获取记录,并且每条记录都实例化一个可运行的任务并将其传递给线程池执行程序。我的可运行任务就在这里:

@Component
@Scope("prototype")
public class ARunnableTask implements Runnable {

    private String param;

    private ThreadPoolExecutor executor;

    private DAOOrService inject

    @Autowired
    public TempTableExecutorTask(DAOOrService inject) {
        executor = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1000));
        this.inject = inject;
    }

    @Override
    public void run() {
        //...
        executeTransactional();
        //...
        executor.shutdown();
    }

    @Transactional
    private void executeTransactional() {
        //some transactional processes
    }

    public void setParameter(String param) {
        this.param = param;
    }

}

这是我的问题:将runnable任务创建为spring组件并在runnable中使用@Transactional是一个好习惯吗?

如果这不是一个坏习惯,是否有更好的方法来创建可运行的弹簧组件:

ARunnableTask aRunnableTask = (ARunnableTask) context.getBean("aRunnableTask");
aRunnableTask.setParameter(rec.param);

0 个答案:

没有答案