具有优先级的消费者/生产者模式

时间:2018-05-25 11:11:59

标签: java

设计问题:我们有一个现有的界面(和工作实现),如下所示:

public interface Service {
   CompletableFuture<ResponseCar> getResponseOfApple(String url, UUID id);
   CompletableFuture<ResponsePear> getResponseOfPear(String url, UUID id);
}

执行该操作只会返回CompletableFuture - 客户端的OkHttp

现在我们有了一个新的要求:在缓存中保存所有可能的返回(因为响应是来自REST-API的JSON对象)。我们希望使用后台工作程序缓存所有ApplePear,后者仅更新所有后续工作程序。

但是当用户想要一个尚未在缓存中的Pear时,那么这个任务作为后台任务具有更高的优势。

我的想法是PriorityBlockingQueue这样的类型:

@RequiredArgsConstructor
public class PrioritizedQueueElement extends Observable implements Comparable<PrioritizedQueueElement> {

    @NonNull
    @Getter
    private final Object argument;

    @Getter
    @Setter
    private Object returnValue;

    @NonNull
    @Getter
    private final QueueElementType priority;


    @Override
    public int compareTo(final PrioritizedQueueElement o) {
        if (o == null || this.priority == null || o.priority == null) {
            throw new NullPointerException("wrong value");
        }

        return this.priority.compareTo(o.priority);
    }


    public <T> T getValue() {
        return (T) this.returnValue;
    }

    public void setReturnValue(final Object value) {
        this.returnValue = value;
        this.setChanged();
        this.notifyObservers();
    }
}

public enum QueueElementType {
    ONE_TIME_HIGH_PRIORITY,
    ONE_TIME_LOW_PRIORITY,
    RECURRENT_HIGH_PRIORITY,
    RECURRENT_LOW_PRIORITY
}

问题

如何实现新实现实现旧接口?我试图将PrioritizedQueueElement设为Observable,但不知道如何从Observable转到CompletableFuture? 或者我的设计理念是一种可怕的错误方式?

0 个答案:

没有答案
相关问题