2 * Copyright (c) 2015 Pantheon Technologies s.r.o. 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.openflowjava.protocol.impl.core.connection;
10 import com.google.common.base.FinalizableReferenceQueue;
11 import com.google.common.base.FinalizableSoftReference;
12 import com.google.common.base.Preconditions;
13 import java.lang.ref.Reference;
14 import java.util.Collection;
15 import java.util.concurrent.ConcurrentLinkedDeque;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
19 final class OutboundQueueCacheSlice {
20 private static final class QueueRef extends FinalizableSoftReference<OutboundQueueImpl> {
21 private final Collection<?> cache;
23 protected QueueRef(final FinalizableReferenceQueue queue, final Collection<?> cache, final OutboundQueueImpl referent) {
24 super(referent, queue);
25 this.cache = Preconditions.checkNotNull(cache);
29 public void finalizeReferent() {
34 private static final Logger LOG = LoggerFactory.getLogger(OutboundQueueCacheSlice.class);
35 private final FinalizableReferenceQueue refQueue = new FinalizableReferenceQueue();
37 private final ConcurrentLinkedDeque<QueueRef> cache = new ConcurrentLinkedDeque<>();
38 private final int queueSize;
39 private int refCount = 1;
41 OutboundQueueCacheSlice(final int queueSize) {
42 Preconditions.checkArgument(queueSize >= 1);
43 this.queueSize = queueSize;
46 void remove(final QueueRef queueRef) {
47 cache.remove(queueRef);
51 if (--refCount == 0) {
67 OutboundQueueImpl getQueue(final OutboundQueueManager<?> manager, final long baseXid) {
68 final OutboundQueueImpl ret;
69 OutboundQueueImpl cached = null;
71 final Reference<OutboundQueueImpl> item = cache.pollLast();
78 ret = cached.reuse(manager, baseXid);
79 LOG.trace("Reusing queue {} as {} on manager {}", cached, ret, manager);
84 ret = new OutboundQueueImpl(manager, baseXid, queueSize + 1);
85 LOG.trace("Allocated new queue {} on manager {}", ret, manager);
89 void putQueue(final OutboundQueueImpl queue) {
91 if (cache.offer(new QueueRef(refQueue, cache, queue))) {
92 LOG.trace("Saving queue {} for later reuse", queue);
94 LOG.trace("Queue {} thrown away", queue);