2009년 04월 08일
java.util.concurrent을 이용한 부하 테스트 환경 구축 예(JAVA SDK 1.5)
/**
* <PRE>
* Class/Interface Name : MyThreadPoolTask
* History
* 1. 이지홍(hongsgo@gmail.com), 2009. 4. 8., 최초작성
* </PRE>
* @brief ThreadPool을 이용한 부하 테스트 예
* @date 2009. 4. 8.
* @version 1.0.0
* @author 이지홍(hongsgo@gmail.com)
* @warning
*/
public class MyThreadPoolTask implements Runnable {
private IndexManagerService im = new IndexManagerService();
private DBIndexJobSaveInfo dbindexjobsaveinfo = null;
private int type = 0;
private int pseq =0;
public MyThreadPoolTask(int type,int pseq) {
//저장 경로
im.setRootpath("D:\\workspace_20090325\\temp_index_data");
//저장객체 식별자
this.type=type;
this.pseq=pseq;
}
public void run() {
try {
if(type==1){
dbindexjobsaveinfo = new DBIndexJobSaveInfo("pcmong",Integer.toString(pseq+1),DBIndexJobType.DBIndexMakeOne);
}
else if(type==2){
dbindexjobsaveinfo = new DBIndexJobSaveInfo("pcmong",Integer.toString(pseq+1),DBIndexJobType.DBIndexModifyOne);
}
else if(type==3){
dbindexjobsaveinfo = new DBIndexJobSaveInfo("pcmong",Integer.toString(pseq+1),DBIndexJobType.DBIndexDeleteOne);
}
//생성된 작업정보 저장 (파일I/O)
im.setSaveDBIndexJob(dbindexjobsaveinfo);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(100); //쓰레드 풀의 갯수 지정
System.out.println("[임시색인 요청파일 한 폴더에 색인 시작]");
for(int i = 0 ; i < 1000;i++){
es.execute(new MyThreadPoolTask(1,i));
es.execute(new MyThreadPoolTask(2,i));
es.execute(new MyThreadPoolTask(3,i));
}
System.out.println("[Finish submitting!]");
//쓰레드 풀을 릴리즈
es.shutdown();
}
}
J2SE 5.0 버전은 병렬 프로그래밍을 위한 라이브러리가 추가되었다.
이것은 JCR(Java Community Process) 의 [JSR166 : Concurrency Utilities] 에 정의되어 있는 내용으로 JSR 166 의 목적은 다음과 같다. (짧은 영어 실력으로 대강 번역해 보았다.)
------------------------------------------------------------------------------------------
・간단하고 확장가능한 표준 프레임워크를 제공
- 자주 사용되는 유틸리티/메소드를 정리해, 쉽게 배울 수 있고, 유지/보수 하기도 편리한 작은
패키지를 제공
・고품질(high-quality) 의 라이브러리(implementations) 를 제공
------------------------------------------------------------------------------------------
java.util.concurrent 패키지에는
・Thread, synchronized, wait/notify/notifyAll
・락(Lock), 상태(Condition), 큐(Queue), 아토믹(Atomic)
과 관련된 클래스, 인터페이스 등이 존재한다.
1. Executor
Executor 는 복수의 태스크를 병렬로 실행시킬 때 쓰이는 프레임워크다. 비동기로 실행시킬
복수의 처리에 대해, 하나의 처리에 하나의 스레드를 작성하는 것은 리소스를 낭비하는 일이다.
그 때문에 기존의 스레드를 재사용하는 등의 방법을 생각할 수 있는데, Executor 를 통해 스레드의
재사용, 타이머(Scheduling) 등의 병렬 처리를 간단히 구현할 수 있다.
------------------------------------------------------------------------------------------
Executor exe = Executors.newSingleThreadExecutor();
Runnable run1 = ......
Runnable run2 = ......
exe.execute(run1);
exe.execute(run2);
------------------------------------------------------------------------------------------
Executors 클래스는 Executor 인터페이스 등을 구현한 인스턴스를 리턴하는 메소드를 제공하는
클래스이다. Executors.newSingleThreadExecutor() 메소드로 하나의 스레드로 태스크를
실행시키는 Executor 를 취득, Executor 의 execute() 메소드로 태스크를 실행시킨다.
Executors 클래스에 정의되어 있는 몇 개의 메소드를 살펴보면...
◎ newSingleThreadExecutor()
- 하나의 스레드로 태스크를 처리한다.
◎ newFixedThreadPool(int nThreads)
- 지정한 [nThreads] 수만큼 스레드를 작성, 태스크를 처리한다.
◎ newCachedThreadPool()
- 필요한만큼 자동적으로 스레드를 작성, 태스크를 처리한다.
◎ newScheduledThreadPool(int corePoolSize)
- 지정된 시간에 주기적으로 실행되는 [corePoolSize]만큼의 스레드를 작성, 태스크를 처리한다.
2. ExecutorService
ExecutorService 인터페이스는 Executors 인터페이스에 비해 유용한 기능들이 추가되어 있다.
(ExecutorService 인터페이스는 Executors 인터페이스를 상속하였다.)
구체적으로는 스레드의 상태나 태스크 처리를 중지시키는 것이 가능하게 되었다.
ExecutorService 인터페이스에 정의되어 있는 몇 개의 메소드를 살펴보면...
◎ submit()
- 지정된 태스크를 submit, 실행 결과를 Future 형태로 리턴한다.
◎ isTerminated()
- shutdown 된 후, 모든 태스크의 처리가 완료된 경우 true를 리턴한다.
◎ shutdown()
- 스레드를 중지한다. showdown 이전에 submit 된 태스크까지 처리를 완료한다.
◎ shutdownNow()
- 현재 처리중인 태스크의 정지(stop)를 시도(attempt)하고 대기중인 태스크의 처리를 정지(halt)
한다.
concurrent 패키지에 속한 다수의 인스턴스는 ExecutorService 를 구현(implement) 하고 있다.
3. 스레드풀(Thread Pool)
스레드풀이란 태스크를 큐(Queue)에 추가, 순차적으로 태스크를 처리하는 멀티스레드 형식의 하나
이다. 필요 이상의 스레드를 작성하지 않기 때문에 리소스를 효율적으로 사용할 수 있다. Executors
클래스에는 스레드풀에 관련된 몇 개의 메소드가 존재한다.
# by | 2009/04/08 15:40 | JAVA 향기 | 트랙백 | 덧글(0)








☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]