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)) {
49 LOG.warn("Failed to acquire operation permit for transaction {}", identifier);
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(int permits) {
66 this.semaphore.release(permits);
69 public TransactionIdentifier getIdentifier() {
74 int availablePermits() {
75 return semaphore.availablePermits();
79 * Release all the permits.
81 public void releaseAll() {
82 this.semaphore.release(maxPermits - availablePermits());