Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it expensive to create the Thread object or to actually start the thread?

Consider this question.

Now there are various reasons as why creating a thread is expensive, notably the fact that a lot of memory needs to be allocated and the thread needs to be registered.

Now consider this code:

Thread thread = new Thread(new SomeRunnable());
thread.start();

Which part of that is the "expensive" part? The line that actually creates the Thread object or the line that starts the thread? Or both? The reason why I am asking is because I am writing the server-component of a game and I am debating if I should create the Thread object as soon as the player connects and start the thread once the player finishes logging in, or should I both create and start the thread after the player finishes logging in.

like image 497
Martin Tuskevicius Avatar asked May 16 '26 01:05

Martin Tuskevicius


2 Answers

Creating a Thread object is very cheap. You just pay the price of calling the constructor. It's the start() method that takes up space (native calls, stack memory, etc.)

On the other hand if you create plenty of threads, consider creating (and starting them) in advance and having a pool. This is already done for you, check out Executors class.

like image 86
Tomasz Nurkiewicz Avatar answered May 18 '26 13:05

Tomasz Nurkiewicz


This really smacks of premature optimization to me. I really doubt that you are going to see any difference between instantiating or starting the thread earlier rather than later. If it was 100 threads then I might feel differently.

If you have seen performance problems with your application then I would encourage you to use a profiler to discover the real performance sinks.

like image 44
Gray Avatar answered May 18 '26 14:05

Gray