Martin Tuskevicius
Martin Tuskevicius

Reputation: 2630

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.

Upvotes: 2

Views: 1247

Answers (3)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340923

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.

Upvotes: 11

Rob
Rob

Reputation: 11733

If you want to avoid the cost of thread creation, use a Thread pool. I agree with @Gray though. Like a connection pool, a thread pool keeps you from creating things over and over again (and it keeps the number of threads from growing uncontrollably).

Upvotes: 1

Gray
Gray

Reputation: 116908

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.

Upvotes: 4

Related Questions