我在这里修改了基本代码 [github] https://github.com/OpenHFT/Chronicle-Queue/blob/master/docs/How_it_works.adoc
基本上我正在拍摄编年史队列一些相同的编组化对象。我包括了一些打印语句来显示发生了什么。
import java.io.IOException;
import java.nio.file.Files;
import net.openhft.chronicle.queue.ExcerptAppender;
import net.openhft.chronicle.queue.ExcerptTailer;
import net.openhft.chronicle.queue.impl.single.SingleChronicleQueue;
import net.openhft.chronicle.queue.impl.single.SingleChronicleQueueBuilder;
import net.openhft.chronicle.wire.Marshallable;
public class App {
static class MyObject implements Marshallable {
String name;
int age;
@Override
public String toString() {
//return "";
return Marshallable.$toString(this);
}
}
public static void main(String[] args) throws IOException {
// will write the .cq4 file to working directory
SingleChronicleQueue queue = SingleChronicleQueueBuilder.builder().path(Files
.createTempDirectory("queue").toFile()).build();
ExcerptAppender appender = queue.acquireAppender();
ExcerptTailer tailer = queue.createTailer();
MyObject me = new MyObject();
me.name = "rob";
me.age = 40;
System.out.println("1. Tailer is Present = " + tailer.readingDocument().isPresent() + ", Tailer Current Index = " + tailer.index() + ", End = " + queue.createTailer().toEnd().index());
// write 'MyObject' to the queue
appender.writeDocument(me);
appender.writeDocument(me);
appender.writeDocument(me);
appender.writeDocument(me);
System.out.println("2. Tailer is Present = " + tailer.readingDocument().isPresent() + ", Tailer Current Index = " + tailer.index() + ", End = " + queue.createTailer().toEnd().index());
// read 'MyObject' from the queue
MyObject result = new MyObject();
tailer.readDocument(result);
System.out.println("3. Tailer is Present = " + tailer.readingDocument().isPresent() + ", Tailer Current Index = " + tailer.index() + ", End = " + queue.createTailer().toEnd().index());
System.out.println(result);
try {
Thread.sleep(500);
} catch (Exception e){
System.out.println(e);
}
System.out.println("Tailer is Present = " + tailer.readingDocument().isPresent() + ", Tailer Current Index = " + tailer.index() + ", End = " + queue.createTailer().toEnd().index());
}
}
输出
1. Tailer is Present = false, Tailer Current Index = 0, End = 0
2. Tailer is Present = true, Tailer Current Index = 78129750081536, End = 78129750081540
3. Tailer is Present = false, Tailer Current Index = 78129750081536, End = 78129750081540
!chron.App$MyObject {
name: !!null "",
age: 0
}
Tailer is Present = false, Tailer Current Index = 78129750081536, End = 78129750081540
所以根据我的理解......我创建了一个静态对象。我已经把它喂给了编年史队列四次,它们都是同一个对象。您可以看到编年史队列中总共有四个对象。结束索引 - 开始索引。
Trailer.readingDocument().isPresent() 只能看到创建的第一个对象。之后它返回错误...
如果队列中有对象,那么为什么 readingDocument().isPresent() 返回 false?另外为什么对象返回null?
编辑 - 版本实现 'net.openhft:chronicle-queue:5.17.25'