Codename One and Java synchronized keyword - codenameone

I had a suspect that a bug in one of my Codename One projects was caused by concurrent executions of the same listener (if the user taps a button very quickly more times, invoking its listener before it ended the execution)... I added a lock variable in the code, to avoid multiple executions at the same time, and this solved the bug.
This is my first time that I have this kind of problem. Reading on the web, it's suggested to use the synchronized Java keyword (however I'm not sure if it can be useful in this case).
My question is if the synchronized Java keyword is supported by Codename One.

synchronized works fine in Codename One but if you used an action listener it's unlikely that it solved the issue unless we have a huge unimaginable bug.
All events, paints, lifecycle methods etc. are invoked on the EDT. It's a single thread so two clicks on the button will happen on a single thread. synchronized would be meaningless. The EDT is used from the touch screen interaction all the way down to the event on the component itself and you can test that through the isEDT() method.
A more likely scenario is that one of the action listeners on the button uses invokeAndBlock which can trigger weird side effects in the event dispatch chain. invokeAndBlock() is used internally by AndWait methods, dialogs etc.

Using syncronized will prevent concurrent execution of the method, but will essentially queue up the request that are made, by forcing threads to wait for any current execution.
When handling this scenario, you might want to debounce the button clicks, by preventing user interaction for some period after it is first pressed, or for the duration of the resulting computation, by disabling the button and re-enabling it

Related

Locking while front-end waits on response from backend

End users in our react application have the ability to make payments to loans via a pop up. The initial problem that we encountered is that users could click the pay button twice (or heaven forbid more than twice) and this would create multiple payments throwing our accounting into disarray. We thus implemented a sort of lock state that, when triggered to true, shows a loading gif displayed in a div with a simple tweak of the z-index. The state is passed down to the pop up from 2 components above. Every now and then I get an error message displaying that there is a possible memory leak. I assume this has something to do with my fix.
I'm just wondering, is there best practice on how to handle this sort of "locking" situation with react while waiting on some other external system to respond? I've tried to do this via the front-end but I'm not 100% convinced that it's the best and/or only solution.
If you need some code to better illustrate the scenario then let me know and I'll work on adding some examples.
Thanks in advance for your advice!
There's plenty of ways of doing this. You could even had multiple layers to the process. On top of layering the page using a z-indexed loading screen, you could also disable the button depending on some form of state change.
Also, the memory leak could be from you not disposing everything after the life cycle of a particular hook ends. I would suggest you look at using useEffect as a starting point. There's a good chance that either your modal or loading indicator is causing this. Often times, this can be fixed by adding a dependency array to useEffect. Obviously, I am making a lot of assumptions here.

Can I use timerOnce with StateMachineRuntimePersister?

I have a spring statemachine (version 3.0.1) with an own instance for each user. With every HTTP request the statemachine is acquired by a DefaultStateMachineService from a JpaStateMachineRepository. At the end of the HTTP request the statemachine is released again. The state machine is configured to use a StateMachineRuntimePersister.
At one special state of the statemachine there is a transition triggered by a timer:
.withExternal()
.source( "S1" )
.target( "S2" )
.timerOnce( 60000 )
I want this timer to be executed only if the statemachine is still in state S1 after one minute (another cloud instance handling a later step of this statemachine instance could have changed the state in the meantime, making the timer obsolete).
I tried to release the statemachine without stopping it (stateMachineService.releaseStateMachine( machineId, false );). Then the timer always triggers after one minute, because it does not refresh the statemachine from the database leading to an inconsistent state.
I tried to release the statemachine stopped. Then the timer is killed and will not trigger anymore.
One solution could be to switch the trigger from timerOnce to event and to use a separate mechanism (e.g. Quartz scheduler) that reads the statemachine from database, checks the state and then explicitly fires the event.
But this would make the timer feature of spring statemachine useless in a cloud environment, so I guess there should be a better solution.
What would be the best solution here?
The problem you mentioned can be solved using Distributed States.
So, Spring Statemachine uses ZooKeeper to keep states of machines consistent in the app instances.
In your case, ZooKeeper will let your state machine know if its state changes on the other app instance and behave accordingly with the timer.
It's worth mentioning that the feature is not mature as of now according to docs:
Distributed state functionality is still a preview feature and is not yet considered to be stable in this particular release. We expect this feature to mature towards its first official release.
You can find some technical details of the concept in the Distributed State Machine Technical Paper
Personally speaking, I would stick with the solution you described (triggering event fire with a scheduler) since it gives more control over the process.

ExtJs component cleanup

I read the following comment in ExtJs-in-action -
'Do not dismiss the destruction portion of a Component’s lifecycle if you plan on developing your own custom
Components. Many developers have gotten into trouble when they’ve ignored this crucial step and have code that
has left artifacts such as data Stores that continuously poll web servers...'
I have never called explicit destructors/destroy on my my containers/components in 3.4.x
Though things seem to work fine - I am curious on
1. What are some instances where implementing destructors becomes essential
2.what is the proper convention to handle component destruction on close of browser instance.
This guide may be a good read.
You should always consider cleaning up your objects after they are needed to free up memory, especially unbinding event listeners and any timers you've created with setInterval. Once the object reference is destroyed you cannot access it but it could still be listening to or firing events and using up resources.
Generally in ExtJs, You free up resources in the destroy method, but just remember to call the callParent() function too so that ExtJs does it's own cleanup.
Here is another article from IBM in 2012 that seems to go into more depth on the subject.

How to prevent animation from being stopped by background worker in WPF

I have a WPF application that is doing some serious work (doing some calculations) when a button is hit. I wanted to add a 'busy animation'. However, the application is so busy doing its work that the animation is stopped until the calculations are finished.
The serious work should always be handled in a separate thread otherwise the complete user interface may be blocked. So you are unable to click anything and not even close the application.
If it is possible you should also try the make small chunks of work and give the rest of the application time to "take a breath" and not do all work at once. It's not always possible but some work can be managed that way.
Are you running your "serious work" in the UI thread? If so, you need to move the work to a separate thread if you still want the UI to be updated.

Advice needed for multi-threading strategy for WPF application

I'm building a single window WPF application
In the window is a list items (which are persisted in a database of course)
Periodically I need to start a background task that updates the database from an Atom feed. As each new item is added to the database, the list in the UI must also update to reflect this. I don't want this background task to slow down the UI but at the same time it needs to interact with the UI.
Having read loads of articles and seen lots of simple examples, I am still unsure of the best way to implement this.
What I think maybe I could do is:
On the Window_Loaded event, create a DispatchTimer.
When the Tick event fires, call UpdateDb() method.
UpdateDB() will get the items from the Atom feed and add to the database. As I iterate through each item I will call another method to rebind the list to the database so that it "refreshes".
When all the tasks are finished reset the DispatchTimer ??? (not sure if this can / needs to be / done).
Remember, this is background task so a user could be using the UI at the same time.
How does this sound?
Thanks.
This sounds suboptimal because you're doing database connectivity on the UI thread. When the Tick event fires on the DispatcherTimer, handlers will execute on the UI thread. You need to minimize the amount of work you do on this thread to keep the UI responsive, and you definitely shouldn't be doing IO-bound work on this thread.
I would probably have a data service whose responsibility is to update the database and raise events as changes are made. Your UI layer can attach to these events and marshal to the UI thread to apply changes. To marshal to the UI thread, you just need to call Dispatcher.Invoke.
Regardless of your specific approach, the key is to do as much as you can (including any database access) on a separate thread. Marshal back to the UI thread as late as possible and do as little work as possible on the UI thread.
One other thing to note is that WPF automatically marshals changes to scalar values for you. You only need to marshal changes to collections (adding/removing/replacing items).
Your approach would work.
You'd start the timer when the app loads. For each tick of the timer, you start a thread to update the database. Once the database update has happened, you can call .BeginInvoke() on your UI objects to update the UI on the presentation thread (that will be the only time your UI should be affected).
I'd use a System.Threading.Timer, which will call a specified method at a specified interval on a threadpool thread, so no need to create an additional thread, do your db work with that and marshal back to the ui thread as needed.
WPF Multithreading with BackgroundWorker by Pavan Podila:
The good news is that you really don’t have to write such a component since one is available already: the BackgroundWorker class introduced in .Net Framework 2.0. Programmers who are familiar with WinForms 2.0 may have already used this component. But BackgroundWorker works equally well with WPF because it is completely agnostic to the threading model.

Resources