使用forkjoin框架调用Spring bean

时间:2016-08-22 12:52:26

标签: java spring javabeans applicationcontext fork-join

是否可以使用fork-join框架

在Spring中调用bean
public class MyRecursiveAction extends RecursiveAction {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private long workLoad = 0;

    public MyRecursiveAction(long workLoad) {
        this.workLoad = workLoad;
    }

    @Override
    protected void compute() {

        if (this.workLoad > 16) {
            System.out.println("Splitting workLoad : " + this.workLoad);

            List<MyRecursiveAction> subtasks = new ArrayList<MyRecursiveAction>();

            subtasks.addAll(createSubtasks());

            for (RecursiveAction subtask : subtasks) {
                subtask.fork();
            }

        } else {
            //code breaks here
            DepartmentServiceImpl dept = AppContextHolder.getBean("departmentServiceImpl");
            System.out.println("Doing workLoad myself: " + this.workLoad);
        }
    }

    private List<MyRecursiveAction> createSubtasks() {
        List<MyRecursiveAction> subtasks = new ArrayList<MyRecursiveAction>();

        MyRecursiveAction subtask1 = new MyRecursiveAction(this.workLoad / 2);
        MyRecursiveAction subtask2 = new MyRecursiveAction(this.workLoad / 2);

        subtasks.add(subtask1);
        subtasks.add(subtask2);
        return subtasks;
    }

    public static void main(String[] args) {
        MyRecursiveAction myRecursiveAction = new MyRecursiveAction(24);
        ForkJoinPool forkJoinPool = new ForkJoinPool(4);
        forkJoinPool.invoke(myRecursiveAction);
    }

}

这是我如何访问应用程序上下文

public class AppContextHolder {
    private static final ApplicationContext appContext = new ClassPathXmlApplicationContext("classpath:/spring.xml");

    public static <T> T getBean(String bean) {
        return (T) appContext.getBean(bean);
    }
}

当我尝试调试此行时 - 它会中断并退出程序而不会出现任何错误或消息。

DepartmentServiceImpl dept = AppContextHolder.getBean("departmentServiceImpl");

是否可以从其他线程访问spring bean?

0 个答案:

没有答案