1 /*
2 * Copyright (C) 2008-2011, Google Inc.
3 * and other copyright owners as documented in the project's IP log.
4 *
5 * This program and the accompanying materials are made available
6 * under the terms of the Eclipse Distribution License v1.0 which
7 * accompanies this distribution, is reproduced below, and is
8 * available at http://www.eclipse.org/org/documents/edl-v10.php
9 *
10 * All rights reserved.
11 *
12 * Redistribution and use in source and binary forms, with or
13 * without modification, are permitted provided that the following
14 * conditions are met:
15 *
16 * - Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 *
19 * - Redistributions in binary form must reproduce the above
20 * copyright notice, this list of conditions and the following
21 * disclaimer in the documentation and/or other materials provided
22 * with the distribution.
23 *
24 * - Neither the name of the Eclipse Foundation, Inc. nor the
25 * names of its contributors may be used to endorse or promote
26 * products derived from this software without specific prior
27 * written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 */
43
44 package org.eclipse.jgit.lib;
45
46 import java.util.concurrent.Executors;
47 import java.util.concurrent.Future;
48 import java.util.concurrent.ScheduledThreadPoolExecutor;
49 import java.util.concurrent.ThreadFactory;
50 import java.util.concurrent.TimeUnit;
51
52 /** ProgressMonitor that batches update events. */
53 public abstract class BatchingProgressMonitor implements ProgressMonitor {
54 private static final ScheduledThreadPoolExecutor alarmQueue;
55
56 static final Object alarmQueueKiller;
57
58 static {
59 // To support garbage collection, start our thread but
60 // swap out the thread factory. When our class is GC'd
61 // the alarmQueueKiller will finalize and ask the executor
62 // to shutdown, ending the worker.
63 //
64 int threads = 1;
65 alarmQueue = new ScheduledThreadPoolExecutor(threads,
66 new ThreadFactory() {
67 private final ThreadFactory baseFactory = Executors
68 .defaultThreadFactory();
69
70 public Thread newThread(Runnable taskBody) {
71 Thread thr = baseFactory.newThread(taskBody);
72 thr.setName("JGit-AlarmQueue"); //$NON-NLS-1$
73 thr.setDaemon(true);
74 return thr;
75 }
76 });
77 alarmQueue.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
78 alarmQueue.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
79 alarmQueue.prestartAllCoreThreads();
80
81 // Now that the threads are running, its critical to swap out
82 // our own thread factory for one that isn't in the ClassLoader.
83 // This allows the class to GC.
84 //
85 alarmQueue.setThreadFactory(Executors.defaultThreadFactory());
86
87 alarmQueueKiller = new Object() {
88 @Override
89 protected void finalize() {
90 alarmQueue.shutdownNow();
91 }
92 };
93 }
94
95 private long delayStartTime;
96
97 private TimeUnit delayStartUnit = TimeUnit.MILLISECONDS;
98
99 private Task task;
100
101 /**
102 * Set an optional delay before the first output.
103 *
104 * @param time
105 * how long to wait before output. If 0 output begins on the
106 * first {@link #update(int)} call.
107 * @param unit
108 * time unit of {@code time}.
109 */
110 public void setDelayStart(long time, TimeUnit unit) {
111 delayStartTime = time;
112 delayStartUnit = unit;
113 }
114
115 public void start(int totalTasks) {
116 // Ignore the number of tasks.
117 }
118
119 public void beginTask(String title, int work) {
120 endTask();
121 task = new Task(title, work);
122 if (delayStartTime != 0)
123 task.delay(delayStartTime, delayStartUnit);
124 }
125
126 public void update(int completed) {
127 if (task != null)
128 task.update(this, completed);
129 }
130
131 public void endTask() {
132 if (task != null) {
133 task.end(this);
134 task = null;
135 }
136 }
137
138 public boolean isCancelled() {
139 return false;
140 }
141
142 /**
143 * Update the progress monitor if the total work isn't known,
144 *
145 * @param taskName
146 * name of the task.
147 * @param workCurr
148 * number of units already completed.
149 */
150 protected abstract void onUpdate(String taskName, int workCurr);
151
152 /**
153 * Finish the progress monitor when the total wasn't known in advance.
154 *
155 * @param taskName
156 * name of the task.
157 * @param workCurr
158 * total number of units processed.
159 */
160 protected abstract void onEndTask(String taskName, int workCurr);
161
162 /**
163 * Update the progress monitor when the total is known in advance.
164 *
165 * @param taskName
166 * name of the task.
167 * @param workCurr
168 * number of units already completed.
169 * @param workTotal
170 * estimated number of units to process.
171 * @param percentDone
172 * {@code workCurr * 100 / workTotal}.
173 */
174 protected abstract void onUpdate(String taskName, int workCurr,
175 int workTotal, int percentDone);
176
177 /**
178 * Finish the progress monitor when the total is known in advance.
179 *
180 * @param taskName
181 * name of the task.
182 * @param workCurr
183 * total number of units processed.
184 * @param workTotal
185 * estimated number of units to process.
186 * @param percentDone
187 * {@code workCurr * 100 / workTotal}.
188 */
189 protected abstract void onEndTask(String taskName, int workCurr,
190 int workTotal, int percentDone);
191
192 private static class Task implements Runnable {
193 /** Title of the current task. */
194 private final String taskName;
195
196 /** Number of work units, or {@link ProgressMonitor#UNKNOWN}. */
197 private final int totalWork;
198
199 /** True when timer expires and output should occur on next update. */
200 private volatile boolean display;
201
202 /** Scheduled timer, supporting cancellation if task ends early. */
203 private Future<?> timerFuture;
204
205 /** True if the task has displayed anything. */
206 private boolean output;
207
208 /** Number of work units already completed. */
209 private int lastWork;
210
211 /** Percentage of {@link #totalWork} that is done. */
212 private int lastPercent;
213
214 Task(String taskName, int totalWork) {
215 this.taskName = taskName;
216 this.totalWork = totalWork;
217 this.display = true;
218 }
219
220 void delay(long time, TimeUnit unit) {
221 display = false;
222 timerFuture = alarmQueue.schedule(this, time, unit);
223 }
224
225 public void run() {
226 display = true;
227 }
228
229 void update(BatchingProgressMonitor pm, int completed) {
230 lastWork += completed;
231
232 if (totalWork == UNKNOWN) {
233 // Only display once per second, as the alarm fires.
234 if (display) {
235 pm.onUpdate(taskName, lastWork);
236 output = true;
237 restartTimer();
238 }
239 } else {
240 // Display once per second or when 1% is done.
241 int currPercent = lastWork * 100 / totalWork;
242 if (display) {
243 pm.onUpdate(taskName, lastWork, totalWork, currPercent);
244 output = true;
245 restartTimer();
246 lastPercent = currPercent;
247 } else if (currPercent != lastPercent) {
248 pm.onUpdate(taskName, lastWork, totalWork, currPercent);
249 output = true;
250 lastPercent = currPercent;
251 }
252 }
253 }
254
255 private void restartTimer() {
256 display = false;
257 timerFuture = alarmQueue.schedule(this, 1, TimeUnit.SECONDS);
258 }
259
260 void end(BatchingProgressMonitor pm) {
261 if (output) {
262 if (totalWork == UNKNOWN) {
263 pm.onEndTask(taskName, lastWork);
264 } else {
265 int pDone = lastWork * 100 / totalWork;
266 pm.onEndTask(taskName, lastWork, totalWork, pDone);
267 }
268 }
269 if (timerFuture != null)
270 timerFuture.cancel(false /* no interrupt */);
271 }
272 }
273 }