Programming/Java

(JAVA) Multi-Thread를 활용하여 메인페이지를 빠르게 불러오기

armyost 2022. 6. 30. 16:52
728x90

Mobile APP에서는 메인화면에서 워낙 많은 모듈을 호출하다보니 multi thread를 사용하여 병렬로 데이터 처리를 하는 방식이 나름 보편화 되어 있는것 같다. 

 

https://www.youtube.com/watch?v=IVt7HjUM0LQ&t=388s 

 

최근 어느 사이트에서 Web 메인페이지가 느리다는 보고가 있었고, 그 이유는 메인페이지에서 특정 기관의 API에서 데이터를 받아오는데 시간이 소요되어서 느리다는 이유였다. 

 

나는 위 Youtube의 멀티스레드 방식이 해결책이 되지 않을까 하여 자체적으로 테스트를 해보았다. 

 

아래는 Controller에서 View에 특정 데이터를 던지는 것인데

@RequestMapping("/")
	public String index(Model model) {
		int testvalue = 0;
		testvalue = testValue();
		System.out.println("TEST VALUE IS = "+testvalue);
		model.addAttribute("Test_value", testvalue);
		return  "index";
	}

 

일부러 TestValue 연산을 오래 걸리게 만들었다.

public int testValue(){
	 	int testvalue = 0;
	 	int testCount = 100000;
	 	System.out.println("test Cacluation start");
		
	 	for(int i=0; i<testCount; i++){
	 		for(int j=0; j<testCount; j++){
	 			for(int m=0; m<testCount; m++){
	 				testvalue++;
	 			}
	 		}
	 	}

	 	System.out.println("test Cacluation finish");
	 	return testvalue; 
	}

 

이렇게 개발을 하게 되면 Controller에서 View에 전달되는 자체가 지연되므로 메인화면이 늦게 뜨는 현상이 발생한다. 

이를 해결하기 위해 해당 연산을 ChileThread로 돌려서 연산을 시킨다. 

@RequestMapping("/")
public String index(Model model) {
    int testvalue = 0;
    // testvalue = testValue();

    Thread t = new ChildThread();
    t.start();

    model.addAttribute("Test_value", testvalue);
    return  "index";
}

 

class ChildThread extends Thread {
	int testvalue = 0;
	public void run() {
		int testCount = 100000;
		System.out.println("test Cacluation start");
		
		for(int i=0; i<testCount; i++){
			for(int j=0; j<testCount; j++){
				for(int m=0; m<testCount; m++){
					testvalue++;
				}
			}
		}

		System.out.println("test Cacluation finish");
	// AJAX등으로 Frontend의 비동기 호출로 연산한 데이터를 갱신
	}

	public int getResult(){
		return this.testvalue;
	}
}

 

개선을 통해 메인화면과 특정 연산이 분리되어 처리되므로 고객화면에서 메인화면이 빨리뜸을 알 수 있다. 

혹시 자식 Thread의 리턴값이 필요하면 Getter를 사용하면 된다.

 

관련 Git주소 : https://github.com/armyost/multiThreadWeb.git

 

GitHub - armyost/multiThreadWeb: For accelerating lendering main page, some havy contents need to load at child threads.

For accelerating lendering main page, some havy contents need to load at child threads. - GitHub - armyost/multiThreadWeb: For accelerating lendering main page, some havy contents need to load at c...

github.com