package jetbrains.mps.vcs.changesmanager;
/*Generated by MPS */
import org.apache.log4j.Logger;
import org.apache.log4j.LogManager;
import java.util.Queue;
import java.util.LinkedList;
import org.jetbrains.annotations.NotNull;
import org.apache.log4j.Level;
public class SimpleCommandQueue {
private static final Logger LOG = LogManager.getLogger(SimpleCommandQueue.class);
private Thread myThread;
private boolean myDisposed = false;
private boolean myHadExceptions = false;
private final Queue<Runnable> myQueue = new LinkedList<Runnable>();
public SimpleCommandQueue(@NotNull String threadName) {
myThread = new SimpleCommandQueue.MyExecutorThread(threadName);
myThread.start();
}
public void runTask(@NotNull Runnable task) {
if (Thread.currentThread() == myThread) {
task.run();
} else {
addTask(task);
}
}
public void addTask(@NotNull Runnable task) {
synchronized (myQueue) {
myQueue.add(task);
myQueue.notify();
}
}
public void dispose() {
myDisposed = true;
myThread.interrupt();
}
public void assertIsCommandThread() {
assert Thread.currentThread() == myThread;
}
public void assertSoftlyIsCommandThread() {
if (Thread.currentThread() != myThread) {
if (LOG.isEnabledFor(Level.ERROR)) {
LOG.error("", new AssertionError("Current thread is " + Thread.currentThread() + ", but should be " + myThread));
}
}
}
public void setHadExceptions(boolean value) {
myHadExceptions = value;
}
public boolean hadExceptions() {
return myHadExceptions;
}
private class MyExecutorThread extends Thread {
public MyExecutorThread(@NotNull String name) {
super(name);
}
@Override
public void run() {
while (true) {
if (myDisposed) {
return;
}
Runnable task;
synchronized (myQueue) {
while (myQueue.isEmpty()) {
try {
myQueue.wait();
} catch (InterruptedException e) {
return;
}
}
task = myQueue.poll();
}
try {
task.run();
} catch (Throwable e) {
if (e instanceof InterruptedException || e.getCause() instanceof InterruptedException) {
continue;
}
if (LOG.isEnabledFor(Level.ERROR)) {
LOG.error(e.getClass().getName() + " exception in " + getName(), e);
}
myHadExceptions = true;
}
}
}
}
}