All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.xxdb.streaming.client.TopicPoller Maven / Gradle / Ivy

There is a newer version: 3.00.2.2
Show newest version
package com.xxdb.streaming.client;


import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class TopicPoller {
    BlockingQueue> queue;
    List cache=new ArrayList<>();

    public TopicPoller(BlockingQueue> queue) {
        this.queue = queue;
    }

    public void setQueue(BlockingQueue> queue) {
        this.queue = queue;
    }

    public ArrayList poll(long timeout) {
        return poll(timeout, 1);
    }

    public ArrayList poll(long timeout, int size) {
        if(size <= 0)
            throw new IllegalArgumentException("Size must be greater than zero");
        ArrayList list = new ArrayList<>(cache);
        cache.clear();
        LocalTime end=LocalTime.now().plusNanos(timeout*1000000);
        while (list.size() tmp = queue.poll(mileSeconds, TimeUnit.MILLISECONDS);
                if(tmp != null){
                    list.addAll(tmp);
                }
            }catch (InterruptedException e){
                return list;
            }
        }
        return list;
    }

    // take one message from the topic, block if necessary
    public IMessage take() {
        while(true) {
            if (!cache.isEmpty()) {
                IMessage message = cache.get(0);
                cache.remove(0);
                return message;
            }
            try {
                List tmp = queue.take();
                if (tmp != null) {
                    cache.addAll(tmp);
                }
            } catch (InterruptedException e) {
                return null;
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy