Collection of garbage Java by local and global variable with Thread Safe


Which of the below snip of code is more Garbage Collection efficient in terms of TIME

Class Test{...}

Local Variable

private void function(){
   Test test = new Test();

Global Variable

Test test = null;
private void function(){
   if(test == null){
     test = new Test();

Let assume function() call frequently


You all are good. Answered well. Now I come to a point that

CASE-1 is more GC efficient than CASE-2 but on the other hand CASE-1 is not thread safe. So both having pros and cons


In case 1 a Test is created and becomes eligible for GC on each call and this creates lots of garbage. In case 2 it's created once and is possibly never GCed.

Why we dont always use option 2 - it may be not thread safe. Let's replace Test with SimpleDateFormat and function() will need synchronization or it will not work in multi-threaded app. Synchronization is expensive too. So we need to decide which option is better a new object each time or syncronization.