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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With