use of com.questdb.mp.MPSequence in project questdb by bluestreak01.
the class AppendObjectConcurrent method main.
/**
* Multiple threads append to same journal concurrently.
* <p>
* Single append thread receives data from multiple publishers via circular queue using QuestDB's thread messaging mechanism.
* Please refer to my blog post: http://blog.questdb.org/2016/08/the-art-of-thread-messaging.html for more details.
*/
public static void main(String[] args) throws JournalException, InterruptedException {
if (args.length != 1) {
System.out.println("Usage: " + AppendObjectConcurrent.class.getName() + " <path>");
System.exit(1);
}
//
RingQueue<Quote> queue = new RingQueue<>(Quote::new, 4096);
// publisher sequence
final MPSequence pubSequence = new MPSequence(queue.getCapacity());
final SCSequence subSequence = new SCSequence();
// create circular dependency between sequences
pubSequence.then(subSequence).then(pubSequence);
// run configuration
int nThreads = 2;
int nMessages = 1000000;
JournalConfiguration configuration = ModelConfiguration.CONFIG.build(args[0]);
try (Factory factory = new Factory(configuration, 1000, 1, 0)) {
// start publishing threads
for (int i = 0; i < nThreads; i++) {
new Thread(new Publisher(queue, pubSequence, nMessages)).start();
}
// consume messages in main thread
int count = 0;
int deadline = nMessages * nThreads;
try (JournalWriter<Quote> writer = factory.writer(Quote.class)) {
while (count < deadline) {
long cursor = subSequence.next();
if (cursor < 0) {
LockSupport.parkNanos(1);
continue;
}
long available = subSequence.available();
while (cursor < available) {
Quote q = queue.get(cursor++);
q.setTimestamp(System.currentTimeMillis());
try {
writer.append(q);
} catch (JournalException e) {
// append may fail, log and continue
// N.B. this logging uses builder pattern to construct message. Building finishes with $() call.
LOG.error().$("Sequence failed: ").$(cursor - 1).$(e).$();
}
count++;
}
subSequence.done(available - 1);
try {
writer.commit();
} catch (JournalException e) {
// something serious, attempt to rollback
LOG.error().$("Batch commit() failed [").$(available - 1).$(']').$(e).$();
}
}
}
LOG.info().$("Writer done").$();
}
}
Aggregations