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