Search code examples
javaobjectpass-by-referencepass-by-value

Passing by reference into a setter


So I'm experiencing some really massive memory and CPU leaking on my Swing program and realised that I wasn't executing absolutely everything necessary on the EDT, but was stupid enough to go passing everything into methods, eventually realising that I was duplicating objects and their 2000 arrays because of the "pass-by-value" rule.

My question is, for the following code:

public class Test {
    Object obj = new Object();
    public void setOBJ(Object obj) {
        this.obj = obj;
    }
}

Does it set this.obj to a new instance of obj, or the reference to obj?

Furthermore, does it do this in every case or are there certain circumstances where one or the other may happen? I'd try this but don't know where to start and what cases it may happen in.

Finally, in multithreading, does anything change, or is it still going to pass in the same way? Just curious to be honest.


Solution

  • setOBJ(Object obj) assigns a reference of an Object to this.obj. It doesn't create a new instance.

    On the other hand, each time you create a new instance of Test, a new Object instance is also created and assigned to obj (as a result of Object obj = new Object();).

    The question is how many times you call setOBJ, and whether each time you pass to it a new Object instance. We can't tell by the code you posted.