1 4 package com.tc.util.concurrent; 5 6 16 public final class SetOnceRef { 17 private Object ref; 18 private boolean set; 19 private final Object lock = new Object (); 20 private final boolean allowsNullValue; 21 22 26 public SetOnceRef() { 27 this(null, false, false); 28 } 29 30 37 public SetOnceRef(Object ref) { 38 this(ref, false, true); 39 } 40 41 48 public SetOnceRef(Object ref, boolean allowNull) { 49 this(ref, allowNull, true); 50 } 51 52 57 public SetOnceRef(boolean allowNull) { 58 this(null, allowNull, false); 59 } 60 61 private SetOnceRef(final Object ref, final boolean allowNull, final boolean init) { 62 this.allowsNullValue = allowNull; 63 64 if (init) { 65 set(ref); 66 } 67 } 68 69 74 public boolean allowsNull() { 75 return this.allowsNullValue; 76 } 77 78 85 public void set(final Object ref) { 86 synchronized (lock) { 87 if (set) { throw new IllegalStateException ("Reference has already been set"); } 88 89 if ((!allowsNull()) && (ref == null)) { throw new IllegalArgumentException ( 90 "This instance cannot hold a null reference value"); } 91 92 set = true; 93 this.ref = ref; 94 } 95 } 96 97 103 public Object get() { 104 synchronized (lock) { 105 if (!set) { throw new IllegalStateException ("Reference has not been set"); } 106 107 return ref; 108 } 109 } 110 111 116 public boolean isSet() { 117 synchronized (lock) { 118 return set; 119 } 120 } 121 } | Popular Tags |