Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[아이템 29] DelayedQueue #77

Closed
chldbtjd2272 opened this issue Mar 28, 2020 · 1 comment
Closed

[아이템 29] DelayedQueue #77

chldbtjd2272 opened this issue Mar 28, 2020 · 1 comment
Assignees
Labels
Effective Java 3 이펙티브 자바 3

Comments

@chldbtjd2272
Copy link
Contributor

174쪽 마지막줄
DelayedQueue에 대한 설명과 사용하는 클라이언트는 형변환 없이 곧바로 Delayed클래스의 메서드를 호출하는 예시를 만들어줘

@chldbtjd2272 chldbtjd2272 added this to In progress in 이펙티브 자바 via automation Mar 28, 2020
@csbsjy
Copy link
Contributor

csbsjy commented Mar 28, 2020

일단 책의 질문은 DelayQueue는 제네릭타입을 Delyed로 한정해놓았기 때문에 클라이언트에서는 컴파일타임에
바로 Queue에서 꺼낸 원소가 Delayed라는 것을 알고있고 클라이언트는 형변환없이; 사용할 수 있어. 아래는 극단적으로 로타입으로 선언한 DelayQueue 에서 Delay 타입을 꺼낼 수 있다는거를 보여주는거얌

image

DelayedQueue 는 Queue에 삽입하는 원소들에 "Delay" 시간을 지정해 줄 수 있는 Queue 를 말한다.
즉, 넣고 바로 poll 한다고 뺄 수 있는 것이 아니라, Delay 시간만큼 지나야 뺄 수 있다.

여기 삽입하는 원소는 Delayed 인터페이스를 구현해야하고 구현예시는 아래와 같다.

public class DelayEvent implements Delayed {
    private String data;
    private long startTime;

    public String getData() {
        return data;
    }

    public long getStartTime() {
        return startTime;
    }

    public DelayEvent(String data, long delayInMilliseconds) { // delay 지정시간을 입력하고 
        this.data = data;
        this.startTime = System.currentTimeMillis() + delayInMilliseconds; // 그 이후에 poll 될 수 있도록 세팅
    }

    @Override
    public long getDelay(TimeUnit unit) {
        long diff = startTime - System.currentTimeMillis();
        return unit.convert(diff, TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {   // Queue 안에서 만료시간에 따라 Sorting 되어야하기 때문에 필요
        return (this.startTime - ((DelayEvent) o).startTime) <= 0 ? -1 : 1;
    }
}
package Chap4_Generic.item29.DelayQueue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;

public class DelayEventBroker<T extends DelayEvent> {

    private BlockingQueue<T> queue = new DelayQueue<>();

    public void add(T event){
        System.out.printf("[이벤트추가]--------- %s data : startime : %s", event.getData(), event.getStartTime()+"\n");
        queue.add(event);
    }

    public T poll() throws InterruptedException {
        return queue.poll();
    }
}

미얀 테코로 스레드 테스트 아직 못짜겠어서 일단 메인, , ㅎ ㅎ 민형이꺼 볼게 ^__^ ;

package Chap4_Generic.item29.DelayQueue;

public class DelayEventConsumer {

    public static void main(String[] args) throws InterruptedException {
        DelayEventBroker<DelayEvent> broker = new DelayEventBroker<>();

        DelayEvent delayEvent1 = new DelayEvent("FIRST", 500);
        Thread.sleep(1000);
        DelayEvent delayEvent2 = new DelayEvent("SECOND", 2000);

        broker.add(delayEvent1);
        broker.add(delayEvent2);

        new Thread(() -> {
            while (true) {
                try {
                    DelayEvent event = broker.poll();
                    if (event == null) {
                        System.out.println("Waiting ----");
                        Thread.sleep(1000);
                    } else {
                        System.out.printf("[이벤트소모]--------- %s data : startime : %s", event.getData(), event.getStartTime() + "\n");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}

@csbsjy csbsjy closed this as completed Mar 29, 2020
이펙티브 자바 automation moved this from In progress to Done Mar 29, 2020
@pci2676 pci2676 added the Effective Java 3 이펙티브 자바 3 label Nov 1, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Effective Java 3 이펙티브 자바 3
Projects
Development

No branches or pull requests

3 participants