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 akka.dispatch.OnComplete;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Preconditions;
13 import java.util.concurrent.Semaphore;
14 import java.util.concurrent.TimeUnit;
15 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
16 import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
21 * Class for limiting operations. It extends {@link OnComplete}, so we can plug it seamlessly
22 * into akka to release permits as futures complete.
24 public class OperationLimiter extends OnComplete<Object> {
25 private static final Logger LOG = LoggerFactory.getLogger(OperationLimiter.class);
26 private final TransactionIdentifier identifier;
27 private final long acquireTimeout;
28 private final Semaphore semaphore;
29 private final int maxPermits;
31 OperationLimiter(final TransactionIdentifier identifier, final int maxPermits, final long acquireTimeoutSeconds) {
32 this.identifier = Preconditions.checkNotNull(identifier);
34 Preconditions.checkArgument(acquireTimeoutSeconds >= 0);
35 this.acquireTimeout = TimeUnit.SECONDS.toNanos(acquireTimeoutSeconds);
37 Preconditions.checkArgument(maxPermits >= 0);
38 this.maxPermits = maxPermits;
39 this.semaphore = new Semaphore(maxPermits);
46 void acquire(final int acquirePermits) {
48 if (!semaphore.tryAcquire(acquirePermits, acquireTimeout, TimeUnit.NANOSECONDS)) {
49 LOG.warn("Failed to acquire operation permit for transaction {}", identifier);
51 } catch (InterruptedException e) {
52 if (LOG.isDebugEnabled()) {
53 LOG.debug("Interrupted when trying to acquire operation permit for transaction {}", identifier, e);
55 LOG.warn("Interrupted when trying to acquire operation permit for transaction {}", identifier);
61 public void onComplete(final Throwable throwable, final Object message) {
62 if (message instanceof BatchedModificationsReply) {
63 this.semaphore.release(((BatchedModificationsReply)message).getNumBatched());
65 this.semaphore.release();
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());