2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.datastore;
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import java.util.concurrent.Semaphore;
13 import java.util.concurrent.TimeUnit;
14 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
19 * Class for limiting operations.
21 public class OperationLimiter {
22 private static final Logger LOG = LoggerFactory.getLogger(OperationLimiter.class);
23 private final TransactionIdentifier identifier;
24 private final long acquireTimeout;
25 private final Semaphore semaphore;
26 private final int maxPermits;
28 OperationLimiter(final TransactionIdentifier identifier, final int maxPermits, final long acquireTimeoutSeconds) {
29 this.identifier = Preconditions.checkNotNull(identifier);
31 Preconditions.checkArgument(acquireTimeoutSeconds >= 0);
32 this.acquireTimeout = TimeUnit.SECONDS.toNanos(acquireTimeoutSeconds);
34 Preconditions.checkArgument(maxPermits >= 0);
35 this.maxPermits = maxPermits;
36 this.semaphore = new Semaphore(maxPermits);
43 boolean acquire(final int acquirePermits) {
45 if (semaphore.tryAcquire(acquirePermits, acquireTimeout, TimeUnit.NANOSECONDS)) {
48 } catch (InterruptedException e) {
49 if (LOG.isDebugEnabled()) {
50 LOG.debug("Interrupted when trying to acquire operation permit for transaction {}", identifier, e);
52 LOG.warn("Interrupted when trying to acquire operation permit for transaction {}", identifier);
63 void release(int permits) {
64 this.semaphore.release(permits);
68 TransactionIdentifier getIdentifier() {
73 int availablePermits() {
74 return semaphore.availablePermits();
78 * Release all the permits.
80 public void releaseAll() {
81 this.semaphore.release(maxPermits - availablePermits());