allow to exit w/o confirmation for processes which run w/o visible progresses (i...
[fedora-idea.git] / platform / platform-api / src / com / intellij / openapi / progress / AbstractTaskQueue.java
blob0233087d3c9657bead091ec1c801a9c41a833b50
1 /*
2 * Copyright 2000-2009 JetBrains s.r.o.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package com.intellij.openapi.progress;
18 import com.intellij.openapi.application.ApplicationManager;
19 import com.intellij.openapi.diagnostic.Logger;
21 import java.util.LinkedList;
22 import java.util.Queue;
24 public abstract class AbstractTaskQueue<T> {
25 private final static Logger LOG = Logger.getInstance("#com.intellij.openapi.progress.AbstractTaskQueue");
27 private final Object myLock;
28 private final Queue<T> myQueue;
29 private boolean myActive;
30 protected final Runnable myQueueWorker;
32 public AbstractTaskQueue() {
33 myLock = new Object();
34 myQueue = new LinkedList<T>();
35 myActive = false;
36 myQueueWorker = new MyWorker();
39 /**
40 * !!! done under lock! (to allow single failures when putting into the execution queue)
41 * Should run {@link #myQueueWorker}
43 protected abstract void runMe();
44 protected abstract void runStuff(T stuff);
46 public void run(final T stuff) {
47 if (ApplicationManager.getApplication().isUnitTestMode()) {
48 runStuff(stuff);
49 return;
51 boolean impulseGiven = false;
52 synchronized (myLock) {
53 try {
54 myQueue.add(stuff);
55 if (! myActive) {
56 runMe();
57 impulseGiven = true;
59 } catch (Throwable t) {
60 LOG.info(t);
61 throw t instanceof RuntimeException ? ((RuntimeException) t) : new RuntimeException(t);
62 } finally {
63 if ((! myActive) && impulseGiven) {
64 myActive = true;
70 private class MyWorker implements Runnable {
71 public void run() {
72 while (true) {
73 try {
74 final T stuff;
75 synchronized (myLock) {
76 stuff = myQueue.poll();
78 // each task is executed only once, once it has been taken from the queue..
79 runStuff(stuff);
80 } catch (Throwable t) {
81 LOG.info(t);
82 } finally {
83 synchronized (myLock) {
84 if (myQueue.isEmpty()) {
85 myActive = false;
86 return;