CRoemheld
CRoemheld

Reputation: 949

Situational use: Run tasks in ForkJoinPool vs. new Thread

Since I'm trying to understand a few of the new features provided in Java 8, I came upon the following situation:

I wish to implement asynchron method calls into my application (in JavaFX). The idea was to provide/use a seperate thread for everything related to the GUI so that background tasks wont block/delay the visible output in my application.

For the background tasks, I thought about either use a pool of threads or simply run them in the main thread of the application for now. Then, I came upon the ForkJoinPool used in the standard way by using the CompletableFuture class when doing something like this:

CompletableFuture.runAsync(task);

whereas task is a Runnable.

In most tutorials and the Javadoc, the ForkJoinPool is described as "a pool which contains threads waiting for tasks to run". Also, the ForkJoinPool is usually the size of the cores of the users machine, or doubled if hyperthreading is supported.

What advantages does the ForkJoinPool give me over the traditional Thread when I want to run a task asynchronously?

Upvotes: 3

Views: 919

Answers (1)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23349

ForkJoinPool is not comparable with Threads, it's rather comparable with ThreadPools. Creating a new thread by code often bad and will lead to OutOfMemoryErrors because it is not controlled. Depending on your use case you might need to use a ForkJoinPool or a different pool but make sure you use one. And by the way, all CompletableFuture methods have overloads that allow you pass your own thread pool.

Some benefits of ForkJoinPool,

  • Already initialised for you and shutdown on the JVM shutdown, so you don't need to worry about that
  • Its size can be controlled through a VM parameter
  • Its perfect for compute bound task where work stealing can be beneficial, although this could be a problem depending on the case.

Upvotes: 1

Related Questions