blob: ca483b4bf68796c172e6c0036fc1401e7139e8b2 [file] [log] [blame]
alshabibab984662014-12-04 18:56:18 -08001/*
2 * Copyright 2014 Open Networking Laboratory
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 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.core.impl;
Brian O'Connor520c0522014-11-23 23:50:47 -080017
Madan Jampani66feabf2015-06-05 12:24:20 -070018import java.util.concurrent.atomic.AtomicBoolean;
19
Brian O'Connorabafb502014-12-02 22:26:20 -080020import org.onosproject.core.IdBlock;
21import org.onosproject.core.IdGenerator;
22import org.onosproject.core.UnavailableIdException;
Brian O'Connor520c0522014-11-23 23:50:47 -080023
24/**
25 * Base class of {@link IdGenerator} implementations which use {@link IdBlockAllocator} as
26 * backend.
27 */
28public class BlockAllocatorBasedIdGenerator implements IdGenerator {
29 protected final IdBlockAllocator allocator;
Madan Jampanic80da082015-06-03 00:26:21 -070030 protected IdBlock idBlock;
Madan Jampani66feabf2015-06-05 12:24:20 -070031 protected AtomicBoolean initialized;
32
Brian O'Connor520c0522014-11-23 23:50:47 -080033
34 /**
35 * Constructs an ID generator which use {@link IdBlockAllocator} as backend.
36 *
Pavlin Radoslavov119fd5c2014-11-25 19:08:19 -080037 * @param allocator the ID block allocator to use
Brian O'Connor520c0522014-11-23 23:50:47 -080038 */
39 protected BlockAllocatorBasedIdGenerator(IdBlockAllocator allocator) {
40 this.allocator = allocator;
Madan Jampani66feabf2015-06-05 12:24:20 -070041 this.initialized = new AtomicBoolean(false);
Brian O'Connor520c0522014-11-23 23:50:47 -080042 }
43
44 @Override
45 public long getNewId() {
46 try {
Madan Jampani66feabf2015-06-05 12:24:20 -070047 if (!initialized.get()) {
48 synchronized (allocator) {
49 if (!initialized.get()) {
50 idBlock = allocator.allocateUniqueIdBlock();
51 initialized.set(true);
52 }
53 }
54 }
Madan Jampanic80da082015-06-03 00:26:21 -070055 return idBlock.getNextId();
Brian O'Connor520c0522014-11-23 23:50:47 -080056 } catch (UnavailableIdException e) {
57 synchronized (allocator) {
Madan Jampanic80da082015-06-03 00:26:21 -070058 idBlock = allocator.allocateUniqueIdBlock();
Brian O'Connor520c0522014-11-23 23:50:47 -080059 }
Madan Jampani66feabf2015-06-05 12:24:20 -070060 return idBlock.getNextId();
Brian O'Connor520c0522014-11-23 23:50:47 -080061 }
62 }
63}