com.beans.observables.properties.atomic.AtomicObservableProperty Maven / Gradle / Ivy
package com.beans.observables.properties.atomic;
import com.beans.observables.binding.AtomicPropertyBindingController;
import com.beans.observables.binding.PropertyBindingController;
import com.beans.observables.listeners.ObservableEventController;
import com.beans.observables.properties.ObservablePropertyBase;
import com.notifier.EventController;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
/**
*
* A thread-safe implementation of {@link com.beans.observables.properties.ObservableProperty}, holding a
* variable which is accessed for writing or reading through {@link #set(Object)}
* and {@link #get()}.
*
*
* This implementation uses the java.util.concurrent.atomic package, to provide
* a lock-free, atomic read and write operations.
*
*
* Depending on the {@link ObservableEventController} used, it is possible
* that changes from multiple threads won't dispatch in the correct order.
*
*
* @param type of the property data.
*
* @since JavaBeans 1.0
*/
public class AtomicObservableProperty extends ObservablePropertyBase {
private final AtomicReference mValue;
public AtomicObservableProperty(ObservableEventController eventController,
PropertyBindingController bindingController,
T initialValue) {
super(eventController, bindingController);
mValue = new AtomicReference<>(initialValue);
}
public AtomicObservableProperty(EventController eventController,
PropertyBindingController bindingController,
T initialValue) {
super(eventController, bindingController);
mValue = new AtomicReference<>(initialValue);
}
public AtomicObservableProperty(ObservableEventController eventController,
PropertyBindingController bindingController) {
this(eventController, bindingController, null);
}
public AtomicObservableProperty(EventController eventController, T initialValue) {
this(eventController, new AtomicPropertyBindingController<>(), initialValue);
}
public AtomicObservableProperty(EventController eventController) {
this(eventController, null);
}
@Override
protected void setInternalDirect(T value) {
mValue.set(value);
}
@Override
public void set(T value) {
if (!setIfBound(value)) {
T oldValue = mValue.getAndSet(value);
if (!Objects.equals(oldValue, value)) {
fireValueChangedEvent(oldValue, value);
}
}
}
@Override
public T get() {
Optional boundOptional = getIfBound();
return boundOptional.orElseGet(mValue::get);
}
}