Is AnimationTimer running in its own thread? - javafx

Does JavaFX's AnimationTimer run on a separate thread when launched?
I ran a JavaFX application in a debugger, with and without a AnimationTimer, and in both cases there were 6 threads running. Plus, the JavaDocs don't mention it implementing Runnable.
That suggests that it's not run in its own thread, but by its very nature, I'd think it would need to run in its own thread to ensure it runs in a regular enough schedule.
And if it's not run in its own thread, is it just run in whatever thread creates it? Does that mean it's safe to modify UI elements from within the Timer if I create the AnimationTimer inside of Application's start()?

Does JavaFX's AnimationTimer run on a separate thread when launched?
No, it doesn't. It runs on the JavaFX application thread. The AnimationTimer's handle() method is called in every frame while the AnimationTimer is active. Normally, JavaFX tries to maintain a frame rate of 60 fps.
Does that mean it's safe to modify UI elements from within the Timer if I create the AnimationTimer inside of Application's start()?
Yes, it is. Since it runs on the JavaFX application thread, it is perfectly fine to modify scene graph elements. Just make sure you are not doing heavy computation in the handle().

Related

JavaFX wait / notify on Javafx thread or nested event loop

Is there a way to do a "wait()" on the javafx thread that pauses the execution of a method until a background task finishes but allowing the javafx thread to continue.
I have found a propietary method to do something like this
Toolkit.getToolkit().enterNestedEventLoop(key);
and
Toolkit.getToolkit().exitNestedEventLoop(key, value);
Imagine that you have an #FXML action method when the user clicks a button and inside that method (running on the FX Thread) I want to do the following:
1 get a value from a javafx observable property
2 disable an area of the screen and display a progress indicator
3 call a long running task on a server and stop the excution of the action method here without blocking the UI (or in other words, letting the user navigate to another screen while the background task runs)
4 continue here on the fx thread reenabling the ui and hiding the progress indicator
5 update the UI with values returned from the server.
I know one can use a javafx Task to achieve a similar thing, but that would require moving 4 and 5 to the suceeded() method of the javafx task and that is not what i want.
We've got a framework which allows the developer to annotate some of the remote service stubs on a javafx controller with a #Background annotation and replaces those stubs with a jdk dynamic proxy which switches all invocations to any method in the stubs to run on a non javafx thread and continue on 4 when the server call has finished so we don't have to fill up our code with javafx thread synchronization code.
The Toolkit.getToolkit().enterNestedEventLoop(key); and Toolkit.getToolkit().exitNestedEventLoop(key, value); work well in most cases, except in some scenarios like:
if the invocation happens on the javafx thread at application startup time (prepopulating a screen with server data on startup)
if a #FXML action method has two server calls in the same method

QtCore dependence on QCoreApplication

I am trying to use Qt as a library (similar to this), because I want to reuse Qt classes in some currently non-Qt applications, and in shared libraries as cross-platform glue. Everything is non-GUI.
Some problems are easily avoided by DirectConnection, some can be solved with private event loops, even one can run a fake QCoreApplication in a thread and it works (last resort).
I want to know what modules rely on a running instance of QCoreApplication and cannot work without it.
Some of the Qt modules (in QtCore) do need an instance of QCoreApplication to run properly. For example QTimer relies on QCoreApplication to dispatch timer events.
I was reading the documentation for QtConcurrentRun and it seems to be relying on a global instance of QThreadPool, I am about to try and see if the application execution is vital, or maybe the instance is created on first access, or maybe not.
I am going to study QCoreApplicationPrivate source (Windows and Linux for now) but any hints in the right direction is greatly appreciated.
What are other functionality dependencies to the core application? Note that it might depend on the OS.
Edit1: Thanks to Kuba's answer, It seems QCoreApplication event loop is not necessary for timer and socket events to be dispatched. So some QtCore modules require and instance of QCoreApplication, but there is no need to have a running application event loop.
You are conflating the existence of a QCoreApplication with a running event loop. Those two are separate concepts. You may well need the former for the latter, but the latter doesn't have to run in the same thread as the former.
Most notably, you don't really have to call qApp->exec() if you don't have any events to dispatch in the thread where you constructed QCoreApplication.
The existence of a QCoreApplication is, as it were, a non-issue. Things get hairier with QApplication -- you can start it in a non-gui thread, but it's not portable and won't work on OS X. I'm trying to figure out why it doesn't work, but I don't have much time now to offer a satisfactory solution -- not yet.
It is also a misconception that QCoreApplication's event loop needs to be running for socket notifications and timer events to be dispatched to other threads. A QCoreApplication's event loop is nothing special. There is a platform-specific instance of QAbstractEventDispatcher that gets created for a thread when you instantiate the first QEventLoop in that thread. The QEventLoop doesn't know anything specific about the platform.
QCoreApplication's exec() method is quite simple and creates an instance of QEventLoop, and thus will create an instance of platform-specific QAbstractEventDispatcher. This instance is not special in any way. It's the same as any other event dispatcher created in any other thread, as far as my code reading tells so far.
If all underlying window systems would support it, it'd be in fact possible to make Qt GUI code multithreaded -- the per-thread event reception and dispatch is already there as a small first step. The big obstacle, probably the only one, would be the X library and its display lock. The display lock would be an obvious matter of contention between threads. You'd need each thread that wants to talk to the GUI open up a separate connection to the X server, and I don't know if there's a supported way of doing that from Xlib.

