com.xxdb.streaming.client.TopicPoller Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of dolphindb-javaapi Show documentation
Show all versions of dolphindb-javaapi Show documentation
The messaging and data conversion protocol between Java and DolphinDB server
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;
}
}
}
}