ExecutorService vs Casual Thread Spawner

后端 未结 2 1131
野趣味
野趣味 2020-12-01 16:15

I have a basic question about how ExecutorService works in Java.

It is quite hard to see the difference between simply creating Threads to

相关标签:
2条回答
  • 2020-12-01 16:41

    While the question and the sample code do not correlate, I'll try clarifying both. The advantage of ExecutorService over haphazardly spawning threads is that it behaves predictably and avoids the overhead of thread creation, which is relatively big on the JVM (it needs to reserve memory for each thread, for example). By predictability, at least for the fixedThreadPool, I mean you know the maximum number of concurrent threads, and you know when and how they might get created (so your JVM won't blow up in case of sudden peaks).

    By Vince Emigh: ExecutorService also supports cachedThreadPool, which doesn't have a max. The main reason people choose to use ExecutorService is to prevent the overhead of creating multiple threads (by using worker threads). It's mostly used in cases where many small tasks need to be executed on a separate thread. Also, don't forget about singleThreadExecutor.

    Now, on the topic of Runnable vs Callable, it is easy to see from your examples. Callables can return a value place-holder (Future) that will eventually be populated by an actual value in the future. Runnables can not return anything.

    By Vince Emigh: Runnable also cannot throw exceptions, while Callable can.

    0 讨论(0)
  • 2020-12-01 16:44

    ExecutorService provides many advantages compared to plain threads

    1. You can create/manage/control life cycle of Threads & optimize thread creation cost overheads
    2. You can control processing of tasks ( Work Stealing, ForkJoinPool, invokeAll) etc.
    3. You can schedule tasks in Future time
    4. You can monitor the progress and health of threads

    Even for a single Thread, I prefer to use Executors.newFixedThreadPool(1);

    Have a look at related SE questions:

    Java's Fork/Join vs ExecutorService - when to use which?

    What are the advantages of using an ExecutorService?

    0 讨论(0)
提交回复
热议问题