Question about Task management, threads and other foes in flash builder

I'm building a simple task manager that will at this moment execute tasks in a serial manner. I have been reading about threads in flex and it seems it is not quite clear/prepared for real threads.
What I'm looking at this moment is a way to execute a method at the beginning or end of a flash builder update. This method will be the one that will take the responsibility to start tasks added in the previous update. The removing of finished tasks will be done through event notification (the task will notify it finished) then the scheduler will remove it and dispatch the message again to let the outside world know the task was over.
A rough workflow of the system woudl be:
1) Add Tasks to the scheduler. And listen to events of the task (finished, etc...)
2) At the beginning/ End of a flex update (don't know if this really happen) Start tasks waiting. And run tasks that have a runnable method per update.
3) When a task finishes it notifies the scheduler and it is removed from the scheduler queue and redispatches the event to let the outside world the task finsihed.
Could anybody suggest the correct place to have a method like this? Any suggestion to the scheduler?.
Thanks in advance,
Aaron.
Based on your description you don't seem to be doing anything new and that unique. I'd start first with researching existing task and concurrency solutions. If they won't do what you want, extending the code will probably still be easier than starting from scratch.
Get familiar first with Cairngorm 3 Tasks and/or Parsley Tasks.
Also take a look at the callLater() method.
Finally there is the GreenThreads project.

to create a worker thread and keep it alive throughout my application life time to perform some back ground tasks

I have a req where in i have to create a worker thread and keep it alive throughout my application life time to perform some back ground tasks . so is there any way i can stack tasks to this worker thread when ever needed by my application .?
Update: Even though you've indicated in comments you have to do this in Asp.Net, I'll leave my original content below, as it has some useful links.
Since Asp.Net uses the thread pool to schedule incoming requests, running your background task on the thread pool will take one thread off of it and will impact Asp.Net performance. Thus, you will have to use the Thread class.
To achieve your scenario, you can create a new Thread instance, set its IsBackground property to true and start it. Once started, the thread will wait for an AutoResetEvent (using the WaitOne method) to be set by an incoming request (using the Set met6hod), which will signal the background thread that its task should be processed. Once the task is finished, the background thread will again wait on the event.
This is the simplest implementation, which does not allow passing parameters between the request and the background thread and does not allow more than one tasks to be queued at a time. If you need support for parameters or queueing, you will have to keep a reference to the thread object somewhere it ill be accessible to the incoming requests.
You will also have to consider that your background thread can be killed at any point in time, if IIS decides to recycle the Asp.Net worker process. Also, throwing an exception inside the background thread will cause IIS to recycle the Asp.Net worker process.
There are also some considerations around the identity of the background thread. In particular, a background thread can't easily impersonate the identity of the user on the current incoming request. It is possible, but it will require you to pass the user identity each time a new task is scheduled by a request.
It would be useful if you tell us what language and what platform you are writing your code in.
If it happens to be a Windows platform, there is a thread pool you can "borrow" threads from for your tasks. You can schedule your task on the thread pool by using either the QueueUserWorkItem API (C++) or the ThreadPool.QueueUserWorkItem (C#/.Net). Note there are some implications if your task will be running for a longer time.
You can also create your own thread using either the Thread class (C#/.Net) or the _beginthreadex or the CreateThread API (C++). In this case, you will have to implement a queue for the foreground thread to schedule the tasks on and you will have a loop on the background thread to pick the new tasks and execute them. And of course, you will have to synchronize the access to that queue from both threads using some synchronization primitive like a CRITICAL_SECTION (C++) or the lock statement (C#/.Net).
For Linux or OS X you might look into POSIX threads. I have not done much *nix style programming, so there might be even better alternatives. If you are targeting one of these platforms, add that info to your question and I am sure there will be helpful answers in no time.
Creating a thread is typically done by calling a special primitive (CreateThread() in Win32) and passing it an entry function. That function code in invoked in the newly spawned thread and can do whatever it wishes - for example, it could start a loop and peek tasks from a queue created in advance. Your main thread could post tasks to that queue so that the worker thread processes them. When there're no tasks in the queue the worker thread could simply block on a synchronization primitive (an event for example) waiting for new tasks to be posted.

Check if thread is still running

In an ASP.NET MVC application during application_start a new thread gets startet. The thread loads data into the Cache and takes 5 minutes. The application needs to be aware that the loading is in process. Thats why I want to set a flag in an application variable.
I set Application["LoadingCacheActive"] to true when I start the thread.
I dont find a way to set this variable to false when the thread finished. I dont want to use thread.Join, because the application_start has to complete imediately. Inside the created thread I cant set the the variable, because HttpContext.Current is not available.
Any suggestion?
You can use a static AutoResetEvent/ManualResetEvent data member in your Application class. Create the event as not set initially. When you app needs to check whether the thread is finished, it can call WaitOne(0) to test the state of the event. When the thread is finished, it can set the event. If you are using ManualResetEvent, you need to reset it before starting new thread.
You can also use Thread.ThreadState, however, as MSDN states:
Thread state is only of interest in
debugging scenarios. Your code should
never use thread state to synchronize
the activities of threads.
I've had to do similar things. The easiest way is to clear the flag in the last line in the thread.
EDIT: Franci Penov is right, your thread might get killed by a application pool shutdown. However in this case that should not harm you.

Resources