2016-10-19 7 views
0

나는 멀티 스레드 응용 프로그램을 가지고 있습니다. 각 스레드는 스트리밍 데이터를 듣고 스트림에서 이벤트를 처리합니다.SSE 이벤트 소스 리스너로 잠자는 스레드 깨우기

런() 메소드는 현재 다음과 같습니다

public void run() { 

    Client client ClientBuilder.newBuilder().register(SseFeature.class).build(); 
    WebTarget target = client.target("https://stream.example.com/"); 

    org.glassfish.jersey.media.sse.EventSource eventSource = 
      new org.glassfish.jersey.media.sse.EventSource(target) { 

     @Override 
     public void onEvent(InboundEvent inboundEvent) { 
      System.out.println(inboundEvent.getName()+ " :: " + threadId); 

      ... 

     } 
    }; 


    while (true) { 

     try{ 
      Thread.sleep(500L); 
     }catch(InterruptedException e){ 
      ... 
     }   
    } 
} 

는 내가 달성하고자하는 스레드가 가능한 한 많이 자고 이벤트가 스트림에 도착하는 경우에만 각성 될 것입니다. 그런 식으로 대부분의 쓰레드는 잠들고 CPU 부하를 피할 수 있습니다. 스레드가 Thread.sleep()을 사용하여 잠자기 상태 일 때 이벤트에 의해 각성된다는 확신이 없습니다. 결국, eventSource 리스너는 잠자기 된 동일한 스레드에 있습니다.

그래서 본질적으로 제 질문은 그 eventSource가 스레드를 깨울 수있는 방법이 있습니까?

답변

0

다음은 트릭을 수행 한 것 같습니다. eventInput.read()는 읽을 항목이있을 때까지 차단해야합니다.

public void run() { 
    Client client = ClientBuilder.newBuilder().register(SseFeature.class).build(); 
    WebTarget target = client.target("https://stream.example.com/"); 

    EventInput eventInput = target.request().get(EventInput.class); 
    while (!eventInput.isClosed()) { 
     final InboundEvent inboundEvent = eventInput.read(); 
     if (inboundEvent == null) { 
      // connection has been closed 
      break; 
     } 

     onEvent(inboundEvent);   
    } 
} 

protected void onEvent(InboundEvent inboundEvent) { 
    .... 
} 
관련 문제