inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

Querydsl을 멀티쓰레드 환경에서 사용할 때 발생하는 문제에 대해

해결된 질문

452

qwerty1434

작성한 질문수 6

0

안녕하세요. Querydsl강의를 수강하고 혼자 개발을 진행하다가 다음과 같은 문제가 발생해서 질문을 남기게 되었습니다.
제 상황은 A엔티티와 B엔티티를 가지고 있고, 둘은 OneToOne관계로 B가 연관관계의 주인인 상황입니다. Repository에는 A와 B의 데이터를 호출하는 Querydsl코드가 각각 존재하며, 이를 Service Layer에서 그대로 Return값으로 받고 있습니다.
이들을 멀티쓰레드 환경에서 호출했을 때 B데이터를 호출하는 코드에 Connection leak이 존재한다는 에러가 발생하는 상황입니다. (.yml파일에서 hikari의 leak-detection-threshold을 설정한 상황입니다.)

Domain

@NoArgsConstructor
@AllArgsConstructor
@Entity
public class A {
    @Id
    private Long id;

    @OneToOne(mappedBy = "a")
    private B b;

    private int var1;
}
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class B {
    @Id
    private Long id;

    @OneToOne
    @JoinColumn(name = "b_id")
    private A a;

    private int var1;
}

Repository

public interface Repository extends JpaRepository<A,Long>, RepositoryCustom {

}
public interface RepositoryCustom {
    Dto queryOne();
    Dto queryTwo();
    Dto queryThree();
}
public class RepositoryCustomImpl implements RepositoryCustom {
    private final JPAQueryFactory queryFactory;

    public RepositoryCustomImpl(EntityManager em) {
        this.queryFactory = new JPAQueryFactory(em);
    }

    @Override
    public Dto queryOne() {
        return queryFactory
                .select(Projections.constructor(Dto.class,
                        a.id,
                        a.var1
                ))
                .from(a)
                .fetchFirst();
    }

    @Override
    public Dto queryTwo(){
        return queryFactory
                .select(Projections.constructor(Dto.class,
                        b.id,
                        b.var1
                ))
                .from(b)
                .fetchFirst();
    }

    @Override
    public Dto queryThree(){
        System.out.println("a.getClass() = " + a.getClass());
        System.out.println("b.getClass() = " + b.getClass());
        return queryFactory
                .select(Projections.constructor(Dto.class,
                        b.id,
                        b.var1
                ))
                .from(b)
                .fetchFirst();
    }
}

DTO

public class Dto {
    private Long id;
    private int var1;
}

Service

@org.springframework.stereotype.Service
@RequiredArgsConstructor
public class Service {

    private final Repository repo;

    @Transactional
    public Dto logicOne(){
        return repo.queryOne();
    }

    @Transactional
    public Dto logicTwo(){
        return repo.queryTwo();
    }

    @Transactional
    public Dto logicThree(){
        return repo.queryThree();
    }

}

테스트코드

@SpringBootTest
@Slf4j
public class SimpleTest {
    @Autowired
    Service service;

    @Test
    void connection_leak_detected(){
        Runnable userA = () -> {
            Dto dto = service.logicOne();
            log.info("[Thread A: {}]",dto);
        };
        Thread threadA = new Thread(userA);
        threadA.start();

        Runnable userB = () -> {
            Dto dto = service.logicTwo();
            log.info("[Thread B: {}]",dto);
        };
        Thread threadB = new Thread(userB);
        threadB.start();

        sleep(6000);

    }

    @Test
    void leak_not_detected(){
        Runnable userA = () -> {
            Dto dto = service.logicOne();
            log.info("[Thread A: {}]",dto);
        };
        Thread threadA = new Thread(userA);
        threadA.start();

        Runnable userB = () -> {
            Dto dto = service.logicThree();
            log.info("[Thread B: {}]",dto);
        };
        Thread threadB = new Thread(userB);
        threadB.start();

        sleep(6000);
    }

    @Test
    @Transactional
    void connection_leak_detected_otherCase(){
        Runnable userA = () -> {
            Dto dto = service.logicOne();
            log.info("[Thread A: {}]",dto);
        };
        Thread threadA = new Thread(userA);
        threadA.start();

        Runnable userB = () -> {
            Dto dto = service.logicThree();
            log.info("[Thread B: {}]",dto);
        };
        Thread threadB = new Thread(userB);
        threadB.start();

        sleep(6000);
    }




    private void sleep(int millis){
        try{
            Thread.sleep(millis);
        } catch (InterruptedException e){
            e.printStackTrace();
        }
    }

}

어떤 이유로 이러한 Connection leak이 발생하는지, 그리고 어떻게하면 이러한 문제를 해결할 수 있는지 궁금합니다..!


 

 

 

 

java jpa spring querydsl

답변 0

강의 소스코드는 어디서 다운받을 수 있나요?

1

17

2

JpaPagingItemReader는 좋은게 없는거야..??

0

34

1

입문 강의 듣고 바로 들어도 괜찮을까요?

0

28

1

리프레시토큰

0

44

1

DB 연결 후 회원가입 시 생성되는 id 번호 질문

0

40

1

로그인 확인

0

66

3

ttl 산정 기준

0

42

1

정처기 2026-3 실기 문의

0

97

2

정처기 실기 3회 컴싸 사용 여부

0

63

1

자바 킴쌤 클래스 기초part2.pdf파일은 어디서 받을 수 있나요?

0

39

1

오타 제보 드립니다.

0

65

2

모의고사 1 회 2번문제 중

0

80

2

26-2 이론문제 재탕

1

61

1

26-2년도 코드문제

0

41

0

26-2 코드문제

0

48

1

15분 48초 질문

0

66

2

26-1년도 이론문제 재탕

0

72

1

26-1년도 코드문제 재탕

0

52

0

이론재탕만 눈치챘어도

0

82

1

25-3년도 이론문제 재탕

0

63

1

25-3년도 코드문제 재탕

0

48

0

출력값 문의

0

62

2

25-2 분기커버리지

0

54

0

25-2 이론 재탕

0

74

1