Need clarification on use of access method.

The access method is said to be used to provide exclusive access to the UI from threads outside of the request handling thread. I just wanted to clear things up. Is access ever required to be used from events related to components? For example, if I have a button that uses some data that is also being used by some background thread, does access have to be applied within the click listener for the button since it is part of the request handling thread? Or am I misunderstanding this. Thanks.

Couple of rules of thumb regarding use of ui.access(…)

  • ui.access(…) is needed always when doing modification of ui of any kind from background thread (i.e. out side request handling thread)

  • Keep ui.access(…) calls atomic, think that ui is shared resource, if you lock ui for extensive amount of time it will be blocking other possible updates

  • Try to follow MVP (Model View Presenter) type pattern. e.g. if you have button and your button click triggers async backend call. Do it follows

    • In view button clickEvent call presenter class to fetch the data

    • Implement updateWhatever(…) method in your view class and use ui.access(…) there getUI().ifPresent(ui → ui.access(() → { … })); This makes the method safe to call from background thread

    • In presenter fetch data using executor service using e.g. CompletableFuture. Update ui in callback of the future by calling view.updateWhatever(…) This makes the background thead code agnostic of ui.access(…).

The above ensures the proper separation of concern. You can have many ui controls triggering the same async backend call. You manage update of ui in single method. Click listener is kept simple. I prefer not to use background threads in view class, presenter (or in some cases model) is better place for them.