Skip to content

Instantly share code, notes, and snippets.

@vietj
Created May 6, 2011 15:39
Show Gist options
  • Save vietj/959191 to your computer and use it in GitHub Desktop.
Save vietj/959191 to your computer and use it in GitHub Desktop.
/*
* Copyright (C) 2010 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.crsh;
import org.crsh.term.Term;
import org.crsh.term.TermEvent;
import java.io.IOException;
import java.util.concurrent.PriorityBlockingQueue;
/**
* @author <a href="mailto:julien.viet@exoplatform.com">Julien Viet</a>
*/
public class EventQueue {
/** . */
private final Term term;
/** . */
private final PriorityBlockingQueue<TermEvent> queue;
/** . */
private Thread thread;
/** . */
private final Object lock;
/** . */
private volatile boolean priorityMode;
/** . */
private volatile boolean done;
public EventQueue(Term term) {
this.term = term;
this.queue = new PriorityBlockingQueue<TermEvent>(10);
this.lock = new Object();
this.priorityMode = false;
this.done = false;
}
public void start() {
if (thread != null) {
throw new IllegalStateException();
}
this.thread = new Thread() {
@Override
public void run() {
while (!done) {
try {
TermEvent event = term.read();
queue.add(event);
synchronized (lock) {
lock.notifyAll();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
this.thread.start();
}
public void stop() {
if (thread != null) {
done = true;
term.close();
}
}
public int getSize() {
return queue.size();
}
public void setPriorityMode(boolean value) {
this.priorityMode = value;
synchronized (lock) {
lock.notifyAll();
}
}
public TermEvent next() throws InterruptedException {
while (true) {
if (priorityMode) {
TermEvent event = queue.take();
if (event instanceof TermEvent.Break || event instanceof TermEvent.Close) {
return event;
} else {
queue.add(event);
synchronized (lock) {
lock.wait();
}
}
} else {
return queue.take();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment