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.datastore.identifiers.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;
30 OperationLimiter(final TransactionIdentifier identifier, final int maxPermits, final int acquireTimeoutSeconds) {
31 this.identifier = Preconditions.checkNotNull(identifier);
33 Preconditions.checkArgument(acquireTimeoutSeconds >= 0);
34 this.acquireTimeout = TimeUnit.SECONDS.toNanos(acquireTimeoutSeconds);
36 Preconditions.checkArgument(maxPermits >= 0);
37 this.semaphore = new Semaphore(maxPermits);
44 private void acquire(final int acquirePermits) {
46 if (!semaphore.tryAcquire(acquirePermits, acquireTimeout, TimeUnit.NANOSECONDS)) {
47 LOG.warn("Failed to acquire operation permit for transaction {}", identifier);
49 } catch (InterruptedException e) {
50 if (LOG.isDebugEnabled()) {
51 LOG.debug("Interrupted when trying to acquire operation permit for transaction {}", identifier, e);
53 LOG.warn("Interrupted when trying to acquire operation permit for transaction {}", identifier);
59 this.semaphore.release();
63 public void onComplete(final Throwable throwable, final Object message) {
64 if (message instanceof BatchedModificationsReply) {
65 this.semaphore.release(((BatchedModificationsReply)message).getNumBatched());
67 this.semaphore.release();
71 public TransactionIdentifier getIdentifier() {
76 Semaphore getSemaphore() {