본문 바로가기
개발/Java

[Java] ThreadPool 을 이용한 Method 실행하기

by 코딩하는 흰둥이 2025. 4. 25.

배치 스케줄 코드를 구현하다가 사용한 코드를 정리하려고 한다

DB 또는 정의되어 있는 메서드 명을 가져와서

동적으로 메서드를 실행시키는 코드로 ThreadPool 을 이용하여 병렬처리가 가능하고

Method Class 를 이용하여 메서드를 실행시킨다

 

 

 

 

메서드를 호출하기 위한 테스트 main Class
public class TestController {

    public static void main(String[] args) throws Exception {

        // method 실행 시킬 class
        TestExecutor testExecutor = new TestExecutor();
        testExecutor.TestMethod();

    }
}

 

 

 

ThreadPool 을 생성하여 메서드를 실행시키는 코드
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestExecutor {

    public void TestMethod() {

        // DB 또는 실행 시킬 메서드 명 가져오기
        List<Map<String, Object>> resultList = new ArrayList<>();

        // TEST 용으로 실행시킬 메서드 명 넣기
        Map<String, Object> testMap1 = new HashMap<>();
        Map<String, Object> testMap2 = new HashMap<>();
        Map<String, Object> testMap3 = new HashMap<>();
        Map<String, Object> testMap4 = new HashMap<>();

        // 존재하는 메서드
        testMap1.put("name", "test01");
        resultList.add(testMap1);

        // 존재하는 메서드
        testMap2.put("name", "test02");
        resultList.add(testMap2);

        // 존재하는 메서드
        testMap3.put("name", "test03");
        resultList.add(testMap3);

        // 존재하지 않는 메서드
        testMap4.put("name", "test04");
        resultList.add(testMap4);

        // 스레드 풀 생성 , 실행시킬 메서드 개수만큼 생성
        ExecutorService executor = Executors.newFixedThreadPool(resultList.size());

        for (Map<String, Object> jobMap : resultList) {
            String jobName = String.valueOf(jobMap.get("name"));    // 메서드 명

            try {
                // "현재 클래스" 에서 메서드 찾기
                Method method = this.getClass().getMethod(jobName);

                // 파라미터가 있다면 실행시킬 메서드의 파라미터에 맞게 타입을 지정해야함
                //Method method = this.getClass().getMethod(jobName, String.class, String.class, String.class, String.class);

                Runnable run = () -> {
                    try {

                        // this = 실행시킬 메서드 명
                        method.invoke(this);

                        // String type 의 파라미터가 4개 더 있을때
                        //method.invoke(this, String1, String2, String3, String4);

                    } catch (Exception e) {
                        System.err.println("method 실행 실패: " + jobName);
                    }
                };

                executor.submit(run);
            } catch (Exception e) {
                System.err.println(jobName + " method 가 존재하지 않습니다.");
            }

        }
        executor.shutdown();
    }


    public void test01() throws Exception {
        LocalDateTime now = LocalDateTime.now();
        String formatter = now.format(DateTimeFormatter.ofPattern("yyyy년 MM월 dd일 HH시 mm분 ss초"));

        System.out.println("test01 실행 중: " + Thread.currentThread().getName() + " , formatter : " + formatter);
    }

    public void test02() throws Exception {
        LocalDateTime now = LocalDateTime.now();
        String formatter = now.format(DateTimeFormatter.ofPattern("yyyy년 MM월 dd일 HH시 mm분 ss초"));

        System.out.println("test02 실행 중: " + Thread.currentThread().getName() + " , formatter : " + formatter);
    }

    public void test03() throws Exception {
        LocalDateTime now = LocalDateTime.now();
        String formatter = now.format(DateTimeFormatter.ofPattern("yyyy년 MM월 dd일 HH시 mm분 ss초"));

        System.out.println("test03 실행 중: " + Thread.currentThread().getName() + " , formatter : " + formatter);
    }

}

 

 

 

TEST

01~03 의 메서드가 동일 시간에 동작하였고

없는 method 는 catch 로 빠진다

 

 


 

 

test01~03 처럼 메서드를 생성하지 않고

실행하려는 메서드도 공통 메서드로 실행시킬 수 있다

테스트 겸 보여주기 위해 각각 메서드를 생성하였으니 참고하자

 

 

 

 

댓글