4

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()?

GOXR3PLUS
  • 6,877
  • 9
  • 44
  • 93
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • ApplicationTimer or AnimationTimer? – ItachiUchiha Oct 11 '15 at 19:07
  • @ItachiUchiha Oops! Good catch. Sorry. I'll fix it. – Carcigenicate Oct 11 '15 at 19:10
  • There is already a thread managing scheduling to render each frame: the FX Application Thread. Since the `handle` method is invoked once per frame on that thread, it needs no additional threading mechanisms of its own to managing the scheduling. – James_D Oct 11 '15 at 19:30

1 Answers1

5

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().

ItachiUchiha
  • 36,135
  • 10
  • 122
  • 176
  • Just to clarify. When you say that it runs on the application thread, that's because that's the thread that it was started on and not because of some black magic in the background correct? – Carcigenicate Oct 11 '15 at 21:47
  • 1
    I believe you *have* to call `AnimationTimer.start()` on the FX Application Thread. However, what `start()` does is register the timer with a centralized timer from the toolkit, that subsequently invokes `handle()` on the FX Application Thread for you. So, if you consider that black magic, then yes, it's done by black magic. The source code is [here](http://hg.openjdk.java.net/openjfx/8u60/rt/file/996511a322b7/modules/graphics/src/main/java/javafx/animation/AnimationTimer.java). – James_D Oct 11 '15 at 22:13