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 * </p> 21 */ 22 public class UpdateCommitLock { 23 24 /** The update count. */ 25 private int updateCount; 26 27 /** The commit count. */ 28 private int commitCount; 29 30 /** The commit requests. */ 31 private int commitRequests; 32 33 /** 34 * Lock for update. 35 * 36 * @throws InterruptedException the interrupted exception 37 */ 38 public synchronized void lockForUpdate() throws InterruptedException { 39 while (commitCount > 0 || commitRequests > 0) { 40 wait(); 41 } 42 updateCount++; 43 } 44 45 /** 46 * Release update lock. 47 */ 48 public synchronized void releaseUpdateLock() { 49 updateCount--; 50 notifyAll(); 51 } 52 53 /** 54 * Lock for commit. 55 * 56 * @throws InterruptedException the interrupted exception 57 */ 58 public synchronized void lockForCommit() throws InterruptedException { 59 commitRequests++; 60 while (updateCount > 0 || commitCount > 0) { 61 wait(); 62 } 63 commitRequests--; 64 commitCount++; 65 } 66 67 /** 68 * Release commit lock. 69 */ 70 public synchronized void releaseCommitLock() { 71 commitCount--; 72 notifyAll(); 73 } 74 75 }