1

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.

  • 1
    "Does it set `this.obj` to a new instance of `obj`, or the reference to `obj`?" -> it returns the reference to the object, not a clone. "Furthermore, does it do this in every case" -> yes, you always pass the reference. "inally, in multithreading, does anything change, or is it still going to pass in the same way?" -> yes, even in multithreaded environments, references are passed to methods. – Turing85 Dec 14 '17 at 10:20
  • Take a look at [this link](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) TL;DR : you only copy a reference on this object, you do not clone it. Your program is slow for another reason. – Arnaud Denoyelle Dec 14 '17 at 10:23
  • @Turing85 Thankyou very much! –  Dec 14 '17 at 10:39
  • @ArnaudDenoyelle Thanks for the link. Now I just need to find out where the array issues are... –  Dec 14 '17 at 10:40

1 Answers1

1

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Oh no, thats fine then. I know I've got array issues all over the place but I'm just trying to single them out. If it's only pass-by-reference then I guess I'm looking in the wrong place. Thankyou very much! :) –  Dec 14 '17 at 10:39
  • May I please ask, are getters also pass-by-value? –  Dec 14 '17 at 10:43
  • 1
    @finnrayment Are you asking whether a getter is creating a new instance each time it is called? Generally it does not, unless it contains code that creates a new copy of the instance you are trying to get, and returns a reference to that copy. – Eran Dec 14 '17 at 10:45
  • Yes, that answers the question! Thankyou very much Eran. –  Dec 14 '17 at 10:48