Brian O'Connor
Committed by Gerrit Code Review

Refactoring BlockAllocatorBasedIdGenerator.java

Allowing first call to getNewId() to throw an NPE, and handling initial setup in catch block

Change-Id: I409aa9c8a309dbbf4fc3738c3870ec4d91831303
...@@ -21,6 +21,8 @@ import org.onosproject.core.IdBlock; ...@@ -21,6 +21,8 @@ import org.onosproject.core.IdBlock;
21 import org.onosproject.core.IdGenerator; 21 import org.onosproject.core.IdGenerator;
22 import org.onosproject.core.UnavailableIdException; 22 import org.onosproject.core.UnavailableIdException;
23 23
24 +import static com.google.common.base.Preconditions.checkNotNull;
25 +
24 /** 26 /**
25 * Base class of {@link IdGenerator} implementations which use {@link IdBlockAllocator} as 27 * Base class of {@link IdGenerator} implementations which use {@link IdBlockAllocator} as
26 * backend. 28 * backend.
...@@ -37,27 +39,29 @@ public class BlockAllocatorBasedIdGenerator implements IdGenerator { ...@@ -37,27 +39,29 @@ public class BlockAllocatorBasedIdGenerator implements IdGenerator {
37 * @param allocator the ID block allocator to use 39 * @param allocator the ID block allocator to use
38 */ 40 */
39 protected BlockAllocatorBasedIdGenerator(IdBlockAllocator allocator) { 41 protected BlockAllocatorBasedIdGenerator(IdBlockAllocator allocator) {
40 - this.allocator = allocator; 42 + this.allocator = checkNotNull(allocator, "allocator cannot be null");
41 this.initialized = new AtomicBoolean(false); 43 this.initialized = new AtomicBoolean(false);
42 } 44 }
43 45
44 @Override 46 @Override
45 public long getNewId() { 47 public long getNewId() {
46 try { 48 try {
47 - if (!initialized.get()) {
48 - synchronized (allocator) {
49 - if (!initialized.get()) {
50 - idBlock = allocator.allocateUniqueIdBlock();
51 - initialized.set(true);
52 - }
53 - }
54 - }
55 return idBlock.getNextId(); 49 return idBlock.getNextId();
56 } catch (UnavailableIdException e) { 50 } catch (UnavailableIdException e) {
57 synchronized (allocator) { 51 synchronized (allocator) {
58 idBlock = allocator.allocateUniqueIdBlock(); 52 idBlock = allocator.allocateUniqueIdBlock();
59 } 53 }
60 return idBlock.getNextId(); 54 return idBlock.getNextId();
55 + } catch (NullPointerException e) {
56 + synchronized (allocator) {
57 + if (!initialized.get()) {
58 + idBlock = allocator.allocateUniqueIdBlock();
59 + initialized.set(true);
60 + return idBlock.getNextId();
61 + } else {
62 + throw e;
63 + }
64 + }
61 } 65 }
62 } 66 }
63 } 67 }
......