Java .parallelStream() with spring annotated methods

后端 未结 2 820
南方客
南方客 2021-02-05 12:04

I try using the parallelStream() in DAO with Spring @Transactional annotations and get so problem:

@Transactional
public void processCo         


        
2条回答
  •  [愿得一人]
    2021-02-05 12:28

    Well, I have a guess consists of several guesses:

    • You have session management policy as session-per-thread;
    • Object you wrote in example is in fact some entity that uses lazy loading;
    • processOne() method uses entity properties that are loaded lazily;
    • Because of first point, threads, started for parallelStream() has no session available (probably in ThreadLocal, don't remember how technically sessions are bound to threads);

    That altogether causing the problem you have. The behavior looks quite strange to me, so I suggest to do the following:

    • Remove all lazy loading and try parallelStream() again;
    • If that succeeds, you'll have to load the entities completely before performing parallelStream().

    Alternative way to go: detaching all list elements from session before doing parallelStream().

    Although as Marko wrote in comments, Session is not thread-safe, so that means you have to get rid of Session usage either by removing lazy loading, or by detaching all entities from session.

提交回复
热议问题