aboutsummaryrefslogtreecommitdiffstats
path: root/messagebus/src/main/java/com/yahoo/messagebus/test/QueueAdapter.java
blob: dd819d30d0cb750a491d3a10be71bb9a17ad3c40 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus.test;

import com.yahoo.messagebus.*;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author <a href="mailto:havardpe@yahoo-inc.com">Haavard Pettersen</a>
 */
public class QueueAdapter implements MessageHandler, ReplyHandler {

    private final Queue<Routable> queue = new ConcurrentLinkedQueue<>();

    @Override
    public void handleMessage(Message message) {
        queue.offer(message);
    }

    @Override
    public void handleReply(Reply reply) {
        queue.offer(reply);
    }

    public Routable dequeue() {
        return queue.poll();
    }

    public boolean isEmpty() {
        return queue.isEmpty();
    }

    public int size() {
        return queue.size();
    }

    public boolean waitSize(int size, int seconds) {
        long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(seconds);
        while (true) {
            if (size() == size) {
                return true;
            }
            if (System.currentTimeMillis() > timeout) {
                return false;
            }
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            }
        }
    }
}