JavaBeanProperty: jdk7 vs jdk 8 - WeakOnTheFeet vs StrongInTheArm - java

A long standing issue (some call it - arguably - feature :) is the weakness of all listeners installed by all fx-bindings. As a consequence, we can't build "chains" of properties without keeping a strong reference to each link of the chain.
A particular type of such a chain link is a JavaBeanProperty: its purpose is to adapt a javabean property to a fx-property. Typically, nobody is interested in the adapter as such, so its usage would do something like
private Parent createContentBean() {
...
// local ref only
Property property = createJavaBeanProperty();
Bindings.bindBidirectional(label.textProperty(), property, NumberFormat.getInstance());
.. wondering why the label isn't updated. Changing property to a strong reference will work as expected (leaving me puzzeld as to who is responsible to feed the dummy, but that's another question):
Property property;
private Parent createContentBean() {
...
// instantiate the field
property = createJavaBeanProperty();
Bindings.bindBidirectional(label.textProperty(), property, NumberFormat.getInstance());
Long intro, but nearly there: jdk8 somehow changed the implementation so that the first approach is now working, there's no longer any need to keep a strong reference to a JavaBeanProperty. On the other hand, custom implementations of "chain links" still need a strong reference.
Questions:
is the change of behaviour intentional and if so, why?
how is it achieved? The code looks very similar ... and I would love to try something similar in custom adapters
A complete example to play with:
public class BeanAdapterExample extends Application {
private Counter counter;
public BeanAdapterExample() {
this.counter = new Counter();
}
Property property;
private Parent createContentBean() {
VBox content = new VBox();
Label label = new Label();
// strong ref
property = createJavaBeanProperty();
// local property
Property property = createJavaBeanProperty();
Bindings.bindBidirectional(label.textProperty(), property, NumberFormat.getInstance());
Slider slider = new Slider();
slider.valueProperty().bindBidirectional(property);
Button button = new Button("increase");
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent paramT) {
counter.increase();
}
});
content.getChildren().add(label);
content.getChildren().add(slider);
content.getChildren().add(button);
return content;
}
protected JavaBeanDoubleProperty createJavaBeanProperty(){
try {
return JavaBeanDoublePropertyBuilder.create()
.bean(counter).name("count").build();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
#Override
public void start(Stage stage) throws Exception {
Scene scene = new Scene(createContentBean());
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
public static class Counter {
private double count;
public Counter() {
this(0);
}
public Counter(double count) {
this.count = count;
}
/**
* Increases the counter by 1.
*/
public void increase() {
setCount(getCount()+ 1.);
}
/**
* #return the count
*/
public double getCount() {
return count;
}
/**
* #param count the count to set
*/
public void setCount(double count) {
double old = getCount();
this.count = count;
firePropertyChange("count", old, getCount());
}
PropertyChangeSupport support = new PropertyChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener l) {
support.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
support.removePropertyChangeListener(l);
}
protected void firePropertyChange(String name, Object oldValue,
Object newValue) {
support.firePropertyChange(name, oldValue, newValue);
}
}
}
BTW: added the Swing tag because adapting core beans will be a frequent task in migration

Reminds me on an issue I've stumbled across last year - a binding does not create a strong reference so the property will be garbage collected if the property is a method local field.

Gropingly trying to answer part of my own answer:
tentative guess: it's not intentional. Looks like now the JavaBeanProperty is never garbage collected, which couldn't have been the requirement.
the only difference I could find is a phantomReference (Cleaner in the snippet) to the property, created in its constructor: that seems to keep it strong enough to never (?) be released. If I mimic that in custom properties, they "work" in a chain but are not garbage collected as well. Not an option, IMO.
The jdk8 constructor of the property:
JavaBeanDoubleProperty(PropertyDescriptor descriptor, Object bean) {
this.descriptor = descriptor;
this.listener = descriptor.new Listener<Number>(bean, this);
descriptor.addListener(listener);
Cleaner.create(this, new Runnable() {
#Override
public void run() {
JavaBeanDoubleProperty.this.descriptor.removeListener(listener);
}
});
}
The other way round: if I add such a reference to an arbitrary custom property, then it's stuck in memory just the same way as the javabeanProperty:
protected SimpleDoubleProperty createPhantomedProperty(final boolean phantomed) {
SimpleDoubleProperty adapter = new SimpleDoubleProperty(){
{
// prevents the property from being garbage collected
// must be done here in the constructor
// otherwise reclaimed immediately
if (phantomed) {
Cleaner.create(this, new Runnable() {
#Override
public void run() {
// empty, could do what here?
LOG.info("runnable in cleaner");
}
});
}
}
};
return adapter;
}
To reproduce the non-collection, add the code snippet below to my example code in the question, run in jdk7/8 and monitor with your favourite tool (used VisualVM): while running, click the "create" to create 100k of free-flying JavaBeanProperties. In jdk7, they never even show up in the memory sampler. In jdk8, they are created (sloooowly! so you might reduce the number) and build up. Forced garbage collection has no effect, even after nulling the underlying bean they are bound to.
Button create100K = new Button("create 100k properties");
create100K.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent paramT) {
Property propertyFX;
/// can't measure any effect
for (int i = 0; i < 100000; i++) {
propertyFX = createCountProperty();
}
LOG.info("created 100k adapters");
}
});
Button releaseCounter = new Button("release counter");
releaseCounter.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent paramT) {
counter = null;
}
});
Just FYI: created an issue for the potential memory leak - which is already marked as fixed, that was quick! Unfortunately, the fix-version is 8u20, not sure what to do until then. The only thingy coming to my mind is to c&p all JavaBeanXXProperty/Builders and add the fix. At the price of heavy warnings and unavailability in security-restricted environments. Also, we are back to the jdk7 behaviour (would have been too lucky, eating the cake and still have it :-)

