-2

Actually I was asked this question recently in an interview , I answered stack , am I right as I thought that threads would be executing methods, but could you please explain as why threads get created in stack or if not then why is it created in heap.

Thanks in advance

  • 4
    The following link may clarify your doubt: http://stackoverflow.com/questions/19433523/where-is-thread-object-created-stack-or-heap – Pooja Dubey Jun 21 '16 at 07:17
  • 1
    All objects are created on heap, including `Thread` objects. – Kayaman Jun 21 '16 at 07:21
  • 1
    A Thread object is always created on the heap (unless it is not started) Most objects are created on the heap (as that is what it is for) but in some cases when an object can be determined by Escape Analysis to have not escaped a method, it can place the object on the stack. In the case of Thread this isn't possible unless it is not actually started. – Peter Lawrey Jun 21 '16 at 07:27

1 Answers1

0

The main difference between heap memory and stack memory is that stack memory is used to store local variables and function calls while heap memory is used to store objects in Java. No matter where the object is created in code.

So Thread objects stored in heap.

Also Each Thread has its own stack to hold own local variables and function calls.

Ahmed Amr
  • 579
  • 3
  • 10