2 * Copyright (c) 2016 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
9 package org.opendaylight.openflowplugin.applications.frsync.util;
11 import java.util.concurrent.Semaphore;
13 import javax.annotation.Nonnull;
15 import org.opendaylight.openflowplugin.applications.frsync.SemaphoreKeeper;
17 import com.google.common.cache.CacheBuilder;
18 import com.google.common.cache.CacheLoader;
19 import com.google.common.cache.LoadingCache;
22 * Key-based semaphore provider.
24 public class SemaphoreKeeperGuavaImpl<K> implements SemaphoreKeeper<K> {
26 private LoadingCache<K, Semaphore> semaphoreCache;
28 public SemaphoreKeeperGuavaImpl(final int permits, final boolean fair) {
29 semaphoreCache = CacheBuilder.newBuilder()
32 .build(new CacheLoader<K, Semaphore>() {
34 public Semaphore load(final K key) throws Exception {
35 return new Semaphore(permits, fair) {
36 private static final long serialVersionUID = 1L;
43 public Semaphore summonGuard(final @Nonnull K key) {
44 return semaphoreCache.getUnchecked(key);
48 public String toString() {
49 return super.toString() + " size:" + (semaphoreCache == null ? null : semaphoreCache.size()) + " " + semaphoreCache;