Brian O'Connor | 66630c8 | 2014-10-02 21:08:19 -0700 | [diff] [blame] | 1 | package org.onlab.onos.net.intent.impl; |
| 2 | |
| 3 | import org.onlab.onos.net.intent.IdGenerator; |
| 4 | |
| 5 | /** |
| 6 | * Base class of {@link IdGenerator} implementations which use {@link IdBlockAllocator} as |
| 7 | * backend. |
| 8 | * |
| 9 | * @param <T> the type of ID |
| 10 | */ |
| 11 | public abstract class AbstractBlockAllocatorBasedIdGenerator<T> implements IdGenerator<T> { |
| 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 AbstractBlockAllocatorBasedIdGenerator(IdBlockAllocator allocator) { |
| 21 | this.allocator = allocator; |
| 22 | this.idBlock = allocator.allocateUniqueIdBlock(); |
| 23 | } |
| 24 | |
| 25 | @Override |
| 26 | public synchronized T getNewId() { |
| 27 | try { |
| 28 | return convertFrom(idBlock.getNextId()); |
| 29 | } catch (UnavailableIdException e) { |
| 30 | idBlock = allocator.allocateUniqueIdBlock(); |
| 31 | return convertFrom(idBlock.getNextId()); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * Returns an ID instance of {@code T} type from the long value. |
| 37 | * |
| 38 | * @param value original long value |
| 39 | * @return ID instance |
| 40 | */ |
| 41 | protected abstract T convertFrom(long value); |
| 42 | } |