blob: 39f8efd3272607ed6ac219b1b42bf9a4cb076a80 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2016 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.certsrv.util;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;
/** A locking mechanism for loading or reloading an initially
* unknown number of items.
*
* The "producer" is the thread that loads items, informing the
* Loader when each item is loaded and how many items there are
* (when that fact becomes known).
*
* Other threads can await the completion of a (re)loading
* process.
*/
public class AsyncLoader {
private CountDownLatch producerInitialised = new CountDownLatch(1);
private ReentrantLock loadingLock = new ReentrantLock();
private Integer numItems = null;
private int numItemsLoaded = 0;
/**
* Acquire the lock as a producer.
*/
public void startLoading() {
numItems = null;
numItemsLoaded = 0;
loadingLock.lock();
producerInitialised.countDown();
}
/**
* Increment the number of items loaded by 1. If the number
* of items is known and that many items have been loaded,
* unlock the loader.
*/
public void increment() {
numItemsLoaded += 1;
checkLoadDone();
}
/**
* Set the number of items. If the number of items already
* loaded is equal to or greater than the number, unlock the
* loader.
*/
public void setNumItems(Integer n) {
numItems = n;
checkLoadDone();
}
private void checkLoadDone() {
if (numItems != null && numItemsLoaded >= numItems) {
while (loadingLock.isHeldByCurrentThread())
loadingLock.unlock();
}
}
public void awaitLoadDone() throws InterruptedException {
/* A consumer may await upon the Loader immediately after
* starting the producer. To ensure that the producer
* has time to acquire the lock, we use a CountDownLatch.
*/
producerInitialised.await();
loadingLock.lock();
loadingLock.unlock();
}
}
|