Merge "BUG:5888 - Changing FRM from clustered DCN to clustered DTCN"
[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 com.google.common.cache.CacheBuilder;
12 import com.google.common.cache.CacheLoader;
13 import com.google.common.cache.LoadingCache;
14 import java.util.concurrent.Semaphore;
15 import javax.annotation.Nonnull;
16 import org.opendaylight.openflowplugin.applications.frsync.SemaphoreKeeper;
17
18 /**
19  * Key-based semaphore provider.
20  */
21 public class SemaphoreKeeperGuavaImpl<K> implements SemaphoreKeeper<K> {
22
23     private LoadingCache<K, Semaphore> semaphoreCache;
24
25     public SemaphoreKeeperGuavaImpl(final int permits, final boolean fair) {
26         semaphoreCache = CacheBuilder.newBuilder()
27                 .concurrencyLevel(1)
28                 .weakValues()
29                 .build(new CacheLoader<K, Semaphore>() {
30                     @Override
31                     public Semaphore load(final K key) throws Exception {
32                         return new Semaphore(permits, fair) {
33                             private static final long serialVersionUID = 1L;
34                         };
35                     }
36                 });
37     }
38
39     @Override
40     public Semaphore summonGuard(final @Nonnull K key) {
41         return semaphoreCache.getUnchecked(key);
42     }
43     
44     @Override
45     public String toString() {
46         return super.toString() + " size:" + (semaphoreCache == null ? null : semaphoreCache.size()) + " " + semaphoreCache;
47     }
48 }