首页 > 解决方案 > 服务和控制器之间打开多线程有什么区别?

问题描述

服务和控制器之间打开多线程有什么区别?当我在控制器中打开多线程时,我不需要打开休眠会话,我可以得到currentSession. 但是,当我在服务中打开一个线程时,我必须先获取hibernate sessionFactory,然后再打开一个新会话。最后,我必须关闭会话。请帮助或尝试提供一些想法如何实现这一目标。

@Controller

public class TestController extends BaseController {

    @Autowired
    private TestService testService;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    private TestDao testDao;

    @ResponseBody
    @RequestMapping("/testMultiInService")
    public Object test() {
        GenericListResponse response = testService.testMulti();
        return response;
    }
}

@Service

public class TestServiceImpl extends TestService {

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    private TestDao testDao;

    private static Logger logger = Logger.getLogger(TestServiceImpl.class);

    @Override
    @Transactional
    public GenericListResponse testMulti() {
        CountDownLatch latch = new CountDownLatch(2);

        TestCallable1 callable1 = new TestCallable1(this, latch);
        Future<List> future1 = taskExecutor.submit(callable1);
        List list = new ArrayList();

        try {
            latch.await();
            if (null != future1)
                list.addAll(future1.get());
            if (null != future2)
                list.addAll(future2.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public class TestCallable1 implements Callable<List> {

    private TestService testService;

    private CountDownLatch latch;

    public TestCallable1(TestService testService, CountDownLatch latch) {
        this.testService = testService;
        this.latch = latch;
    }

    @Override
    public List call() throws Exception {
        List list = null;
        try {
            list = testService.getDimArea();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.latch.countDown();
            return list;
        }
    }


}

标签: javamultithreadingtransactions

解决方案


推荐阅读