0

Is the following code safe in Java? My concern is due to the fact that in function f() variable arr is allocated on stack and as such is deallocated upon leaving the scope but is still referred to outside the scope.

public class Main {

public static class Array {
    public final int[] arr;

    public Array(int arr[]) {
        this.arr = arr;
    }
}

public static Array f() {
    int arr[] = {1, 2, 3};
    return new Array(arr);
}

public static void main(String[] args) {
    Array a = f();
    System.out.println(a.arr[0]);
    System.out.println(a.arr[1]);
    System.out.println(a.arr[2]);
 }
}
6
  • The arr variable's lifetime ends when f does, but the array's lifetime is separate from the variable's lifetime. Commented Sep 6, 2017 at 21:57
  • You don't have to worry about memory management in Java. If you're used to C++, think smart pointers. Commented Sep 6, 2017 at 21:57
  • but still isn't the Array variable storing reference of a variable with ended lifetime? Commented Sep 6, 2017 at 21:58
  • No. It is storing a reference to the array, not the variable. You cannot have references to variables in Java. Commented Sep 6, 2017 at 21:59
  • 1
    Or maybe you're looking for this instead: Does initialized java array go onto stack or heap? Commented Sep 6, 2017 at 22:32

2 Answers 2

1

In f you create variable arr which is an int array and then construct an Array object which ends up having a pointer to that same primitive int array.

Function f then ends returning the Array object - the variable arr goes out of scope but the memory location it points to is still referenced by the Array object being returned so the memory location cannot be garbage collected. The return value is then assigned to variable a of your main method meaning that the memory that arr originally pointed to still cannot be garbage collected until the main method ends. This is shown by the fact that the values of what was originally called arr are output as part of the main function

Short answer, yes this is safe to do. Memory is garbage collected when nothing is left pointing to it / when it is no longer referenced

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

Comments

1

It's safe because java uses references to track it. Even when arr goes out of scope in f, data is still referenced by a. Garbage collector will not clean it in the time it takes for the return value to be assigned, either.

On a side note, try to avoid using the same name both as local variable and field.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.