1 /*
2 * Copyright (C) 2010, 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.Semaphore;
47 import java.util.concurrent.atomic.AtomicInteger;
48 import java.util.concurrent.locks.ReentrantLock;
49
50 /**
51 * Wrapper around the general {@link org.eclipse.jgit.lib.ProgressMonitor} to
52 * make it thread safe.
53 *
54 * Updates to the underlying ProgressMonitor are made only from the thread that
55 * allocated this wrapper. Callers are responsible for ensuring the allocating
56 * thread uses {@link #pollForUpdates()} or {@link #waitForCompletion()} to
57 * update the underlying ProgressMonitor.
58 *
59 * Only {@link #update(int)}, {@link #isCancelled()}, and {@link #endWorker()}
60 * may be invoked from a worker thread. All other methods of the ProgressMonitor
61 * interface can only be called from the thread that allocates this wrapper.
62 */
63 public class ThreadSafeProgressMonitor implements ProgressMonitor {
64 private final ProgressMonitor pm;
65
66 private final ReentrantLock lock;
67
68 private final Thread mainThread;
69
70 private final AtomicInteger workers;
71
72 private final AtomicInteger pendingUpdates;
73
74 private final Semaphore process;
75
76 /**
77 * Wrap a ProgressMonitor to be thread safe.
78 *
79 * @param pm
80 * the underlying monitor to receive events.
81 */
82 public ThreadSafeProgressMonitor(ProgressMonitor pm) {
83 this.pm = pm;
84 this.lock = new ReentrantLock();
85 this.mainThread = Thread.currentThread();
86 this.workers = new AtomicInteger(0);
87 this.pendingUpdates = new AtomicInteger(0);
88 this.process = new Semaphore(0);
89 }
90
91 /** {@inheritDoc} */
92 @Override
93 public void start(int totalTasks) {
94 if (!isMainThread())
95 throw new IllegalStateException();
96 pm.start(totalTasks);
97 }
98
99 /** {@inheritDoc} */
100 @Override
101 public void beginTask(String title, int totalWork) {
102 if (!isMainThread())
103 throw new IllegalStateException();
104 pm.beginTask(title, totalWork);
105 }
106
107 /**
108 * Notify the monitor a worker is starting.
109 */
110 public void startWorker() {
111 startWorkers(1);
112 }
113
114 /**
115 * Notify the monitor of workers starting.
116 *
117 * @param count
118 * the number of worker threads that are starting.
119 */
120 public void startWorkers(int count) {
121 workers.addAndGet(count);
122 }
123
124 /**
125 * Notify the monitor a worker is finished.
126 */
127 public void endWorker() {
128 if (workers.decrementAndGet() == 0)
129 process.release();
130 }
131
132 /**
133 * Non-blocking poll for pending updates.
134 *
135 * This method can only be invoked by the same thread that allocated this
136 * ThreadSafeProgressMonior.
137 */
138 public void pollForUpdates() {
139 assert isMainThread();
140 doUpdates();
141 }
142
143 /**
144 * Process pending updates and wait for workers to finish.
145 *
146 * This method can only be invoked by the same thread that allocated this
147 * ThreadSafeProgressMonior.
148 *
149 * @throws java.lang.InterruptedException
150 * if the main thread is interrupted while waiting for
151 * completion of workers.
152 */
153 public void waitForCompletion() throws InterruptedException {
154 assert isMainThread();
155 while (0 < workers.get()) {
156 doUpdates();
157 process.acquire();
158 }
159 doUpdates();
160 }
161
162 private void doUpdates() {
163 int cnt = pendingUpdates.getAndSet(0);
164 if (0 < cnt)
165 pm.update(cnt);
166 }
167
168 /** {@inheritDoc} */
169 @Override
170 public void update(int completed) {
171 if (0 == pendingUpdates.getAndAdd(completed))
172 process.release();
173 }
174
175 /** {@inheritDoc} */
176 @Override
177 public boolean isCancelled() {
178 lock.lock();
179 try {
180 return pm.isCancelled();
181 } finally {
182 lock.unlock();
183 }
184 }
185
186 /** {@inheritDoc} */
187 @Override
188 public void endTask() {
189 if (!isMainThread())
190 throw new IllegalStateException();
191 pm.endTask();
192 }
193
194 private boolean isMainThread() {
195 return Thread.currentThread() == mainThread;
196 }
197 }