Open Kilda Java Documentation
ResourcePool.java
Go to the documentation of this file.
1 /* Copyright 2017 Telstra Open Source
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 package org.openkilda.messaging.payload;
17 
18 import com.google.common.base.MoreObjects;
19 import com.google.common.collect.ImmutableSet;
20 
21 import java.util.Set;
22 import java.util.concurrent.ConcurrentHashMap;
23 
32 public class ResourcePool {
36  private final Set<Integer> resources = ConcurrentHashMap.newKeySet();
37  private Integer nextId;
38  private Integer lower;
39  private Integer upper;
40 
47  public ResourcePool(final Integer minValue, final Integer maxValue) {
48  this.nextId = minValue;
49  this.lower = minValue;
50  this.upper = maxValue;
51  }
52 
58  public Integer allocate() {
59  int range = upper - lower;
60  if (resources.size() <= range) {
61  // We are just going to loop through everything until we find a free one. Generally
62  // speaking this could be inefficient .. but we use "nextId" as a start, and that should
63  // have the greatest chance of being available.
64  for (int i = 0; i < range; i++) {
65  if (nextId > upper)
66  nextId = lower;
67  int next;
68 
69  // ensure only one thread executes the post-incremen
70  synchronized (nextId) {
71  next = nextId++;
72  }
73 
74  if (resources.add(next)) {
75  return next;
76  }
77  }
78  }
79  throw new ArrayIndexOutOfBoundsException("Could not allocate resource: pool is full");
80  }
81 
88  public Integer allocate(Integer id) {
89  // This is added to ensure that if we are adding one or many IDs, we set nextId to the
90  // largest of the set. This only affects the next call to allocate() without id, and all
91  // it'll do is cause the search to start at this point.
92  if (id > nextId)
93  nextId = id+1;
94  return resources.add(id) ? id : null;
95  }
96 
103  public Integer deallocate(final Integer resourceId) {
104  return resources.remove(resourceId) ? resourceId : null;
105  }
106 
112  public Set<Integer> dumpPool() {
113  return ImmutableSet.copyOf(resources);
114  }
115 
119  @Override
120  public String toString() {
121  return MoreObjects.toStringHelper(this)
122  .add("resources", resources)
123  .add("nextId", nextId)
124  .add("lower", lower)
125  .add("upper", upper)
126  .toString();
127  }
128 }
Integer deallocate(final Integer resourceId)
id
Definition: nodes.py:55
ResourcePool(final Integer minValue, final Integer maxValue)