Merge "Make model/pom.xml inherit from odlparent-lite"
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / common / DeviceConnectionRateLimiter.java
1 /*
2  * Copyright (c) 2018 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.openflowplugin.impl.common;
9
10 import com.google.common.util.concurrent.RateLimiter;
11 import java.util.concurrent.TimeUnit;
12 import java.util.concurrent.atomic.AtomicReference;
13 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.provider.config.rev160510.OpenflowProviderConfig;
14
15 public class DeviceConnectionRateLimiter {
16     private final boolean doRateLimit;
17     private final AtomicReference<RateLimiter> rateLimiter;
18
19     public DeviceConnectionRateLimiter(final OpenflowProviderConfig config) {
20         int deviceConnectionRateLimitPerMin = config.getDeviceConnectionRateLimitPerMin().toJava();
21         double rateLimiterSize;
22         if (deviceConnectionRateLimitPerMin == 0) {
23             doRateLimit = false;
24             rateLimiterSize = 1;
25         } else {
26             doRateLimit = true;
27             rateLimiterSize = 1d / (60d / deviceConnectionRateLimitPerMin);
28         }
29         rateLimiter = new AtomicReference<>(RateLimiter.create(rateLimiterSize));
30
31     }
32
33     public boolean tryAquire() {
34         if (doRateLimit) {
35             return rateLimiter.get().tryAcquire(0, TimeUnit.SECONDS);
36         }
37         return true;
38     }
39 }