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 static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.VisibleForTesting;
14 import java.util.concurrent.Semaphore;
15 import java.util.concurrent.TimeUnit;
16 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
21 * Class for limiting operations.
23 public class OperationLimiter {
24 private static final Logger LOG = LoggerFactory.getLogger(OperationLimiter.class);
25 private final TransactionIdentifier identifier;
26 private final long acquireTimeout;
27 private final Semaphore semaphore;
28 private final int maxPermits;
30 OperationLimiter(final TransactionIdentifier identifier, final int maxPermits, final long acquireTimeoutSeconds) {
31 this.identifier = requireNonNull(identifier);
33 checkArgument(acquireTimeoutSeconds >= 0);
34 this.acquireTimeout = TimeUnit.SECONDS.toNanos(acquireTimeoutSeconds);
36 checkArgument(maxPermits >= 0);
37 this.maxPermits = maxPermits;
38 this.semaphore = new Semaphore(maxPermits);
45 boolean acquire(final int acquirePermits) {
47 if (semaphore.tryAcquire(acquirePermits, acquireTimeout, TimeUnit.NANOSECONDS)) {
50 } catch (InterruptedException e) {
51 if (LOG.isDebugEnabled()) {
52 LOG.debug("Interrupted when trying to acquire operation permit for transaction {}", identifier, e);
54 LOG.warn("Interrupted when trying to acquire operation permit for transaction {}", identifier);
65 void release(final int permits) {
66 this.semaphore.release(permits);
70 TransactionIdentifier getIdentifier() {
75 int availablePermits() {
76 return semaphore.availablePermits();
80 * Release all the permits.
82 public void releaseAll() {
83 this.semaphore.release(maxPermits - availablePermits());