2 * ========================LICENSE_START=================================
5 * Copyright (C) 2019 Nordix Foundation
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ========================LICENSE_END===================================
21 package org.oransc.policyagent.repository;
23 import java.util.ArrayList;
24 import java.util.Iterator;
25 import java.util.LinkedList;
26 import java.util.List;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
31 import reactor.core.publisher.Mono;
32 import reactor.core.publisher.MonoSink;
35 * A resource lock. Exclusive means that the caller takes exclusive ownership of
36 * the resurce. Non exclusive lock means that several users can lock the
37 * resource (for shared usage).
40 private static final Logger logger = LoggerFactory.getLogger(Lock.class);
42 private boolean isExclusive = false;
43 private int lockCounter = 0;
44 private final List<LockRequest> lockRequestQueue = new LinkedList<>();
45 private static AsynchCallbackExecutor callbackProcessor = new AsynchCallbackExecutor();
47 private static class AsynchCallbackExecutor implements Runnable {
48 private List<LockRequest> lockRequestQueue = new LinkedList<>();
50 public AsynchCallbackExecutor() {
51 Thread thread = new Thread(this);
55 public synchronized void addAll(List<LockRequest> requests) {
56 this.lockRequestQueue.addAll(requests);
64 for (LockRequest request : consume()) {
65 request.callback.success(request.lock);
69 } catch (InterruptedException e) {
70 Thread.currentThread().interrupt();
71 logger.error("Interrupted {}", e.getMessage());
75 private synchronized List<LockRequest> consume() {
76 List<LockRequest> q = this.lockRequestQueue;
77 this.lockRequestQueue = new LinkedList<>();
81 @SuppressWarnings("java:S2274")
82 private synchronized void waitForNewEntries() throws InterruptedException {
83 if (this.lockRequestQueue.isEmpty()) {
89 public enum LockType {
93 /** The caller thread will be blocked util the lock is granted. */
94 public synchronized void lockBlocking(LockType locktype) {
95 while (!tryLock(locktype)) {
100 /** Reactive version. The Lock will be emitted when the lock is granted */
101 public synchronized Mono<Lock> lock(LockType lockType) {
102 if (tryLock(lockType)) {
103 return Mono.just(this);
105 return Mono.create(monoSink -> addToQueue(monoSink, lockType));
109 public Mono<Lock> unlock() {
110 return Mono.create(monoSink -> {
112 monoSink.success(this);
116 public void unlockBlocking() {
117 synchronized (this) {
118 if (lockCounter <= 0) {
119 lockCounter = -1; // Might as well stop, to make it easier to find the problem
120 logger.error("Number of unlocks must match the number of locks");
123 if (lockCounter == 0) {
128 this.processQueuedEntries();
132 public String toString() {
133 return "Lock cnt: " + this.lockCounter + " exclusive: " + this.isExclusive + " queued: "
134 + this.lockRequestQueue.size();
137 /** returns the current number of granted locks */
138 public synchronized int getLockCounter() {
139 return this.lockCounter;
142 private void processQueuedEntries() {
143 List<LockRequest> granted = new ArrayList<>();
144 synchronized (this) {
145 for (Iterator<LockRequest> i = lockRequestQueue.iterator(); i.hasNext();) {
146 LockRequest request = i.next();
147 if (tryLock(request.lockType)) {
149 granted.add(request);
153 callbackProcessor.addAll(granted);
156 private static class LockRequest {
157 final MonoSink<Lock> callback;
158 final LockType lockType;
161 LockRequest(MonoSink<Lock> callback, LockType lockType, Lock lock) {
162 this.callback = callback;
163 this.lockType = lockType;
168 private synchronized void addToQueue(MonoSink<Lock> callback, LockType lockType) {
169 lockRequestQueue.add(new LockRequest(callback, lockType, this));
172 @SuppressWarnings("java:S2274") // Always invoke wait() and await() methods inside a loop
173 private synchronized void waitForUnlock() {
176 } catch (InterruptedException e) {
177 logger.warn("waitForUnlock interrupted", e);
178 Thread.currentThread().interrupt();
182 private boolean tryLock(LockType lockType) {
183 if (this.isExclusive) {
186 if (lockType == LockType.EXCLUSIVE && lockCounter > 0) {
190 this.isExclusive = lockType == LockType.EXCLUSIVE;