Brian O'Connor | 520c052 | 2014-11-23 23:50:47 -0800 | [diff] [blame^] | 1 | package org.onlab.onos.core.impl; |
| 2 | |
| 3 | import org.onlab.onos.core.IdBlock; |
| 4 | import org.onlab.onos.core.IdGenerator; |
| 5 | import org.onlab.onos.core.UnavailableIdException; |
| 6 | |
| 7 | /** |
| 8 | * Base class of {@link IdGenerator} implementations which use {@link IdBlockAllocator} as |
| 9 | * backend. |
| 10 | */ |
| 11 | public class BlockAllocatorBasedIdGenerator implements IdGenerator { |
| 12 | protected final IdBlockAllocator allocator; |
| 13 | protected IdBlock idBlock; |
| 14 | |
| 15 | /** |
| 16 | * Constructs an ID generator which use {@link IdBlockAllocator} as backend. |
| 17 | * |
| 18 | * @param allocator |
| 19 | */ |
| 20 | protected BlockAllocatorBasedIdGenerator(IdBlockAllocator allocator) { |
| 21 | this.allocator = allocator; |
| 22 | this.idBlock = allocator.allocateUniqueIdBlock(); |
| 23 | } |
| 24 | |
| 25 | @Override |
| 26 | public long getNewId() { |
| 27 | try { |
| 28 | return idBlock.getNextId(); |
| 29 | } catch (UnavailableIdException e) { |
| 30 | synchronized (allocator) { |
| 31 | idBlock = allocator.allocateUniqueIdBlock(); |
| 32 | return idBlock.getNextId(); |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | } |