Swing timer alternative for JavaFX and the thread management difference - multithreading

Is it safe to use Swing timer for JavaFX or there is an special alternative for Swing? What is the differnce of the thread management between JavaFX and Swing?
In fact I'm interested to know the equivalents of Swing Timer, SwingUtilities.invokeLater() and invodeAndWait() for JavaFX.
By the way what if we use some Swing components in the JavaFX? Should we use two parallel Timer/Threads for updating those components?

JavaFX equivalent of SwingUtilities.invokeLater()
Platform.runLater(java.lang.Runnable runnable)
See also JavaFx response to SwingUtilities.invokeLater.
JavaFX equivalent of invokeAndWait()
The public JavaFX API deliberately does not expose an invokeAndWait call on Platform.runLater because it is easy to deadlock yourself with it, so you can use the below code instead as long as you know exactly what you are doing.
final FutureTask query = new FutureTask(new Callable() {
#Override
public Object call() throws Exception {
return queryPassword();
}
});
Platform.runLater(query);
System.out.println(query.get()); // the get blocks until the query FutureTask completes.
See also Return result from javafx platform runlater.
JavaFX equivalent of javax.swing.Timer.
Use a Timeline. The following will update a label displaying the date every second:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Label dateLabel = new Label();
Timeline timeline = new Timeline(
new KeyFrame(
Duration.ZERO,
actionEvent -> dateLabel.set(dateFormat.format(new Date()))
),
new KeyFrame(
Duration.seconds(1)
)
);
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
See also the Timeline based answer to How to update the label box every 2 seconds in java fx?.
If we use some Swing components in the JavaFX? Should we use two parallel Timer/Threads for updating those components?
I think not, depends on the app, but generally a single Timer for the application would be preferred. This is kind of a specialized case. Generally, if you have some asynchronous process happening on a Timer, you want it to happen all at once, so the Timer fires, does some processing, then shunts the results back to the GUI. As you are mixing two UI frameworks, it's a little more complicated because you want to update both frameworks with results at the same time or within the same render frame.
To approximate this, I'd advise using just a plain java.util.Timer, rather than a javax.swing.Timer, or use a ScheduledExectorService if you need more flexibility. Then, in the TimerTask or scheduled Runnable, perform your processing logic and after the processing is done make calls to Platform.runLater and seperately SwingUtilities.invokeLater as appropriate to shunt the results back to either JavaFX or Swing components.
Of course you should consider if mixing two frameworks such as this and dealing with the potential threading complications is worth it. If you are able to just use a single framework and rely on the concurrency approach which works best with that framework, I think that would be a preferred approach.
What is the difference of the thread management between JavaFX and Swing?
From a user point of view it is pretty similar. Both JavaFX and Swing remain single threaded frameworks for application layer UI processing. All user code for JavaFX runs on the JavaFX application thread. Moreover any code which may modify the active scene graph (nodes displayed on the stage), must run on the JavaFX application thread. These rules are similar to the nature of thread management in Swing programming.
The JavaFX application thread and the Swing thread in the initial release of Java 8 are different by default. So:
To update Swing components from the JavaFX application thread, use Platform.runLater to switch processing from the JavaFX thread to the Swing thread.
To update JavaFX nodes from the Swing thread, use SwingUtilities.invokeLater to switch processing from the Swing thread to the JavaFX thread.
A future release of the Java platform may feature a unified application thread for Swing and JavaFX.
Note that the internal threading implementation used in library code differs between Swing and JavaFX. JavaFX will use different hardware and software rendering pipelines which can run on their own thread. However, this internal implementation detail is completely hidden from the application programmer.
Reference Documentation
Concurrency in JavaFX Tutorial by Oracle. In particular, see the sections on Task and Service for managing background operations from JavaFX, topics which are not explicitly discussed in this answer.

Related

JavaFX Progress Dialog On Saving

At one point in my application, I have to save a JavaFX UI which takes a long time. During this save, I have to show a Progress Dialog telling the user what is happening at that time.
I have read that heavy tasks should be ran using a Task and not the JavaFX thread. However, this is not possible for me for the 2 following reasons:
1- The heavy tasks include JavaFX confirmation dialog popups which are sometimes buggy on MAC if not called by the JavaFX thread.
2- The save method must return a boolean to tell if the save went ok or not. And this save method is triggered by the JavaFX thread. Meaning the JavaFX thread must return the boolean variable and has to wait for the Task to finish before doing that.
And sadly the JavaFX UI is integrated in a Swing UI which makes it more difficult to work with.
Task is just one implementation of the javafx.concurrent.Worker interface, which provides facilities to communicate with the GUI respectively the JavaFX thread. Other implementations are Service and ScheduledService. Basically, the difference is that Service is designed for reuse, whereas Task isn't, and ScheduledService can restart itself after execution.
So, to address your two concerns:
The heavy tasks include JavaFX confirmation dialog popups which are sometimes buggy on MAC if not called by the JavaFX thread.
As mentioned before, the Worker interface provides a nice API to update the GUI from another thread. For instance, from the JavaFX thread, you can easily bind a Labeled to the message property which gets updated from the background thread.
The save method must return a boolean to tell if the save went ok or not. And this save method is triggered by the JavaFX thread. Meaning the JavaFX thread must return the boolean variable and has to wait for the Task to finish before doing that.
For example, Task's call() method can return arbitrary objects, which includes Boolean. Moreover, the Worker interface has a getValue() method to retrieve the result from the corresponding worker.
I recommend reading the "Concurrency in JavaFX" tutorial for further information. For ProgressBar itself, have a look at the "Progress Bar and Progress Indicator" tutorial.

how to use c# threads in unity3d for android platform?

I am in need to load files, scenes and play animations in threads..
Tried loading files via www in Android...
how to do other stuff via threads?
But how come a game engine doesn't allow us to create threads?
or my understanding is wrong?
how can one create threads in UNITY3D?
You can use threads in Unity but the engine is not thread safe. Usually you run detached threads (from the Unity UI) to do long running processes and check on results (you cannot interact with Unity from the working thread).
The common approach is to use a class which represents a threading job which will be initialized by the Unity main thread. Then you start a worker thread on a function of that class and let it do it's job (Coroutines run on the Unity main thread so are not real threads. Best article on Coroutines is here)
Here's an example of the approach described above (see accepted answer):
http://answers.unity3d.com/questions/357033/unity3d-and-c-coroutines-vs-threading.html
You might also want to try a UnityGems package that achieves the same effect but provides convenience (such as closure support). See this page
HTH.
Best!
From my own personal experience with Unity, you cannot create/run a separate thread unless the thread doesn't use any of Unity's api. So that means no gameObjects or things of similar nature.I've successfully done it myself for my own pathfinding so I know it is possible. Good Luck! I hope this helps.
A commonly used approarch in Unity3D is to use Coroutines.
IEnumerator DoSth()
{
...
yield retrun ... ;
}
To call/Consume the coroutine:
StartCoroutine(DoSth()); // OK
StartCoroutine("DoSth"); // Also fine
StopCoroutine("DoSth"); // You can stop it as well

Submitting a background job and updating stage with result

I'm a complete noob with JavaFX 2 - (started this morning with a HelloWorld that I'm adapting).
I need to update a Text node with the result of a background thread. Is there anything special I need to be aware of with JavaFX2 or is it simply enough to submit a callable and update the text. A pointer to a tutorial would be appreciated.
After calculating the results, running the
Platform.runLater(new Runnable() {
#Override
public void run() {
// Update the text node with calculated results
}
});
at the end of the same background thread is enough in normal situations. This link also maybe helpful:
Execute task in background in JavaFX.
Platform.runLater() will run later on the JavaFX application thread - which is fine if the executed content is a quick running task (e.g. inexpensive computation without I/O or just a call to update the UI). Use a Timeline for animation or timer based things. Otherwise a Task or Service based solution, for which there is a tutorial. Don't ever read or write from objects involved in an active scenegraph (even updates triggered by binds) off of the JavaFX application thread. Some further discussion and examples are in this forum thread.

Does WinRT still have the same old UI threading restrictions?

In WinForms, pretty much all your UI is thread-specific. You have to use [STAThread] so that the common dialogs will work, and you can't (safely) access a UI element from any thread other than the one that created it. From what I've heard, that's because that's just how Windows works -- window handles are thread-specific.
In WPF, these same restrictions were kept, because ultimately it's still building on top of the same Windows API, still window handles (though mostly just for top-level windows), etc. In fact, WPF even made things more restrictive, because you can't even access things like bitmaps across threads.
Now along comes WinRT, a whole new way of accessing Windows -- a fresh, clean slate. Are we still stuck with the same old threading restrictions (specifically: only being able to manipulate a UI control from the thread that created it), or have they opened this up?
I would expect it to be the same model - but much easier to use, at least from C# and VB, with the new async handling which lets you write a synchronous-looking method which just uses "await" when it needs to wait for a long-running task to complete before proceeding.
Given the emphasis on making asynchronous code easier to write, it would be surprising for MS to forsake the efficiency of requiring single-threaded access to the UI at the same time.
The threading model is identical. There is still a notion of single threaded and multi-threaded apartments (STA/MTA), it must be initialized by a call to RoInitialize. Which behaves very much like CoInitialize in name, argument and error returns. The user interface thread is single threaded, confirmed at 36:00 in this video.
The HTML/CSS UI model is inherently single threaded (until the advent of web workers recently, JS didn't support threads). Xaml is also single threaded (because it's really hard for developers to write code to a multithreaded GUI).
The underlying threading model does have some key differences. When your application starts, an ASTA (Application STA) is created to run your UI code as I showed in the talk. This ASTA does not allow reentrancy - you will not receive unrelated calls while making an outgoing call. This is a significant difference from STAs.
You are allowed to create async workitems - see the Windows.System.Threadpool namespace. These workitem threads are automatically initialized to MTA. As Larry mentioned, webworkers are the JS equivalent concept.
Your UI components are thread affined. See the Windows.UI.Core.CoreDispatcher class for information on how to execute code on the UI thread. You can check out the threading sample for some example code to update the UI from an async operation.
Things are different in pretty important ways.
While it's true the underlying threading model is the same, your question is generally related to how logical concurrency works with UI, and with respect to this what developers see in Windows 8 will be new.
As you mention most dialogs previously blocked. For Metro apps many UI components do not block all. Remember the talk of WinRT being asynchronous? It applies to UI components also.
For example this .NET 4 code will not necessarily kill your harddrive because the UI call blocks on Show (C# example):
bool formatHardDrive = true;
if (MessageBox.Show("Format your harddrive?") == NO)
formatHardDrive = false;
if (formatHardDrive == true)
Format();
With Windows 8 Metro many UI components like Windows.UI.Popups.MessageDialog, are by default Asynchronous so the Show call would immediately (logically) fall through to the next line of code before the user input is retrieved.
Of course there is an elegant solution to this based on the await/promise design patterns (Javascript example):
var md = Windows.UI.Popups.MessageDialog("Hello World!");
md.showAsync().then(function (command) {
console.log("pressed: " + command.label); });
The point is that while the threading model doesn't change, when most people mention UI and threading they are thinking about logical concurrency and how it affects the programming model.
Overall I think the asynchronous paradigm shift is a positive thing. It requires a bit of a shift in perspective, but it's consistent with the way other platforms are evolving on both the client and server sides.

Why is startApp() used instead of the constructor in Java ME applications?

A lot of Java ME tutorials use the startApp() method for creating and initializing objects and the constructor is left blank. However, the startApp() method is also invoked when the MIDlet resumes from a paused state. This causes all the objects to be re-initialized and any changes made are lost.
I have also noticed that the netbeans IDE, in its auto-generated code, uses many if(object==null) statements in startApp() to check if the object was created earlier.
Would it not make sense to simply do all the object creation and initialization in the constructor itself? Is there any reason for not doing this?
This is in part about understanding the MIDP threading model.
What thread the MIDlet constructor is called in depends on who developed the Java Virtual Machine on the phone.
Developers have a tendency to rely only on what the MIDP specification says in that area, which is how startApp, pauseApp and lcdui event handling should behave.
However there are only a few cases where this is important.
The second aspect to this issue is software developers trying to free as much resources (memory, file handles, sockets...) as possible when the MIDlet is paused.
Again, there are cases when MIDlets should hang on to some resources even when paused but you really need to think about what you're doing (and understand it better than casually) when coding that kind of behavior.
It is also worth remembering that some phones always keep the JVM process running. When they also have a JVM that doesn't support class unloading (as is usual in a J2ME world), this means that static variables can remain in memory even after the MIDlet has been completely destroyed.

Resources