Related

Wrapping an EnumMap in a observable SimpleMapProperty

I need to add a SimpleMapProperty to a JavaFX service class, but I am not sure of the correct syntax of if I am using the correct approach. Note that I am not trying to make the JavaFX service appear like a Java Bean, I just need to know how to listen for updates to an EnumMap from a enum ModuleType (that can be TYPEA or TYPEB) and an associated Boolean flag. Essentially, this can be thought of as a pair of watchdog timers wrapped in a single EnumMap.
I am having trouble understanding how to add the underlying EnumMap entries (there should be 2 - one for each ModuleType described above).
public class UDPListenerService extends Service<Void> {
// 'watchdog' property
private final MapProperty<ModuleType, Boolean> watchdog;
// 'watchdog' SimpleMapProperty bound property getter
public ObservableMap<ModuleType, Boolean> getWatchdog() {
return watchdog.get();
}
// 'watchdog' SimpleMapProperty bound property setter
public void setWatchdog(ObservableMap<ModuleType, Boolean> aValue) {
watchdog.set(aValue);
}
// 'watchdog' SimpleMapProperty bound property
public MapProperty<ModuleType, Boolean> watchdogProperty() {
return watchdog;
}
/**
* Constructor
*/
public UDPListenerService()
{
this.watchdog = new SimpleMapProperty<>(
FXCollections.observableHashMap());
}
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
updateMessage("Running...");
while (!isCancelled()) {
try {
Thread.sleep(1000);
Platform.runLater(() -> {
try {
// update do some processing here
// . . .
// pet the watchdog
// setWatchdog
if (testforModuleType==ModuleType.TYPEA) {
// please help with syntax
setWatchdog(ModuleType.TYPEA, false);
} else {
// please help with syntax
setWatchdog(ModuleType.TYPEB, false);
}
} catch (StatusRuntimeException ex) {
// watchdog timed out - listener will
// update gui components
if (testforModuleType==ModuleType.TYPEA) {
// please help with syntax
setWatchdog(ModuleType.TYPEA, true);
} else {
// please help with syntax
setWatchdog(ModuleType.TYPEB, true);
}
}
});
} catch (InterruptedException ex) {}
}
updateMessage("Cancelled");
return null;
}
};
}
}
The way I use this class is in the JavaFX controller class where I add a listener that populates java gui elements depending on whether the associated Boolean flag is true or false.
Usually a readonly map property is used for this kind of behavior, i.e. a ObservableMap field with only a getter. Only the contents of the map are modified; no new map is assigned to the field after the initial map is assigned.
private final ObservableMap<ModuleType, Boolean> watchdog;
public ObservableMap<ModuleType, Boolean> getWatchdog() {
return watchdog;
}
The map itself is modified the same way a java.util.Map would be modified, e.g. in this case using the put method. Changes can be observed e.g. using a MapChangeListener or Bindings.valueAt.
Furthermore EnumMap can be used as backing Map for a ObservableMap, but to do this the observableMap method needs to be used instead of the observableHashMap method.
The following example randomly selects / deselects values of 2 checkboxes based on values in a ObservableMap.
private CheckBox checkBoxA;
private CheckBox checkBoxB;
private ObservableMap<ModuleType, Boolean> map;
#Override
public void start(Stage primaryStage) {
checkBoxA = new CheckBox("type A");
checkBoxB = new CheckBox("type B");
map = FXCollections.observableMap(new EnumMap<>(ModuleType.class));
initMapListeners();
Thread t = new Thread(() -> {
Random random = new Random();
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
boolean b1 = random.nextBoolean();
boolean b2 = random.nextBoolean();
Platform.runLater(() -> {
map.put(ModuleType.TYPEA, b1);
map.put(ModuleType.TYPEB, b2);
});
}
});
t.setDaemon(true);
t.start();
Scene scene = new Scene(new VBox(10, checkBoxA, checkBoxB));
primaryStage.setScene(scene);
primaryStage.show();
}
Both the following implementations of initMapListeners() would both set the CheckBox.selected states based on the map values.
private void initMapListeners() {
checkBoxA.selectedProperty().bind(Bindings.valueAt(map, ModuleType.TYPEA));
checkBoxB.selectedProperty().bind(Bindings.valueAt(map, ModuleType.TYPEB));
}
private void initMapListeners() {
map.addListener((MapChangeListener.Change<? extends ModuleType, ? extends Boolean> change) -> {
if (change.wasAdded()) {
if (change.getKey() == ModuleType.TYPEA) {
checkBoxA.setSelected(change.getValueAdded());
} else if (change.getKey() == ModuleType.TYPEB) {
checkBoxB.setSelected(change.getValueAdded());
}
}
});
}

