자바 5.0 고성능 프로그램 개발 총화 (계속 보충)

24360 단어 자바
(우정 알림: 본 블 로그 글 은 전 재 를 환영 하지만 출처: 진 신 한, http://www.blogjava.net/hankchen) 1. 동시 집합 류 의 선택 을 밝 혀 주 십시오.
    동기 화 된 집합 류 HashtableVector, 그리고 동기 화 된 포장 기 류 Collections.synchronizedMapCollections.synchronizedListMapList 에 기본 적 인 조건 부 스 레 드 안전 실현 을 제공 했다.그러나 일부 요소 로 인해 고도 의 동시성 을 가 진 응용 프로그램 에 적용 되 지 않 는 다. 그들의 집합 범위 의 단일 잠 금 특성 은 신축성 에 있어 장애 가 되 고 ConcurrentModificationException s 이상 이 발생 하지 않도록 비교적 긴 시간 안에 집합 을 잠 가 야 하 는 경우 가 많다.ConcurrentHashMapCopyOnWriteArrayList 은 더욱 높 은 동시성 을 제공 하 는 동시에 스 레 드 안전성 도 지 켰 으 며 호출 자의 약속 에 대해 약간의 할인 을 했 을 뿐이다.ConcurrentHashMapCopyOnWriteArrayList 은 귀하 가 HashMap 또는 ArrayList 을 사용 하 는 어느 곳 에서 든 반드시 유용 한 것 이 아니 라 특정한 공공 해결 방안 을 최적화 시 키 는 디자인 입 니 다.많은 병렬 응용 프로그램 이 그들의 사용 에서 이익 을 얻 을 것 이다.
요약: 다 중 스 레 드 병발 상황 에서 ConcurrentModificationException s 이상 을 피하 기 위해 ConcurrentHashMapCopyOnWriteArrayList
을 사용 하 는 것 을 권장 합 니 다. :ConcurrentLinkedQueue、CopyOnWriteArraySet、LinkedBlockingQueue、ArrayBlockingQueue
 
, , : A*2=a<<1 A/2=a>>1   AtomicInteger ( ), Integer 。 , Number , 。
예 를 들 면:
    private AtomicInteger bomdIdCreator = new AtomicInteger(); //셀 프 시리 얼 번호
    /**
     *새로운 ID 를 받 아 자체 증가 유지
     *@return
     */
    public int getNewBombID(){
         return bomdIdCreator.addAndGet(1);
} , , 。 : 1. 、 : synchronized 2. :( wait notify notifyAll 3. ReentrantLock 

:ReentrantLock
Lock synchronized , 。 : , lock try / , :
 class X {
   private final ReentrantLock lock = new ReentrantLock();
   // ...
   public void m() {
     lock.lock(); // block until condition holds
     try {
       // ... method body
     } finally {
       lock.unlock()
     }
   }
 }
  Doug Lea util.concurrent , 、 、 。 ThreadPoolExecutor 。 , , util.concurrent : , , ( ) 。 Executors Executors.newCachedThreadPool() ( , )、 Executors.newFixedThreadPool(int) ( ) Executors.newSingleThreadExecutor() ( ), 。
public class ThreadPoolExecutorTest {
    final static ExecutorService threadPool = Executors. newCachedThreadPool (); / 간단 한 스 레 드 풀 구현
    /**
     * @param args
     */
    public static void main(String[] args) {
       for(int i=0;i<10;i++){
           threadPool.execute(new Runnable(){
              public void run() {
                  System.out.println("aaa"+this.getClass().getName());
                  //do other things
              }
           });
       }
    }
}   1. Timer 2.  ScheduledThreadPoolExecutor JDK 1.5 3.  Quatz Java 5.0 java.util.concurrent ScheduledThreadPoolExecutor , , Timer ScheduledThreadPoolExecutor scheduleAtFixedRate() scheduleWithFixedDelay() Timer scheduleWithFixedDelay() ScheduledThreadPoolExecutor ScheduledExecutorService
1)public static final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(2);
2)public static final ScheduledThreadPoolExecutor scheduledExecutor=new ScheduledThreadPoolExecutor(2);
, 。

 
ScheduledThreadPoolExecutor Timer 1.      Timer // void schedule(TimerTask task, Date time) // void schedule(TimerTask task, Date firstTime, long period) // void schedule(TimerTask task, long delay) // void schedule(TimerTask task, long delay, long period) // void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) // void scheduleAtFixedRate(TimerTask task, long delay, long period)   period scheduleAtFixedRate period 。 , schedule() scheduleAtFixedRate() , 。   2.      ScheduledThreadPoolExecutor // <V>ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) // ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) // ( Timer.scheduleAtFixedRate()) ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) // ( Timer.schedule()) ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)   1 Timer , ; ScheduledThreadPoolExecutor 2 Timer TimerTask TimerTask TimerTask ScheduledThreadPoolExecutor 3 Timer TimerTask , , Timer TimerTask TimerTask ScheduledThreadPoolExecutor , 。 Timer JDK1.5 Timer
( : , : ,http://www.blogjava.net/hankchen

좋은 웹페이지 즐겨찾기