1

It is said that Java allows to run multiple threads in parallel. It also says that object creation is cheap so that I must always prefer creating new object to reusing them. But, to my knowledge, the objects are created in the global scope (to become a subject to GC). Now, comes the wonder, is parallelism stopped when any of the threads creates an object?

AFAIK, unmanaged languages create the objects on the thread stack so that threads keep running independently. They are all removed once you exit from the subprogram scope. That is you need not add the objects into global list and stop the machine to GC them later. You could do the same with Int/String-like immutable objects in Java, because thy cannot refer other objects creating circular dependencies, that need GC to cleanup. But, afaik, nothing is cleaned up at procedure exit in Java.

1
  • The question is still not clear to me, Can you explain me a bit more about what you are asking basically ? Commented Jun 16, 2016 at 8:07

1 Answer 1

2

Allocation of small objects is quite cheap most of the time because of TLAB (Thread Local Allocation Buffer). Every single thread has a special area in Eden reserved for thread-local allocations called TLAB.

So, you need synchronization only for allocation a new TLAB when previous is filled. That synchronization is a CAS operation, so it is quite fast.

        Eden                       Survivor 1/2
-------------------------------------------------
| T  |     | T  |                ||      |      |
| L  |     | L  |                ||      |      |
| A  |     | A  |                ||      |      |
| B  |     | B  |                ||      |      |
|    |     |    |                ||      |      |
| 1  |     | 2  |                ||      |      |
-------------------------------------------------
  ^           ^
  |           |
  reserved for|thread-1 allocations
              |
              |
              reserved for thread-2 allocations

Moreover, some optimizations can help you to avoid allocations in compiled code - Escape Analysis and Scalar Replacement. In some scenarios compiler can eliminate allocations by placing all the fields of an object on the stack.

Sign up to request clarification or add additional context in comments.

1 Comment

It might be worth adding that, as long as a thread doesn’t modify heap variables outside the TLAB, it is impossible for any other thread to have a reference to any of the newly created objects in that TLAB. And the JVM tracks exactly that, to enable local or minor collections, which do not need stopping the entire JVM (to address the second paragraph of the question).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.