Convert synchronized methods to non-blocking algorithm

Just find some information about non-blocking algorithms, so want to use them in practice. I changed some code from synchronized to non-blocking, so I want to ask does I made everything right and saved previous functionality.
synchronized code:
protected PersistentState persistentState;
protected ClassConstructor(final ID id)
{
super(id);
this.persistentState = PersistentState.UNKNOWN;
}
public final synchronized PersistentState getPersistentState()
{
return this.persistentState;
}
protected synchronized void setPersistentState(final PersistentState newPersistentState)
{
if (this.persistentState != newPersistentState)
{
this.persistentState = newPersistentState;
notifyPersistentStateChanged();
}
}
my alternative in non-blocking algorithm:
protected AtomicReference<PersistentState> persistentState;
protected ClassConstructor(final ID id)
{
super(id);
this.persistentState = new AtomicReference<PersistentState>(PersistentState.UNKNOWN);
}
public final PersistentState getPersistentState()
{
return this.persistentState.get();
}
protected void setPersistentState(final PersistentState newPersistentState)
{
PersistentState tmpPersistentState;
do
{
tmpPersistentState = this.persistentState.get();
}
while (!this.persistentState.compareAndSet(tmpPersistentState, newPersistentState));
// this.persistentState.set(newPersistentState); removed as not necessary
notifyPersistentStateChanged();
}
Do I've done everything correctly, or I missed something? Any suggestions for the code and using non-blocking method for setting abject in general?
Depends what you mean by thread-safe. What do you want to happen if two threads try to write at the same time? Should one of them chosen at random be chosen as the correct new value?
This would be it at it's simplest.
protected AtomicReference<PersistentState> persistentState = new AtomicReference<PersistentState>(PersistentState.UNKNOWN);
public final PersistentState getPersistentState() {
return this.persistentState.get();
}
protected void setPersistentState(final PersistentState newPersistentState) {
persistentState.set(newPersistentState);
notifyPersistentStateChanged();
}
private void notifyPersistentStateChanged() {
}
This would still call notifyPersistentStateChanged in all cases, even if the state hasn't changed. You need to decide what should happen in that scenario (one thread makes A -> B and another goes B -> A).
If, however, you need to only call the notify if successfully transitioned the value you could try something like this:
protected void setPersistentState(final PersistentState newPersistentState) {
boolean changed = false;
for (PersistentState oldState = getPersistentState();
// Keep going if different
changed = !oldState.equals(newPersistentState)
// Transition old -> new successful?
&& !persistentState.compareAndSet(oldState, newPersistentState);
// What is it now!
oldState = getPersistentState()) {
// Didn't transition - go around again.
}
if (changed) {
// Notify the change.
notifyPersistentStateChanged();
}
}

