1 17 package org.apache.servicemix.beanflow; 18 19 import org.apache.servicemix.beanflow.support.Notifier; 20 import org.apache.servicemix.beanflow.support.SynchronousNotifier; 21 22 28 public class DefaultState<T> implements State<T> { 29 30 private T value; 31 private Object lock = new Object (); 32 private Notifier notifier; 33 34 public DefaultState() { 35 notifier = new SynchronousNotifier(); 36 } 37 38 public DefaultState(T value) { 39 this(); 40 this.value = value; 41 } 42 43 public DefaultState(Notifier notifier) { 44 this.notifier = notifier; 45 } 46 47 public DefaultState(T value, Notifier notifier) { 48 this.value = value; 49 this.notifier = notifier; 50 } 51 52 public T get() { 53 synchronized (lock) { 54 return value; 55 } 56 } 57 58 public T getAndSet(T value) { 59 T answer = null; 60 synchronized (lock) { 61 answer = this.value; 62 this.value = value; 63 } 64 65 notifier.run(); 66 return answer; 67 } 68 69 public void set(T value) { 70 synchronized (lock) { 71 this.value = value; 72 } 73 74 notifier.run(); 75 } 76 77 public boolean compareAndSet(T expected, T newValue) { 78 synchronized (lock) { 79 if (equals(value, expected)) { 80 this.value = newValue; 81 return true; 82 } 83 } 84 return false; 85 } 86 87 public void addRunnable(Runnable listener) { 88 notifier.addRunnable(listener); 89 } 90 91 public void removeRunnable(Runnable listener) { 92 notifier.removeRunnable(listener); 93 } 94 95 public String toString() { 96 T currentValue = get(); 97 if (currentValue == null) { 98 return "null"; 99 } 100 else { 101 return currentValue.toString(); 102 } 103 } 104 105 108 public boolean is(T that) { 109 T currentValue = get(); 110 return equals(that, currentValue); 111 } 112 113 public boolean isAny(T... values) { 114 T currentValue = get(); 115 for (T value : values) { 116 if (equals(currentValue, value)) { 117 return true; 118 } 119 } 120 return false; 121 } 122 123 127 public static boolean equals(Object value1, Object value2) { 128 if (value1 == value2) { 129 return true; 130 } 131 if (value1 == null || value2 == null) { 132 return false; 133 } 134 return value1.equals(value2); 135 } 136 } 137 | Popular Tags |