2

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.

Community
  • 1
  • 1
Martin Tuskevicius
  • 2,590
  • 4
  • 29
  • 46

3 Answers3

11

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.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • Couldn't agree with this answer more - don't explicitly manage your threads, let the executors framework do it for you. – Krease Jan 28 '13 at 20:58
  • If I create a thread when a player connects and I stop (interrupt) it when the player disconnects, what Executor would you suggest I use? And also, by saying, "You just pay the price of calling the constructor." are you implying that the first line is the most expensive of the two? – Martin Tuskevicius Jan 28 '13 at 21:43
  • @MartinTuskevicius: check out [`Executors.newCachedThreadPool()`](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool()). And calling a constructor should be very fast, almost free. It's `start()` that takes time and consumes memory. – Tomasz Nurkiewicz Jan 28 '13 at 22:02
4

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.

Gray
  • 115,027
  • 24
  • 293
  • 354
  • 2
    I understand that it's a relatively small thing, but it's a matter of changing two lines for me. I would still like to know the better of the two options. – Martin Tuskevicius Jan 28 '13 at 19:21
1

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).

Rob
  • 11,446
  • 7
  • 39
  • 57