Merge "BUG-5636: making table features configurable for the He plugin. DEFAULT will...
[openflowplugin.git] / applications / forwardingrules-sync / src / main / java / org / opendaylight / openflowplugin / applications / frsync / util / SemaphoreKeeperGuavaImpl.java
1 /**
2  * Copyright (c) 2016 Cisco Systems, Inc. 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
9 package org.opendaylight.openflowplugin.applications.frsync.util;
10
11 import java.util.concurrent.Semaphore;
12
13 import javax.annotation.Nonnull;
14
15 import org.opendaylight.openflowplugin.applications.frsync.SemaphoreKeeper;
16
17 import com.google.common.cache.CacheBuilder;
18 import com.google.common.cache.CacheLoader;
19 import com.google.common.cache.LoadingCache;
20
21 /**
22  * Key-based semaphore provider.
23  */
24 public class SemaphoreKeeperGuavaImpl<K> implements SemaphoreKeeper<K> {
25
26     private LoadingCache<K, Semaphore> semaphoreCache;
27
28     public SemaphoreKeeperGuavaImpl(final int permits, final boolean fair) {
29         semaphoreCache = CacheBuilder.newBuilder()
30                 .concurrencyLevel(1)
31                 .weakValues()
32                 .build(new CacheLoader<K, Semaphore>() {
33                     @Override
34                     public Semaphore load(final K key) throws Exception {
35                         return new Semaphore(permits, fair) {
36                             private static final long serialVersionUID = 1L;
37                         };
38                     }
39                 });
40     }
41
42     @Override
43     public Semaphore summonGuard(final @Nonnull K key) {
44         return semaphoreCache.getUnchecked(key);
45     }
46     
47     @Override
48     public String toString() {
49         return super.toString() + " size:" + (semaphoreCache == null ? null : semaphoreCache.size()) + " " + semaphoreCache;
50     }
51 }