1 /*
2 * Licensed under the GPL License. You may not use this file except in compliance with the License.
3 * You may obtain a copy of the License at
4 *
5 * https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
6 *
7 * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
8 * WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
9 * PURPOSE.
10 */
11 package psiprobe.tools;
12
13 /**
14 * Simple update-commit lock. This implementation assumes that unlimited number of updates can
15 * happen concurrently. However if commit is in progress any update must wait for it to end.
16 * Likewise commits must wait for any updates to finish before acquiring the lock.
17 *
18 * <p>
19 * Commits themselves are not synchronized. It is allowed for two commits to run concurrently.
20 */
21 public class UpdateCommitLock {
22
23 /** The update count. */
24 private int updateCount;
25
26 /** The commit count. */
27 private int commitCount;
28
29 /** The commit requests. */
30 private int commitRequests;
31
32 /**
33 * Lock for update.
34 *
35 * @throws InterruptedException the interrupted exception
36 */
37 public synchronized void lockForUpdate() throws InterruptedException {
38 while (commitCount > 0 || commitRequests > 0) {
39 wait();
40 }
41 updateCount++;
42 }
43
44 /**
45 * Release update lock.
46 */
47 public synchronized void releaseUpdateLock() {
48 updateCount--;
49 notifyAll();
50 }
51
52 /**
53 * Lock for commit.
54 *
55 * @throws InterruptedException the interrupted exception
56 */
57 public synchronized void lockForCommit() throws InterruptedException {
58 commitRequests++;
59 while (updateCount > 0 || commitCount > 0) {
60 wait();
61 }
62 commitRequests--;
63 commitCount++;
64 }
65
66 /**
67 * Release commit lock.
68 */
69 public synchronized void releaseCommitLock() {
70 commitCount--;
71 notifyAll();
72 }
73
74 }