TextField onEdit listener

I am trying to use TextField in javafx.
The scenario: I have list view populated with specific objects and edit button to edit the object associated with list cell of list view.
When I click on edit button it redirects me to a pane with editing feature where I can edit the name of that object and save it using a save button.
So I have to put validation on save button to make it enable and disable.
If I edit the name in text field then it should enable the save button otherwise it should remains disabled.
I have tried using different methods on text fields as below.
textField.textPorperty.addListener(listener -> {
//Logic to enable disable save button
});
As I am using list view, this listener gives me old value as previously edited object which does not satisfy my condition.
I can not use
textField.focusedProperty().addListener((observableValue, oldValue, newValue) -> {});
as It does not give me expected behavior.
Can anyone help me to solve this issue?
You need to implement additional logic that decides whether or not a change to the textProperty should change the enablement state of the button. This requires:
a reference to the initial value (on setting the text to the input, f.i. on changes to selection in the list)
a boolean property that keeps the enablement state (below it's called buffering)
a listener to the textField that updates the enablement state as needed
Below is a very simplified example - just to get you started - that extracts those basics into a dedicated class named BufferedTextInput. Buffering is changed internally on:
set to false if the "subject" value is set or a change is committed/discarded
set to true once on being notified on the first change of the textField
More complex logic (like not buffering on detecting a change back to the original value) can be implemented as needed.
/**
* Bind disable property of commit/cancel button to actual change.
* http://stackoverflow.com/q/29935643/203657
*/
public class ManualBufferingDemo extends Application {
private Parent getContent() {
ObservableList<Person> persons = FXCollections.observableList(Person.persons(),
person -> new Observable[] {person.lastNameProperty()});
ListView<Person> listView = new ListView<>(persons);
TextField lastName = new TextField();
Consumer<String> committer = text -> System.out.println("committing: " + text);
BufferedTextInput buffer = new BufferedTextInput(lastName, committer);
Button save = new Button("Save");
save.setOnAction(e -> {
buffer.commit();
});
save.disableProperty().bind(Bindings.not(buffer.bufferingProperty()));
Button cancel = new Button("Cancel");
cancel.setOnAction(e -> {
buffer.flush();
});
listView.getSelectionModel().selectedItemProperty().addListener((source, old, current) -> {
buffer.setSubject(current.lastNameProperty());
});
cancel.disableProperty().bind(Bindings.not(buffer.bufferingProperty()));
VBox content = new VBox(listView, lastName, save, cancel);
return content;
}
public static class BufferedTextInput {
private ReadOnlyBooleanWrapper buffering;
private StringProperty value;
private TextField input;
private Consumer<String> committer;
public BufferedTextInput(TextField input, Consumer<String> committer) {
buffering = new ReadOnlyBooleanWrapper(this, "buffering", false);
value = new SimpleStringProperty(this, "");
this.input = input;
this.committer = committer;
input.textProperty().addListener((source, old, current) -> {
updateState(old, current);
});
input.setOnAction(e -> commit());
}
private void updateState(String old, String current) {
if (isBuffering()) return;
if (value.get().equals(current)) return;
setBuffering(true);
}
public void setSubject(StringProperty value) {
this.value = value;
input.setText(value.get());
setBuffering(false);
}
public void commit() {
committer.accept(input.getText());
this.value.set(input.getText());
setBuffering(false);
}
public void flush() {
input.setText(value.get());
setBuffering(false);
}
public boolean isBuffering() {
return buffering.get();
}
public ReadOnlyBooleanProperty bufferingProperty() {
return buffering.getReadOnlyProperty();
}
private void setBuffering(boolean buffer) {
buffering.set(buffer);
}
}
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(new Scene(getContent()));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
For production use, such direct coupling between view and model (f.i. when needing the buffering for a complete form) isn't good enough, further separation might be needed. See BufferedObjectProperty and its usage in a FX adaption of the infamous AlbumManager example (very crude)

Java8 - "effectively final"

I'm using RxVertx which is a sort of RxJava along with Java8 and I have a compilation error.
Here is my code:
public rx.Observable<Game> findGame(long templateId, GameModelType game_model, GameStateType state) {
return context.findGame(templateId, state)
.flatMap(new Func1<RxMessage<byte[]>, rx.Observable<Game>>() {
#Override
public Observable<Game> call(RxMessage<byte[]> gameRawReply) {
Game game = null;
switch(game_model) {
case SINGLE: {
ebs.subscribe(new Action1<RxMessage<byte[]>>() {
#Override
public void call(RxMessage<byte[]> t1) {
if(!singleGame.contains(0) {
game = new Game(); // ERROR is at this line
singleGames.put(0, game);
} else {
game = singleGames.get(0); // ERROR is at this line
}
}
});
}
}
return rx.Observable.from(game);
}
});
}
The compilation error is:
"Local variable game defined in an enclosing scope must be final or effectively final"
I cannot define 'game' as final since I do allocation\set and return it at the end of the function.
How can I make this code compile??
Thanks.
I have a Holder class that I use for situations like this.
/**
* Make a final one of these to hold non-final things in.
*
* #param <T>
*/
public class Holder<T> {
private T held = null;
public Holder() {
}
public Holder(T it) {
held = it;
}
public void hold(T it) {
held = it;
}
public T held() {
return held;
}
public boolean isEmpty() {
return held == null;
}
#Override
public String toString() {
return String.valueOf(held);
}
}
You can then do stuff like:
final Holder<Game> theGame = new Holder<>();
...
theGame.hold(myGame);
...
{
// Access the game through the `final Holder`
theGame.held() ....
Since you need to not modify the reference of the object you can wrap the Game in something else.
The quickest (but ugly) fix is to use an array of size 1, then set the content of the array later. This works because the the array is effectively final, what is contained in the array doesn't have to be.
#Override
public Observable<Game> call(RxMessage<byte[]> gameRawReply) {
Game[] game = new Game[1];
switch(game_model) {
case SINGLE: {
ebs.subscribe(new Action1<RxMessage<byte[]>>() {
#Override
public void call(RxMessage<byte[]> t1) {
if(!singleGame.contains(0) {
game[0] = new Game();
singleGames.put(0, game[0]);
} else {
game[0] = singleGames.get(0);
}
}
});
}
}
return rx.Observable.from(game[0]);
}
Another similar option is to make a new class that has a Game field and you then set that field later.
Cyclops has Mutable, and LazyImmutable objects for handling this use case. Mutable is fully mutable, and LazyImmutable is set once.
Mutable<Game> game = Mutable.of(null);
public void call(RxMessage<byte[]> t1) {
if(!singleGame.contains(0) {
game.mutate(g -> new Game());
singleGames.put(0, game.get());
} else {
game[0] = game.mutate(g->singleGames.get(0));
}
}
LazyImmutable can be used to set a value, lazily, once :
LazyImmutable<Game> game = LazyImmutable.def();
public void call(RxMessage<byte[]> t1) {
//new Game() is only ever called once
Game g = game.computeIfAbsent(()->new Game());
}
You cant. At least not directly. U can use a wrapper class however: just define a class "GameContainer" with game as its property and foward a final reference to this container instead.
#dkatzel's suggestion is a good one, but there's another option: extract everything about retrieving/creating the Game into a helper method, and then declare final Game game = getOrCreateGame();. I think that's cleaner than the final array approach, though the final array approach will certainly work.
Although the other approaches look acceptable, I'd like to mention that you can't be sure subscribing to ebs will be synchronous and you may end up always returning null from the inner function. Since you depend on another Observable, you could just simply compose it through:
public rx.Observable<Game> findGame(
long templateId,
GameModelType game_model,
GameStateType state) {
return context.findGame(templateId, state)
.flatMap(gameRawReply -> {
switch(game_model) {
case SINGLE: {
return ebs.map(t1 -> {
Game game;
if (!singleGame.contains(0) {
game = new Game();
singleGames.put(0, game);
} else {
game = singleGames.get(0);
}
return game;
});
}
}
return rx.Observable.just(null);
});
}

How to add addGlobalEventListener in a class in blackberry?

I have made a multiple entry-point project, where App2 is set to autorun and App1 runs on user request.
I am trying to invoke a global event from App1, received by App2.
public class App2 implements GlobalEventListener {
static public int counter = 0;
public static final long countId = 0x1251402f595f81a5L;
public static final long eventId = 0xba4b84944bb7429eL;
private App2() {
Application.getApplication().addGlobalEventListener(this);
}
public static App2 waitForSingleton() {
counter = 2; // Added the counter in Runtime store in a similar way as
// added in eventOccured method
// Deleted some unuseful code
}
public void eventOccurred(long guid, int data0, int data1, Object object0,
Object object1) {
if (guid == eventId) {
callMethodOnOccuranceOfEvent();
}
}
public void callMethodOnOccuranceOfEvent() {
counter++;
RuntimeStore store = RuntimeStore.getRuntimeStore();
Object obj = store.get(countId);
if (obj == null) {
store.put(countId, new Integer(counter));
} else {
store.put(countId, new Integer(counter));
}
}
}
Then in other class I tried like
public class App1 extends MainScreen {
public App1() {
}
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
menu.add(new MenuItem("Call", 20, 10) {
public void run() {
callMethodonclick();
}
});
}
public void callMethodonclick() {
ApplicationManager.getApplicationManager().postGlobalEvent(App2.eventId);
RuntimeStore store = RuntimeStore.getRuntimeStore();
Integer c = (Integer) store.get(App2.countId);
add(new RichTextField("Event Recived#counter#" + c));
}
}
If I invoke the event for three times
Event Recived#counter#2
Event Recived#counter#2
Event Recived#counter#2
while the Expected result is
Event Recived#counter#3
Event Recived#counter#4
Event Recived#counter#5
which I guess suggests that object for App2 in not null but eventOccurred never invoked.
the output clearly suggests that callMethodonclick is not able to post Global event,even though globalEventListener was added in constructor.
Must be like this.
if (obj == null) {
store.put(countId, new Integer(counter));
} else {
store.replace(countId, new Integer(counter));
}
store.put() throw an IllegalArgumentException, because there is something in a store(see API Reference), but this Exception is handled by some system thread, that invokes eventOccured() method and show nothing about this Exception. It is one of the various Blackberry bug.
You are not updating the text in the RichTextField. It only gets added to the screen when there is no runtimestorage object associated with App2.RTSID_MY_APP.
Your code needs to keep a handle on the RichTextField by putting it into a field of the App1 object. Then update the text in the run() method.
I edited your code, adding braces to the if statement, which makes this more clear.

Categories

Resources