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

goja.core.libs.event.EventStream Maven / Gradle / Ivy

The newest version!
/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package goja.core.libs.event;

import goja.core.libs.Promise;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;

/**
 * 

.

* * @author sagyf yang * @version 1.0 2014-09-11 13:24 * @since JDK 1.6 */ public class EventStream { final int bufferSize; final ConcurrentLinkedQueue events = new ConcurrentLinkedQueue(); final List> waiting = Collections.synchronizedList(new ArrayList>()); public EventStream() { this.bufferSize = 100; } public EventStream(int maxBufferSize) { this.bufferSize = maxBufferSize; } public synchronized Promise nextEvent() { if (events.isEmpty()) { LazyTask task = new LazyTask(); waiting.add(task); return task; } return new LazyTask(events.peek()); } public synchronized void publish(T event) { if (events.size() > bufferSize) { events.poll(); } events.offer(event); notifyNewEvent(); } void notifyNewEvent() { T value = events.peek(); for (Promise task : waiting) { task.invoke(value); } waiting.clear(); } class LazyTask extends Promise { public LazyTask() { } public LazyTask(T value) { invoke(value); } @Override public T get() throws InterruptedException, ExecutionException { T value = super.get(); markAsRead(value); return value; } @Override public T getOrNull() { T value = super.getOrNull(); markAsRead(value); return value; } private void markAsRead(T value) { if (value != null) { events.remove(value); } } } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy