View Javadoc
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  	public void start(int totalTasks) {
91  		if (!isMainThread())
92  			throw new IllegalStateException();
93  		pm.start(totalTasks);
94  	}
95  
96  	public void beginTask(String title, int totalWork) {
97  		if (!isMainThread())
98  			throw new IllegalStateException();
99  		pm.beginTask(title, totalWork);
100 	}
101 
102 	/** Notify the monitor a worker is starting. */
103 	public void startWorker() {
104 		startWorkers(1);
105 	}
106 
107 	/**
108 	 * Notify the monitor of workers starting.
109 	 *
110 	 * @param count
111 	 *            the number of worker threads that are starting.
112 	 */
113 	public void startWorkers(int count) {
114 		workers.addAndGet(count);
115 	}
116 
117 	/** Notify the monitor a worker is finished. */
118 	public void endWorker() {
119 		if (workers.decrementAndGet() == 0)
120 			process.release();
121 	}
122 
123 	/**
124 	 * Non-blocking poll for pending updates.
125 	 *
126 	 * This method can only be invoked by the same thread that allocated this
127 	 * ThreadSafeProgressMonior.
128 	 */
129 	public void pollForUpdates() {
130 		assert isMainThread();
131 		doUpdates();
132 	}
133 
134 	/**
135 	 * Process pending updates and wait for workers to finish.
136 	 *
137 	 * This method can only be invoked by the same thread that allocated this
138 	 * ThreadSafeProgressMonior.
139 	 *
140 	 * @throws InterruptedException
141 	 *             if the main thread is interrupted while waiting for
142 	 *             completion of workers.
143 	 */
144 	public void waitForCompletion() throws InterruptedException {
145 		assert isMainThread();
146 		while (0 < workers.get()) {
147 			doUpdates();
148 			process.acquire();
149 		}
150 		doUpdates();
151 	}
152 
153 	private void doUpdates() {
154 		int cnt = pendingUpdates.getAndSet(0);
155 		if (0 < cnt)
156 			pm.update(cnt);
157 	}
158 
159 	public void update(int completed) {
160 		if (0 == pendingUpdates.getAndAdd(completed))
161 			process.release();
162 	}
163 
164 	public boolean isCancelled() {
165 		lock.lock();
166 		try {
167 			return pm.isCancelled();
168 		} finally {
169 			lock.unlock();
170 		}
171 	}
172 
173 	public void endTask() {
174 		if (!isMainThread())
175 			throw new IllegalStateException();
176 		pm.endTask();
177 	}
178 
179 	private boolean isMainThread() {
180 		return Thread.currentThread() == mainThread;
181 	}
182 }