blob: 007ac119055563cfb945e272a7056394d8cb2246 [file] [log] [blame]
Carmelo Casconeda15af82019-12-09 22:36:48 -08001/*
2 * Copyright 2019-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.%
15 */
16
17package org.onosproject.pipelines.fabric.impl.behaviour.bng;
18
19import com.google.common.collect.BiMap;
20import com.google.common.collect.HashBiMap;
21import com.google.common.collect.Lists;
22
23import java.util.NoSuchElementException;
24import java.util.Queue;
25
26import static org.onosproject.net.behaviour.BngProgrammable.Attachment;
27
28/**
29 * Trivial, thread-safe, non-distributed implementation of {@link
30 * FabricBngLineIdAllocator}.
31 */
32final class SimpleBngLineIdAllocator implements FabricBngLineIdAllocator {
33
34 private final long size;
35 private final BiMap<Handle, Long> allocated = HashBiMap.create();
36 private final Queue<Long> released = Lists.newLinkedList();
37
38 /**
39 * Creates a new allocator that can allocate and hold up to the given number
40 * of IDs.
41 *
42 * @param size maximum number of IDs to allocate.
43 */
44 SimpleBngLineIdAllocator(long size) {
45 this.size = size;
46 for (long i = 0; i < size; i++) {
47 released.add(i);
48 }
49 }
50
51 @Override
52 public long allocate(Attachment attachment) throws IdExhaustedException {
53 final Handle handle = new Handle(attachment);
54 synchronized (this) {
55 if (allocated.containsKey(handle)) {
56 return allocated.get(handle);
57 }
58 try {
59 final long id = released.remove();
60 allocated.put(handle, id);
61 return id;
62 } catch (NoSuchElementException e) {
63 // All IDs are taken;
64 throw new IdExhaustedException();
65 }
66 }
67 }
68
69 @Override
70 public void release(Attachment attachment) {
71 final Handle handle = new Handle(attachment);
72 synchronized (this) {
73 Long id = allocated.remove(handle);
74 if (id != null) {
75 released.add(id);
76 }
77 }
78 }
79
80 @Override
81 public void release(long id) {
82 synchronized (this) {
83 if (allocated.inverse().containsKey(id)) {
84 allocated.inverse().remove(id);
85 released.add(id);
86 }
87 }
88 }
89
90 @Override
91 public long size() {
92 return size;
93 }
94
95 @Override
96 public long freeCount() {
97 return released.size();
98 }
99
100 @Override
101 public long allocatedCount() {
102 return allocated.size();
103 }
104}