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]);
 }
}
Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
Hanna Khalil
  • 975
  • 1
  • 10
  • 28
  • The `arr` variable's lifetime ends when `f` does, but the *array*'s lifetime is separate from the variable's lifetime. – user2357112 Sep 06 '17 at 21:57
  • You don't have to worry about memory management in Java. If you're used to C++, think smart pointers. – Bernhard Barker Sep 06 '17 at 21:57
  • but still isn't the `Array` variable storing reference of a variable with ended lifetime? – Hanna Khalil Sep 06 '17 at 21:58
  • No. It is storing a reference to the array, not the variable. You cannot have references to variables in Java. – user2357112 Sep 06 '17 at 21:59
  • 1
    Or maybe you're looking for this instead: [Does initialized java array go onto stack or heap?](https://stackoverflow.com/questions/3474852/does-initialized-java-array-go-onto-stack-or-heap) – Bernhard Barker Sep 06 '17 at 22:32
  • It may help to think of `int arr[] = {1, 2, 3};` as actually `int arr[] = new int[]{1, 2, 3};`. It declares a variable `arr`, creates an object on the stack, and assigns the latter to the former – AJNeufeld Sep 06 '17 at 23:29

2 Answers2

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

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.

jurez
  • 4,436
  • 2
  • 12
  • 20