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 throw new NullPointerException("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;
136 /** returns the current number of granted locks */
137 public synchronized int getLockCounter() {
138 return this.lockCounter;
141 private void processQueuedEntries() {
142 List<LockRequest> granted = new ArrayList<>();
143 synchronized (this) {
144 for (Iterator<LockRequest> i = lockRequestQueue.iterator(); i.hasNext();) {
145 LockRequest request = i.next();
146 if (tryLock(request.lockType)) {
148 granted.add(request);
152 callbackProcessor.addAll(granted);
155 private static class LockRequest {
156 final MonoSink<Lock> callback;
157 final LockType lockType;
160 LockRequest(MonoSink<Lock> callback, LockType lockType, Lock lock) {
161 this.callback = callback;
162 this.lockType = lockType;
167 private synchronized void addToQueue(MonoSink<Lock> callback, LockType lockType) {
168 lockRequestQueue.add(new LockRequest(callback, lockType, this));
171 @SuppressWarnings("java:S2274") // Always invoke wait() and await() methods inside a loop
172 private synchronized void waitForUnlock() {
175 } catch (InterruptedException e) {
176 logger.warn("waitForUnlock interrupted", e);
177 Thread.currentThread().interrupt();
181 private boolean tryLock(LockType lockType) {
182 if (this.isExclusive) {
185 if (lockType == LockType.EXCLUSIVE && lockCounter > 0) {
189 this.isExclusive = lockType == LockType.EXCLUSIVE;