kuhaku kuhaku - 1 month ago 11
Java Question

RunLater on current thread or give a task to current thread to run later

I want to achieve what

Platform.runLater()
does but on the current thread and the program isn't related to JavaFX, it's a Tomcat server.

I tried to do
Platform.runLater(this::foo);
but I'm pretty sure it doesn't do anything. Probably because there's no JavaFX thread to do it.

I'd rather not open a
ScheduledExecutorService
because it's going to be another thread on many instances (so many threads), not to mention the method it would need to run is
synchronized
so I smell a deadlock.

I couldn't find any useful methods on
Thread.currentThread()
(
run
and
start
don't take parameters).

Is there another option to do this?

Answer

I used a newSingleThreadExecutor to achieve this, since it can take multiple runnables to a queue and run them sequentially, it can be given tasks from several places and it will run them one by one, it's similar to platform.runLater.

Having a single thread that all instances of the class hold a reference to, solves the "many threads" problem.

It also won't cause a deadlock because it will at most wait for just one other thread to finish the synchronized function and then run just this one function.