Java Destruction

« Return to Article
  • OutlawProgrammer 2010-04-07 11:10
    Why would this have any effect on memory whatsoever? It literally does nothing.
  • Maurits 2010-04-07 11:12
    OutlawProgrammer:
    Why would this have any effect on memory whatsoever? It literally does nothing.


    Ah... now I get it. Thanks for pointing that out.
  • tim 2010-04-07 11:16
    OutlawProgrammer:
    Why would this have any effect on memory whatsoever? It literally does nothing.

    Of course it has an effect. It's code - it takes up memory.
  • DaveK 2010-04-07 11:16
    OutlawProgrammer:
    Why would this have any effect on memory whatsoever? It literally does nothing.
    It both increments *and* decrements the underlying object's reference count! You can hardly call that "nothing"!
  • Anon 2010-04-07 11:18
    public class Destruction {
    
    public static void delete(Object object){}
    }


    Yaay optimisation!
  • frits 2010-04-07 11:18
    Obviously the problem is that he forgot to call System.gc().
  • Coyne 2010-04-07 11:20
    DaveK:
    OutlawProgrammer:
    Why would this have any effect on memory whatsoever? It literally does nothing.
    It both increments *and* decrements the underlying object's reference count! You can hardly call that "nothing"!


    Uses CPU time, too. Definitely not "nothing"!
  • Bryan The K 2010-04-07 11:24
    <i>public class Destruction {
    public static void delete(Object object){
    object = null;
    }
    }</i>

    I got it. He forgot to object ? null , right?

    CAPTCHA: erat - to remove a difficult programmer by force.
  • Medinoc 2010-04-07 11:24
    And if the programmer relies on this function, it's probable that the original object reference will never be set to null (and so, the object never deleted).
  • TGV 2010-04-07 11:25
    You really haven't read about JIBE? That's Java Intention Based Execution. The compiler sees the intention of the programmer was to destruct the object, and will generate code to do so. Afterwards, all variables and fields pointing to this object will be null. I think it's time for y'all to upgrade and keep up with the literature.
  • javacoder 2010-04-07 11:26
    it allow the object to be garbage collected.... it is still a WTF because a one liner should be done by the caller
  • wil 2010-04-07 11:27
    Any Java compiler from 1.4 will optimize it away the first time this code is executed. So it would't consume any CPU nor additional memory
  • Mike Caron 2010-04-07 11:28
    I bet this application used to be written in C++.

    Only problem is that it's missing a vector delete method!
  • gm 2010-04-07 11:29
    Honestly, this is WTF-worthy?
  • Anonymously Yours 2010-04-07 11:29
    I almost want to call this article a troll to get someone to say, "Java's the real WTF," and start a holy war...
  • Randy 2010-04-07 11:29
    I'm guessing that he read somewhere that setting an object reference to null causes it to be reclaimed.

    Luckily, I've never had to worry about garbage collection with my applications. I let the VM do that for me.
  • SkittlesAreYum 2010-04-07 11:30
    javacoder:
    it allow the object to be garbage collected.... it is still a WTF because a one liner should be done by the caller


    Yeah, not really.
  • epv 2010-04-07 11:30
    The main reason it's a memory hog is that it's in Java. Bazing.
  • JamesQMurphy 2010-04-07 11:31
    javacoder:
    it allow the object to be garbage collected.... it is still a WTF because a one liner should be done by the caller

    But the object won't be garbage-collected unless ALL outstanding references are set to null. And this only sets the (newly-created) reference to null. Even the caller's reference will still be non-null.
  • frits 2010-04-07 11:34
    javacoder:
    it allow the object to be garbage collected.... it is still a WTF because a one liner should be done by the caller


    You know nulling objects to "help" the garbage collector is usually considered bad practice, right?

    http://www.ibm.com/developerworks/library/j-jtp01274.html
  • dkf 2010-04-07 11:37
    epv:
    The main reason it's a memory hog is that it's in Java. Bazing.
    The act before you with the anatomically-accurate balloon animals was better. In a depressing way.
  • friedo 2010-04-07 11:38
    javacoder:
    it allow the object to be garbage collected....


    No, it doesn't.
  • Goo 2010-04-07 11:44
    gm:
    Honestly, this is WTF-worthy?


    It shows a complete lack of understanding of how the language works. It's as bad a smell as there is. It'd not surprise me if this came from the kind of place that reboots their application server once or twice a day to keep the memory footprint at bay.

  • pcooper 2010-04-07 11:45
    Maybe the coder was used to VB, where parameters are sent ByRef by default?
  • Steve W 2010-04-07 11:45
    I'm not a Java guru (despite having used it extensively) so I'll say what I *think* is going wrong here.

    First of all, he's obviously instantiated a class whose sole purpose is to delete other objects. If this isn't a singleton then it will be taking up a lot of memory if he's instantiating a new instance every time.

    Secondly, setting it to null doesn't help. Best let the garbage collector do things on its own. I can't remember Java's semantics for parameters but I think it's a local copy of the object which is being set to null and not the original memory reference.
  • Docta Jonez 2010-04-07 11:45
    This one actually made me laugh. I've not seen a WTF that made me laugh in a while :-)

    Seriously though, this highlights just how poorly these concepts are dealt with on CS courses. I've met many developers who have a major lack of understanding about the "black magic" of garbage collection. Arbitrary null setting really drives me nuts.

    <rant>
    Seriously, if you have a memory problem in your application, run the damn thing through a profiler. Don't just start scatter-gunning null allocations throughout your code.
    </rant>

    Captcha: populus - Awesome game, 'nuff said!
  • Swedish tard 2010-04-07 11:49
    gm:
    Honestly, this is WTF-worthy?


    Quite so.
    That code displays a rather big lack of knowledge how java handles parameters, and a blatant disregard for a bunch best practices regarding the language and OOP in general.
    It is rather hard to manage to get more things wrong in a single static method class in java tbh.
  • Mike D. 2010-04-07 11:49
    This function has an upside: If it is consistently used, then there will be a distinct lack of heap fragmentation.
  • Jim 2010-04-07 11:50
    Steve W:
    I'm not a Java guru (despite having used it extensively) so I'll say what I *think* is going wrong here.

    First of all, he's obviously instantiated a class whose sole purpose is to delete other objects. If this isn't a singleton then it will be taking up a lot of memory if he's instantiating a new instance every time.

    It's unlikely they are instantiating a new class since the method itself is static.
  • Patrick 2010-04-07 11:51
    OutlawProgrammer:
    Why would this have any effect on memory whatsoever? It literally does nothing.

    Simple. It makes a copy of the object passed to it (as it is passed by value), then doesn't use it. The allocated memory remains until the garbage collector kicks in, and by then more copies of other objects would have also appeared.
  • ShatteredArm 2010-04-07 11:55
    Steve W:
    I'm not a Java guru (despite having used it extensively) so I'll say what I *think* is going wrong here.

    First of all, he's obviously instantiated a class whose sole purpose is to delete other objects. If this isn't a singleton then it will be taking up a lot of memory if he's instantiating a new instance every time.


    It's a static method. No instance needs to be created to call that method.


    Secondly, setting it to null doesn't help. Best let the garbage collector do things on its own. I can't remember Java's semantics for parameters but I think it's a local copy of the object which is being set to null and not the original memory reference.


    It's beside the point. It's not about whether it's better to let the GC do things on its own. The point is that it doesn't even do anything. Even if a forced removal of the reference were the way to go, this does not achieve that. The only reference to the object that is removed is the one on the stack that is used to pass the location of the object into the function. The original reference is left unaffected. This is not Java, it's just basic computer science.
  • Raedwald 2010-04-07 11:59
    You tell me over and over, we're on the eve of
    Destruction
    .
  • Xyro 2010-04-07 11:59
    TRWTF is that you commenters don't know how references work. No, it doesn't make a copy of the object. No, the variable reassignment doesn't bubble back to the caller. No, the garbage collector doesn't care.
  • tiller 2010-04-07 11:59
    Jim:
    Steve W:
    I'm not a Java guru (despite having used it extensively) so I'll say what I *think* is going wrong here.

    First of all, he's obviously instantiated a class whose sole purpose is to delete other objects. If this isn't a singleton then it will be taking up a lot of memory if he's instantiating a new instance every time.

    It's unlikely they are instantiating a new class since the method itself is static.


    One can hope, but I have seen people make a class with all methods static and then create instance of this class and call the static methods from the instance variable.
  • Anon 2010-04-07 12:00
    Steve W:
    I'm not a Java guru (despite having used it extensively) so I'll say what I *think* is going wrong here.

    First of all, he's obviously instantiated a class whose sole purpose is to delete other objects. If this isn't a singleton then it will be taking up a lot of memory if he's instantiating a new instance every time.


    No, the method is static.


    Secondly, setting it to null doesn't help. Best let the garbage collector do things on its own. I can't remember Java's semantics for parameters but I think it's a local copy of the object which is being set to null and not the original memory reference.


    Objects aren't "set to null", references (or pointers) to those objects are set to null. I think this is the fundamental misunderstanding that caused this code to be created in the first place.
  • avflinsch 2010-04-07 12:01
    Patrick:
    OutlawProgrammer:
    Why would this have any effect on memory whatsoever? It literally does nothing.

    Simple. It makes a copy of the object passed to it (as it is passed by value), then doesn't use it. The allocated memory remains until the garbage collector kicks in, and by then more copies of other objects would have also appeared.


    I think that is the whole purpose of the code. Create more garbage so that the garbage collection kicks in sooner.
  • Buffled 2010-04-07 12:02
    frits:
    javacoder:
    it allow the object to be garbage collected.... it is still a WTF because a one liner should be done by the caller


    You know nulling objects to "help" the garbage collector is usually considered bad practice, right?

    http://www.ibm.com/developerworks/library/j-jtp01274.html

    Depending on the JVM. The Blackberry docs encourage it, for example. That being said, the way it was implemented here is literally worse than useless.
  • rwbthatisme 2010-04-07 12:03
    obviously on an embedded system......
  • anonymous 2010-04-07 12:04
    I grow tired of this conversation. Summon the dancing girls!
  • Anonymous 2010-04-07 12:15
    anonymous:
    I grow tired of this conversation. Summon the dancing girls!

    Alright! Let's dance!

  • Russ 2010-04-07 12:20
    javacoder:
    it allow the object to be garbage collected.... it is still a WTF because a one liner should be done by the caller


    WRONG! Thank you for playing.

    It only internally to the routine sets the object to null. The routine that calls this would still have the original and untouched object.
  • OBL 2010-04-07 12:28
    Anonymously Yours:
    I almost want to call this article a troll to get someone to say, "Java's the real WTF," and start a holy war...
    INFIDEL!!!!
  • nobody 2010-04-07 12:35
    agreed.

    you guys call yourselves coders? rule 1. stfu if you don't know and don't try to pull it out of your ass.
    rule 2. it's not pass by value. go to rule 1.
  • Lunkwill 2010-04-07 12:36
    Xyro:
    TRWTF is that you commenters don't know how references work.
    Indeed, seems about a third of those who feel qualified to comment on Java stuff don't have a farkin clue how the language works. I hope that's not representative of people actually using it. "Hope dies last", as they say...

    anonymous:
    I grow tired of this conversation. Summon the dancing girls!
    s/dancing/Irish/
  • gallier2 2010-04-07 12:36
    Patrick:
    OutlawProgrammer:
    Why would this have any effect on memory whatsoever? It literally does nothing.

    Simple. It makes a copy of the object passed to it (as it is passed by value), then doesn't use it. The allocated memory remains until the garbage collector kicks in, and by then more copies of other objects would have also appeared.


    As always, the WTF are in the comments, Java doesn't make a copy of the passed object, the reference to the object is passed by value, the reference is nulled, and the original reference of the caller is not modified.

    There was also a comment at the beginning which talked about the reference counter incremented and decremented, wrong!!! The function does nothing, it writes a 0 on the call stack, that's all.
  • Bob 2010-04-07 12:37
    javacoder:
    it allow the object to be garbage collected.... it is still a WTF because a one liner should be done by the caller


    This is why this is a valid WTF! More comments from java experts please!
  • Dan 2010-04-07 12:37
    Let's not forget that Java doesn't GC with reference counting; it uses mark and sweep.
  • Lunkwill 2010-04-07 12:40
    nobody:
    agreed.

    you guys call yourselves coders? rule 1. stfu if you don't know and don't try to pull it out of your ass.
    rule 2. it's not pass by value. go to rule 1.

    2. yes it is, think of primitive types. it's just that object types *are* references. go to rule 1.
  • Sanity 2010-04-07 12:40
    frits:
    javacoder:
    it allow the object to be garbage collected.... it is still a WTF because a one liner should be done by the caller


    You know nulling objects to "help" the garbage collector is usually considered bad practice, right?

    http://www.ibm.com/developerworks/library/j-jtp01274.html


    Depends entirely on the situation. That page lists a perfectly legitimate case -- objects still technically reachable (part of an array, for instance) but which the program is done with.

    Of course, this only works if you're actually talking directly to the array. I suppose the person who wrote this wanted

    Destruction.delete(arr[i]);

    But of course, that does less than nothing. The method would only really work like this:

    Destruction.delete(arr, i);

    ...and that's specific to arrays, and also fairly useless.
  • Quicksilver 2010-04-07 12:58
    My Favourite Java Destruction till now was a program that set all instance variables null ... in the finallizer ...
    "To help garbage collection"

    argh
  • _sam 2010-04-07 13:01
    I didn't think I was a Java expert, but then I [discovered Smirnoff | read the comments from people who thought they were]...

    Good article, made me giggle.
  • fahadsadah 2010-04-07 13:03
    ShatteredArm:

    It's a static method. No instance needs to be created to call that method.


    What makes you think he knows that?
  • Jean-Marc 2010-04-07 13:05
    Java doesn't reference count... but I get what you are saying.
  • Yardik 2010-04-07 13:06
    Wow.. these comments explain exactly what happened in the code WTF, seemingly the world is full of people who *think* they know how java works but really have no clue.

    If you don't know you are right, why would you open your mouth to spout bullsh!t? Especially in a community of people who should, at least, partially, know what is going on?

    How can you appreciate a good WTF if you don't recognize that you are perpetrating one by commenting on something you don't fundamentally understand?

    *headdesk* I have no clue.
  • Optical Aleutian 2010-04-07 13:16
    Anonymous:
    anonymous:
    I grow tired of this conversation. Summon the dancing girls!

    Alright! Let's dance!



    Quick! Is she turning clockwise or counterclockwise?
  • runfaraway 2010-04-07 13:18
    Anonymously Yours:
    I almost want to call this article a troll to get someone to say, "Java's the real WTF," and start a holy war...


    http://blog.aegisub.org/2008/12/if-programming-languages-were-religions.html

    Let's hope this code is not doing anything to the object's children...

  • Winston Chang 2010-04-07 13:20
    Java method params are pass-by-value. In the case of object parameters, the reference is passed by value. It's a source of much confusion, as many people would call it "pass-by-reference", which is in a sense true, as the object is not copied, but the reference to the object is, so it's still pass-by-value. So in the case of the WTF, the method is setting a copy of the reference to null, while the original reference passed in is unaffected. That's why it does nothing.

  • Jaime 2010-04-07 13:25
    pcooper:
    Maybe the coder was used to VB, where parameters are sent ByRef by default?

    That was changed 10 years ago. If you're going to pick on VB, at least get it right.
  • Chaos215bar2 2010-04-07 13:25
    TRWTF here is definitely the number of commenters who think this helps the garbage collector, deallocates the object, or does anything other than wasting CPU cycles and memory. Seriously, this is really basic Java here.
  • hmcclungiii 2010-04-07 13:31
    One can hope, but I have seen people make a class with all methods static and then create instance of this class and call the static methods from the instance variable.
    And the award for stupidest bullsh*t comment goes to ...
  • Maurits 2010-04-07 13:41
    TRWTF is that the Destruction class isn't final.
  • Zecc 2010-04-07 13:43
    Jim:
    Steve W:
    I'm not a Java guru (despite having used it extensively) so I'll say what I *think* is going wrong here.

    First of all, he's obviously instantiated a class whose sole purpose is to delete other objects. If this isn't a singleton then it will be taking up a lot of memory if he's instantiating a new instance every time.

    It's unlikely they are instantiating a new class since the method itself is static.
    I think he meant "instantiating a class" in the sense of "creating a new class", rather than "creating an object" of that class. I may be wrong though.
  • frits 2010-04-07 13:43
    This sums up 25% of the comments today and fulfills the dancing girl request (kind of).



  • cconroy 2010-04-07 13:43
    Lunkwill:
    anonymous:
    I grow tired of this conversation. Summon the dancing girls!
    s/dancing/Irish/


    s/Irish/dancing Irish
  • Centurion 2010-04-07 13:55
    Goo:
    It'd not surprise me if this came from the kind of place that reboots their application server once or twice a day to keep the memory footprint at bay.

    Ooh, I used to work there! Seriously. We hired a guy whose sole job was to go from one webserver to the next, rebooting them, and incidentally killing the shopping carts of whoever was on at the time.

    No, we didn't want to automatically reboot them all at the same time. That would cause an outage!
  • Clock 2010-04-07 14:02
    Optical Aleutian:
    Quick! Is she turning clockwise or counterclockwise?

    Yes.
  • Maurits 2010-04-07 14:12
    Centurion:
    We didn't want to automatically reboot them all at the same time. That would cause an outage!


    Too bad nobody thought of automatically rebooting them all at different times.
  • ParkinT 2010-04-07 14:18
    Setting a referenced object to null (aka NOTHING) inside a method (aka SUBroutine) has a very "VB-esque" flavor to it.

    DIM Object
    Object = ME
    Object = NOTHING

    I Object 2 VB
  • //Rumen 2010-04-07 14:21
    In VB parameters are sent ByVal by default. :P

    And just to troll it up a little:

    "Java is TRWTF here"
  • EngleBart 2010-04-07 14:23
    The comment + code truly makes the WTF.

    For CSODs like this, a mandatory example of how it was called needs to be included to prevent speculation on how it was called and most likely provide further WTFs. Of course, the worst example should be used!

    I could see using a marker method like this if I was coding something in Java that I knew would be ported to C++. (Probably a lot safer than trying to code in C++ and then port to Java) Since this sample was dealing with Java EJBs, I don't think we can give the author the benefit of the doubt.

    Now for the Java 101 lecture...

    Java object references are really pointers. If you understand how pointers work from C, C++, or assembly then you understand how Java object references work.

    Java severely limits the pointer/reference though. There is no pointer arithmetic. All objects are allocated in the heap, never on the stack. Unlike C/C++, you can NEVER assign an arbitrary value to the reference nor access its contents. A new Object from the heap, another pointer of the same type (copy the value), or null may be assigned to an object pointer/reference. That is about it.

    Since Java passes ALL parameters, both primitives and object references, by value (another name for pass by copy), the unknowable "pointer" value is copied on the stack creating a duplicate reference to the same object. As the caller of the function, you know that no one will ever mess with your "pointers", but the callee can mess with the Object that lives at the address of the pointer. This is the cause of many bugs in java. Some other code changes a value that you thought they couldn't! Alas, there is no const Object concept like C++. Many of the Java primitive types are immutable which is as close to a C++ const Object as I have seen.

    Garbage collection(gc) is an implementation specific detail, don't count on knowing how it actually works. Most JVMs support different algorithms for gc to allow you to tune it for different scenarios. (GUI vs. server backend vs. a batch program that exits and can dump the whole memory footprint quickly)

    In some scenarios, setting a null could be necessary to ensure garbage collection, but this is rare. Stack frames are a better solution in many cases.

    Unless you have taken the time to disassemble Java byte code, don't try to guess what you think is happening. Of course, as someone else pointed out, a lot of the TRWTFs appear in the comments.

    One guy that I used to work with started "optimizing" tons of code by changing the scope of variable declarations. Aside from introducing bugs, the only thing his optimization did was to change the order of 2 variables on the stack frame. He had to revert all of his code.

  • Mo 2010-04-07 14:44
    javacoder:
    it allow the object to be garbage collected.... it is still a WTF because a one liner should be done by the caller


    Yeah, well, you know, that's just, like, your opinion, man.
  • Squire 2010-04-07 15:25
    This is totally a WTF!

    The programmer is obviously an idiot, doing something so pointless and wasteful.

    public class Destruction {
    public static void delete(Object object){
    if (object != null) {
    object = null;
    }
    }
    }

    There, I fixed it.

    </sarcasm>
  • ClutchDude 2010-04-07 15:25
    This might be borderline insulting to some, but here's a fun example for those who aren't quite getting the idea of how Java references work and why this code is a really big wtf.

    It also shows what Englebert talked about in regards to bug creation where member objects are messed with by methods that modify the object.

    package main;
    public class MainTest {
    public String b="";
    public static void main(String... args) {
    MainTest a = new MainTest();
    Destroy.destroy(a);
    if(a==null)
    System.out.println("The a reference is null!");
    else
    System.out.println("The a reference isn't null!");
    if(a.b==null)
    System.out.println("The b reference is null!");
    else
    System.out.println("The b reference isn't null!");

    }
    static class Destroy
    {
    public static void destroy(Object o)
    {
    ((MainTest) o).b=null;
    o = null;
    }
    }
    }
  • Zylon 2010-04-07 15:33
    Anonymously Yours:
    I almost want to call this article a troll to get someone to say, "Java's the real WTF," and start a holy war...

    You need disagreement to have a war.
  • Swedish tard 2010-04-07 16:15
    Optical Aleutian:
    Anonymous:
    anonymous:
    I grow tired of this conversation. Summon the dancing girls!

    Alright! Let's dance!



    Quick! Is she turning clockwise or counterclockwise?


    Yes.
  • OutlawProgrammer 2010-04-07 16:28
    Medinoc:
    And if the programmer relies on this function, it's probable that the original object reference will never be set to null (and so, the object never deleted).


    I think this is the winner. When writing my initial comment, I wondered why the story ended with something like: "this was only one of the sources of memory leaks," when, clearly, no memory is either allocated nor freed. I can only assume that the author of the Destruction class also wrote a whole bunch of code that looks like this:


    final Map cache = new HashMap();

    Object get(String key)
    {
    Object value = cache.get(key);
    if(value == null)
    {
    value = datasource.get(key);
    cache.put(key, value);
    }
    return value;
    }

    Object remove(String key)
    {
    Object cached = cache.get(key);
    if(cached != null)
    Destruction.destroy(cached); // memory leak!
    }
  • I know java 2010-04-07 16:33
    nobody:
    agreed.

    you guys call yourselves coders? rule 1. stfu if you don't know and don't try to pull it out of your ass.
    rule 2. it's not pass by value. go to rule 1.


    Hmmm, pass by reference, pass by value. In Java there are two kinds of type: primitive types and reference types. There are, therefore two kinds of value: primitive values and reference values. Calls to methods are by value, the arguments being either primitive values or reference values.

    If you are unclear on this take a look at the JLS Edition 3, section 4.1 (http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html). If you can't understand what it says there then please fuck off.

    Don't persist myths like Java is pass by reference. It's misunderstandings like that that lead to code of the calibre shown in the original post.

    If you think Java is pass by reference then could you write a simple swap function?
  • KMG 2010-04-07 16:46
    Yes! Absolutely! I do indeed concur! Wholeheartedly!
  • frits 2010-04-07 16:51
    I know java:
    nobody:
    agreed.

    you guys call yourselves coders? rule 1. stfu if you don't know and don't try to pull it out of your ass.
    rule 2. it's not pass by value. go to rule 1.


    Hmmm, pass by reference, pass by value. In Java there are two kinds of type: primitive types and reference types. There are, therefore two kinds of value: primitive values and reference values. Calls to methods are by value, the arguments being either primitive values or reference values.

    If you are unclear on this take a look at the JLS Edition 3, section 4.1 (http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html). If you can't understand what it says there then please fuck off.

    Don't persist myths like Java is pass by reference. It's misunderstandings like that that lead to code of the calibre shown in the original post.

    If you think Java is pass by reference then could you write a simple swap function?



    //Assumption a[] and b[] have one element each
    void swap(Object a[], Object b[])
    {
    object temp = a[0].clone();
    a[0] = b[0].clone();
    b[0] = temp;

    }
  • Me 2010-04-07 17:18
    javacoder:
    it allow the object to be garbage collected.... it is still a WTF because a one liner should be done by the caller


    BaBow...Try Again....
  • Welcor 2010-04-07 17:21
    frits:


    //Assumption a[] and b[] have one element each
    void swap(Object a[], Object b[])
    {
    object temp = a[0].clone();
    a[0] = b[0].clone();
    b[0] = temp;

    }

    I fail to see how this is better than

    //Assumption a[] and b[] have one element each
    void swap(Object a[], Object b[])
    {
    object temp = a[0];
    a[0] = b[0];
    b[0] = temp;
    }

    What did those clone() calls do?
  • Welcor 2010-04-07 17:23
    Oh, and by the way - this isn't passing by reference. This is passing a copy of the reference to two array objects, and then manipulating those objects.
  • Caffeine 2010-04-07 17:28
    I'm not a Java programmer, but unless the language completely redefines how object programming languages work:

    - Person A tells Person B where the memory party is.
    - Person B is a goldfish or Dory from Nemo and immediately forgets where the party is.
    - Person A doesn't have some kind of freaky Vulcan mind-meld with Person A and still knows where the party is. Truth be told A is rather glad when Person B doesn't turn up because he always thought B was a bit of a tosser.

    Captcha Genitus: The first book of the Freudian Bible
  • luis.espinal 2010-04-07 17:36
    javacoder:
    it allow the object to be garbage collected.... it is still a WTF because a one liner should be done by the caller


    The text in red is a WTF. Consider the following:


    Object lonelyTurd = new Object();
    Destructor.delete( lonelyTurd );
    // lonelyTurd is still referenciable
    // it ain't gonna get garbage collected


    A method's argument is only one of possibly many references to that object. Setting it to null does nothing.

    No, it doesn't allow the object referenced by lonelyTurd to get garbage collected.

    Once all references to an object become unreachable, then the object becomes eligible for garbage collection.

    Then it is moved to the "younger generation" region by a minor garbage collection. It is first placed in a section memory section called the "Eden", then to one "survivor" space, and then to another.

    Then, at a later time when it is deemed sufficiently *old* on the second "survivor" space, it is moved to the "tenured generation" memory space. Then ,when a "major" garbage collection executes, then and only then this object is finally garbage collected.
  • Fedaykin 2010-04-07 17:39
    Steve W:
    I'm not a Java guru (despite having used it extensively) so I'll say what I *think* is going wrong here.

    First of all, he's obviously instantiated a class whose sole purpose is to delete other objects. If this isn't a singleton then it will be taking up a lot of memory if he's instantiating a new instance every time.

    Secondly, setting it to null doesn't help. Best let the garbage collector do things on its own. I can't remember Java's semantics for parameters but I think it's a local copy of the object which is being set to null and not the original memory reference.
    \

    A.) It's a static method, there will only ever be one instance (per class loader) of that method.

    B.) Java is pseudo pass-by-reference. A copy of the reference is made and handed to the called method. However, the heap-allocated object is never copied.
  • Dave 2010-04-07 17:43
    Yeah.... seems to be written by one of those people who chose a managed environment so the 'don't have to worry about memory management' =D

    Ranks right up beside the code i see from one of our C# developers on a regular basis. It looks something like:

    if (null == myValueType)
    Throw new WtfTheyveChangedTheDotNetFrameworkException();
  • md5sum 2010-04-07 17:49
    Swedish tard:
    Optical Aleutian:
    Anonymous:
    anonymous:
    I grow tired of this conversation. Summon the dancing girls!

    Alright! Let's dance!



    Quick! Is she turning clockwise or counterclockwise?


    Yes.


    Both, among other things, depending on where exactly you are looking at her from. Also, at any given point in time progression she is also not moving, which leads to the impression that she is actually just standing still. If I had to stand still with my leg out like that for 2 seconds I'd faint...

    :D
  • luis.espinal 2010-04-07 17:51
    nobody:
    agreed.

    you guys call yourselves coders? rule 1. stfu if you don't know and don't try to pull it out of your ass.
    rule 2. it's not pass by value. go to rule 1.


    Everything is passed by value in Java, both primitives and Object pointers.

    From the JSL : http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#20448


    When the method or constructor is invoked (�15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared Type, before execution of the body of the method or constructor. The Identifier that appears in the DeclaratorId may be used as a simple name in the body of the method or constructor to refer to the formal parameter.



    What that also implies however, and taking into consideration that there is no explicit pointer de-referencing in Java, every Java pointer is itself an immutable Object reference.

    And what does that mean in codespeak? That objects are passed by reference.

    The reference to the object is passed by value (the the value of the memory address it points to gets copied). That is the definition of passing by value.

    The object being referenced to, however, does not get copied or cloned. It is still referenced by the copy of the memory address value pointing to it. That is the definition of passing by reference.

    That is, in Java, Object pass-by-reference is implemented by enforcing a pass-by-value on the Object references themselves. A coder knows the difference.
  • Frank 2010-04-07 18:39
    Dave:
    if (null == myValueType)
    Throw new WtfTheyveChangedTheDotNetFrameworkException();

    Well, yeah! It should be:

    if (myValueType == null)

    for readability!
  • Tama 2010-04-07 18:42
    I'm actually thinking that this would be a great interview question...
  • //Rumen 2010-04-07 18:42
    nobody:
    agreed.

    you guys call yourselves coders? rule 1. stfu if you don't know and don't try to pull it out of your ass.
    rule 2. it's not pass by value. go to rule 1.


    I thought rule '1' is 'You do NOT talk about fight club' ?
  • anon 2010-04-07 18:54
    this code is ridiculous, the class should have a private constructor to prevent inexpierienced programmers instantiating it.
  • tiller 2010-04-07 19:02
    [quote user="luis.espinal"][quote user="nobody"]agreed.

    The object being referenced to, however, does not get copied or cloned. It is still referenced by the copy of the memory address value pointing to it. That is the definition of passing by reference.
    [/quote]

    Kinda true but you forget one thing. The object is newer passed to the function. Think about it. The object is newer passed to the function. A reference to the object is passed to the function, so talking about whatever the object is passed by value or reference does not make sense because the object is newer passed to the function.

    And
  • newfweiler 2010-04-07 19:10
    private static List<Object> trashcan = new ArrayList<Object>();
    

    private static void Destroy(Object object) {
    trashcan.add(object);
    object = null;
    System.out.println("" + trashcan.size() + " objects have been destroyed.");
    };
  • dkf 2010-04-07 19:27
    tiller:
    The object is newer passed to the function. Think about it. The object is newer passed to the function. A reference to the object is passed to the function, so talking about whatever the object is passed by value or reference does not make sense because the object is newer passed to the function.
    “Newer”??

    You keep using that word. I do not think it means what you think it means.

    (What does the age of the object have to do with anything?)
  • dkf 2010-04-07 19:28
    luis.espinal:
    That is, in Java, Object pass-by-reference is implemented by enforcing a pass-by-value on the Object references themselves. A coder knows the difference.
    Remember, a C++ coder doesn't understand the difference.
  • Jinks 2010-04-07 20:02
    variables and pointers. concepts which elude many.
  • Maurits 2010-04-07 20:45
    md5sum:
    at any given point in time progression she is also not moving


    Zeno's arrow paradox...

    http://en.wikipedia.org/wiki/Zeno%27s_paradoxes
  • SomeJavaGuy 2010-04-07 21:00
    luis.espinal:


    Once all references to an object become unreachable, then the object becomes eligible for garbage collection.

    Then it is moved to the "younger generation" region by a minor garbage collection. It is first placed in a section memory section called the "Eden", then to one "survivor" space, and then to another.

    Then, at a later time when it is deemed sufficiently *old* on the second "survivor" space, it is moved to the "tenured generation" memory space. Then ,when a "major" garbage collection executes, then and only then this object is finally garbage collected.


    I feel compelled to point out that as soon as an object becomes eligible for collection, it will be collected by the next collection that affects the region it's in. If it becomes eligible in the Eden space (as many objects do), it won't make it to the survivor space, and similarly for the survivor to survivor/tenured spaces. Minor collections affect the Eden and survivor spaces, major collections affect Eden, survivor, and tenured spaces.

    What you described would defeat the entire purpose of generational garbage collection, which is to take advantage of the relative frequencies of different object lifespans (the vast majority of which live either very briefly or forever).
  • Bonghit 2010-04-07 21:13
    Dont know java, but in .Net land we have object.Finalize() method which should force a garbage collection on object if i remember right.


    suscipit - moo
  • kingmike 2010-04-08 00:20
    yes, yes you do. So does java. Many ways.

    It doesn;t take away from the fact that a lot of the commenters don't know what they're on about. The java memorey allocation and manipulation doesn't really translate neatly on to other languages.
  • immibis 2010-04-08 01:22
    Because of all the commenters who don't know what they're talking about, here's a C version:

    void delete(void *object)
    {
    object = NULL;
    }

    There, happy?
  • DeepThought 2010-04-08 02:16
    OutlawProgrammer:


    ...
    Object remove(String key)
    {
    Object cached = cache.get(key);

    if(cached != null)
    Destruction.destroy(cached); // memory leak!
    }


    I involuntarily winced when I read this! Good example of why the original post was such a WTF!
  • allancth 2010-04-08 02:36
    The real WTF is actually the comments by some who does not understand pass by value/ref.
  • diodor 2010-04-08 02:50
    frits:
    javacoder:
    it allow the object to be garbage collected.... it is still a WTF because a one liner should be done by the caller


    You know nulling objects to "help" the garbage collector is usually considered bad practice, right?

    http://www.ibm.com/developerworks/library/j-jtp01274.html


    I don't knew it...

    But in J2ME is IMPERATIVE to do it or you'll run out of memory quickly.... So I'll have to read more before believe it (Im going to google it now)
  • Gruntled Postal Worker 2010-04-08 03:51
    Steve W:
    I'm not a Java guru (despite having used it extensively) so I'll say what I *think* is going wrong here.

    First of all, he's obviously instantiated a class whose sole purpose is to delete other objects. If this isn't a singleton then it will be taking up a lot of memory if he's instantiating a new instance every time.

    Secondly, setting it to null doesn't help. Best let the garbage collector do things on its own. I can't remember Java's semantics for parameters but I think it's a local copy of the object which is being set to null and not the original memory reference.


    He used a static method, so the Destruction class doesn't need to be instantiated.

    Parameters are passed by value. In the case of objects this means the value of the pointer. All the delete method does is set the method local copy of the pointer to null, doing exactly nothing with the original object and marking nothing to be garbage collected.
  • csrster 2010-04-08 04:00
    Optical Aleutian:
    Anonymous:
    anonymous:
    I grow tired of this conversation. Summon the dancing girls!

    Alright! Let's dance!



    Quick! Is she turning clockwise or counterclockwise?


    It's an interesting optical illusion whereby if you lie on your back and look up her skirt
    a) she appears to change from clockwise to counterclockwise or vice-versa
    b) you can see if she's "commando", and
    c) you get kicked in the nuts and thrown out by security.
  • facilisi 2010-04-08 04:14
    Anonymous:
    anonymous:
    I grow tired of this conversation. Summon the dancing girls!

    Alright! Let's rotate our favourite barbie dolls over a mirror!



    FTFY
  • Kempeth 2010-04-08 04:41
    It's obviously implemented wrong... It should be:

    public class Destructor<T> {
    public T delete(T object){
    return null;
    }

    public static void main(String args[]) {
    SomeClass foo = new SomeClass();
    Destructor<SomeClass> bar = new Destructor<SomeClass>();
    foo = bar.delete(foo);
    }
    }
  • aswani 2010-04-08 04:47
    you are not alone in this universe brother
  • Anonymous coward 2010-04-08 04:48
    As happens a lot on this site the WTF is in the ignorant beholder. A little lesson: java is garbage collected, but sometimes people have to set a reference to null, but this is not a normal case. This method would be handy to mark those exceptional cases in the code.

    “I’d like to say that this explains why the application is a completely memory hog… but sadly, this is but one of many, many, many reasons.”

    TRWTF is that so called software engineers don't even know the basics of their platform. Setting a object reference to null does not cause a memory leak in Java like in C/C++.
  • Jan 2010-04-08 05:02
    DaveK:
    OutlawProgrammer:
    Why would this have any effect on memory whatsoever? It literally does nothing.
    It both increments *and* decrements the underlying object's reference count! You can hardly call that "nothing"!

    Well... with appropriate escape analysis (available in the latest versions of hotspot), that could be optimized away.
  • bd 2010-04-08 05:38
    Bonghit:
    Dont know java, but in .Net land we have object.Finalize() method which should force a garbage collection on object if i remember right.
    You don't remember right.

    http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx
  • Gruntled Postal Worker 2010-04-08 06:34
    Anonymous coward:
    As happens a lot on this site the WTF is in the ignorant beholder. A little lesson: java is garbage collected, but sometimes people have to set a reference to null, but this is not a normal case. This method would be handy to mark those exceptional cases in the code.

    “I’d like to say that this explains why the application is a completely memory hog… but sadly, this is but one of many, many, many reasons.”

    TRWTF is that so called software engineers don't even know the basics of their platform. Setting a object reference to null does not cause a memory leak in Java like in C/C++.


    You don't get it. If the programmer designs his program thinking that he is removing references to an object this way, then objects that he thinks are ready to be garbage collected are probably still being referenced, because the quoted code has no effect.

    There's a good chance the JVM will optimize calls to it away during runtime, because it has no side effects, and does no work other than assigning an unused value to a method LOCAL reference variable.
  • Henning Makholm 2010-04-08 07:28
    Optical Aleutian:
    Quick! Is she turning clockwise or counterclockwise?

    Counterclockwise. The reflection in the floor shows that the outstretched foot is farthest from the camera in the right-to-left half-cycle.
  • frits 2010-04-08 08:53
    diodor:
    frits:
    javacoder:
    it allow the object to be garbage collected.... it is still a WTF because a one liner should be done by the caller


    You know nulling objects to "help" the garbage collector is usually considered bad practice, right?

    http://www.ibm.com/developerworks/library/j-jtp01274.html


    I don't knew it...

    But in J2ME is IMPERATIVE to do it or you'll run out of memory quickly.... So I'll have to read more before believe it (Im going to google it now)


    Someone else pointed that else, too. We all know by now that embedded devices have their own rules. Did you notice I said "usually". I didn't mean it in the passive-agressive-I-really-mean-always kind of way. I purposely quoted an article that shows an exception.

  • frits 2010-04-08 08:59
    Welcor:
    frits:


    //Assumption a[] and b[] have one element each
    void swap(Object a[], Object b[])
    {
    object temp = a[0].clone();
    a[0] = b[0].clone();
    b[0] = temp;

    }

    I fail to see how this is better than

    //Assumption a[] and b[] have one element each
    void swap(Object a[], Object b[])
    {
    object temp = a[0];
    a[0] = b[0];
    b[0] = temp;
    }

    What did those clone() calls do?


    RTM. Object.clone() creates a new copy of the Object (not just the reference). Your way might work just fine, I don't have a Java compiler at work to test it out. I do mostly C++ and C# for work. I only use Java for school projects.

    Welcor:

    Oh, and by the way - this isn't passing by reference. This is passing a copy of the reference to two array objects, and then manipulating those objects.


    The guy asked for a swap function. He didn't say how.
  • snoopy 2010-04-08 09:13
    Wtf? that's not safe enough. Everybody knows that's just assigning null doesn't help.

    Here is proper code:

    public class Destruction {
    public static void delete(Object object){
    object = null;

    while (object != null){
    object = null;
    }

    if (object != null){
    object = null;
    }
    }
    }
  • Chezmondo 2010-04-08 09:22
    TRWTF is that this little piece of code has created 3 pages of comments.
  • luis.espinal 2010-04-08 09:25
    tiller:
    luis.espinal:


    The object being referenced to, however, does not get copied or cloned. It is still referenced by the copy of the memory address value pointing to it. That is the definition of passing by reference.


    Kinda true but you forget one thing. The object is newer passed to the function. Think about it. The object is newer passed to the function. A reference to the object is passed to the function, so talking about whatever the object is passed by value or reference does not make sense because the object is newer passed to the function.

    And


    ^.^
  • pcooper 2010-04-08 09:32
    Jaime:
    pcooper:
    Maybe the coder was used to VB, where parameters are sent ByRef by default?

    That was changed 10 years ago. If you're going to pick on VB, at least get it right.


    Oh, I meant VB, not Visual Fred or VB.NET or whatever newfangled stuff they're using now at other places. Definitely one of the poorer defaults I've seen in a programming language, but now I see it as just one of VB's quaint quirks that you get used to.
  • nik0las 2010-04-08 09:37
    TRWTF is not calling 'finalize()'...
  • luis.espinal 2010-04-08 09:41
    Anonymous coward:
    As happens a lot on this site the WTF is in the ignorant beholder. A little lesson: java is garbage collected, but sometimes people have to set a reference to null, but this is not a normal case. This method would be handy to mark those exceptional cases in the code.

    “I’d like to say that this explains why the application is a completely memory hog… but sadly, this is but one of many, many, many reasons.”

    TRWTF is that so called software engineers don't even know the basics of their platform. Setting a object reference to null does not cause a memory leak in Java like in C/C++.


    Under certain conditions (read "poor shitty coding") doing just that will actually lead to a memory leak. Memory leaks in Java are of a different nature, and I'm pretty sure the original poster of this WTF is actually referring to that (as opposed to blaming a C++ like memory leak to his Java specific memory problems.)

    See, setting an object reference parameter to null inside a method body that

    1. is outside the scope that created the object being referenced to by that reference parameter, and

    2. with the expectation that such method call in the de-allocation/garbage collection of that object (which we can safely assume that is the case given the name of the static class and method

    will most certainly cause a memory leak by virtue of not garbage collecting that object in a timely fashion (which is critical in high volume systems) or never at all if it happens to have one reference inside a data structure with a long lifespan (.ie. as an attribute in a http servlet session or application context.)

    Ever seen some people rolling their own poorly written caching layer on JEE apps that end up failing to clear their expired entries? Chances are they do something like what is described in this articles WTF.
  • yummy 2010-04-08 09:48
    frits:
    Welcor:
    frits:


    //Assumption a[] and b[] have one element each
    void swap(Object a[], Object b[])
    {
    object temp = a[0].clone();
    a[0] = b[0].clone();
    b[0] = temp;

    }

    I fail to see how this is better than

    //Assumption a[] and b[] have one element each
    void swap(Object a[], Object b[])
    {
    object temp = a[0];
    a[0] = b[0];
    b[0] = temp;
    }

    What did those clone() calls do?


    RTM. Object.clone() creates a new copy of the Object (not just the reference). Your way might work just fine, I don't have a Java compiler at work to test it out. I do mostly C++ and C# for work. I only use Java for school projects.

    Welcor:

    Oh, and by the way - this isn't passing by reference. This is passing a copy of the reference to two array objects, and then manipulating those objects.


    The guy asked for a swap function. He didn't say how.


    1 - clone is protected.
    2 - after the function call a[0] != b[0]
    3 - depending on the implementation of the object a[0].equals(b[0]) *might* be true if the two objects are the same type.

    So much for the swap function in java, huh
  • bd 2010-04-08 10:15
    frits:
    Someone else pointed that else, too. We all know by now that embedded devices have their own rules. Did you notice I said "usually".
    Rule number one: they don't have a filesystem (usually).
  • Spectre 2010-04-08 11:04
    pcooper:
    Jaime:
    pcooper:
    Maybe the coder was used to VB, where parameters are sent ByRef by default?

    That was changed 10 years ago. If you're going to pick on VB, at least get it right.


    Oh, I meant VB, not Visual Fred or VB.NET or whatever newfangled stuff they're using now at other places. Definitely one of the poorer defaults I've seen in a programming language, but now I see it as just one of VB's quaint quirks that you get used to.


    The current version of the language is called "VB", see http://msdn.microsoft.com/en-us/vbasic/default.aspx. So be more specific next time.
  • Unblogworthy 2010-04-08 11:31
    The Destruction-Delete Pattern works in most languages.

    For example, Here's DDP in Python:


    class Destruction:
    @staticmethod
    def delete(obj):
    obj = None

    class Eggs:
    pass

    >>> basket = Eggs()

    >>> basket
    <__main__.Eggs instance at 0x00C95530>

    >>> Destruction.delete(basket)
    >>> basket

    <__main__.Eggs instance at 0x00C95530>


    DDP ensures that my basket of eggs remains untouched.
  • OMGWTFJON 2010-04-08 11:42
    Clearly he wanted:

    import org.apache.commons.lang.mutable.MutableObject;

    public static void delete(MutableObject object) {
    object.setValue(null);
    }

    with a call like:

    Destruction.delete(new MutableObject(thingToDelete));

    :D
  • OMGWTFJON 2010-04-08 11:56
    Whoops, forgot mandatory logging and exception handling, as all enterprise applications require. And what if two threads tried to delete it at once?

    public static void delete(MutableObject object) {
    logger.debug("ENTERING delete for " + object);
    synchronized(object.getValue()) {
    object.setValue(null);
    if(object.getValue() != null) {
    logger.warn("object isn't NULL after delete!!!!");
    throw new IllegalStateException("object isn't null!");
    }
    }
    logger.debug("EXITING delete");
    }

    They should hire me. I'd soon have their shoddy code whipped into shape!
  • mike 2010-04-08 12:29
    newfweiler:
    private static List<Object> trashcan = new ArrayList<Object>();
    

    private static void Destroy(Object object) {
    trashcan.add(object);
    object = null;
    System.out.println("" + trashcan.size() + " objects have been destroyed.");
    };


    Well played. This is the funniest code I've ever seen.
  • tiller 2010-04-08 12:56
    dkf:
    tiller:
    The object is newer passed to the function. Think about it. The object is newer passed to the function. A reference to the object is passed to the function, so talking about whatever the object is passed by value or reference does not make sense because the object is newer passed to the function.
    “Newer”??

    You keep using that word. I do not think it means what you think it means.

    (What does the age of the object have to do with anything?)


    Did you quote the wrong post? I said nothing about age of objects. And the age of an object should not really matter. Except that it might influence the garbage collection policy for that object.
  • Welcor 2010-04-08 13:25
    yummy:
    frits:
    Welcor:
    frits:


    //Assumption a[] and b[] have one element each
    void swap(Object a[], Object b[])
    {
    object temp = a[0].clone();
    a[0] = b[0].clone();
    b[0] = temp;

    }

    I fail to see how this is better than

    //Assumption a[] and b[] have one element each
    void swap(Object a[], Object b[])
    {
    object temp = a[0];
    a[0] = b[0];
    b[0] = temp;
    }

    What did those clone() calls do?


    RTM. Object.clone() creates a new copy of the Object (not just the reference). Your way might work just fine, I don't have a Java compiler at work to test it out. I do mostly C++ and C# for work. I only use Java for school projects.

    Welcor:

    Oh, and by the way - this isn't passing by reference. This is passing a copy of the reference to two array objects, and then manipulating those objects.


    The guy asked for a swap function. He didn't say how.


    1 - clone is protected.
    2 - after the function call a[0] != b[0]
    3 - depending on the implementation of the object a[0].equals(b[0]) *might* be true if the two objects are the same type.

    So much for the swap function in java, huh

    I've used a similar approach to my version (without the clone() calls) several times. It will work as expected. After the call, a[0] will be equal to what b[0] was before the call, and b[0] will be equal to what a[0] was before the call.

    I was just wondering why the clone calls were there. There should be no reason to clone the objects, since we're basically just switching a couple of pointers.

  • amischiefr 2010-04-08 13:43
    Steve W:
    I'm not a Java guru (despite having used it extensively)

    First of all, he's obviously instantiated a class whose sole purpose is to delete other objects. If this isn't a singleton then it will be taking up a lot of memory if he's instantiating a new instance every time.

    Really? You've used it extensively and don't know what the static keyword does? It means he does not have to instantiate an instance in order to call the method.
  • EngleBart 2010-04-08 14:12
    "newer" as written by someone with German as their primary language would be pronounced as "never" in English.

    "Volkswagen" spoken -> "Folks vagen" means -> Folk wagon same as -> people cart.

    I used to work with a guy who must have learned English in a font that could not distinguish lower case g from lower case q. It made for lots of interesting variable names, but if you knew the algorithm you could read it.

    P.S. I love using open source from all over the world.
  • Alastriona 2010-04-08 16:48
    OutlawProgrammer:
    Why would this have any effect on memory whatsoever? It literally does nothing.


    Actually it does. Java passes function arguements by value. What this means is that when you pass Object object to the funtion, it actually creates a copy of that object, which takes up more memory. After that you set it to null, but being java it will not immediatly deallocate the memory, it will wait for the garbage collector to do this.

    Not only are you increasing memory usage (at least until the GC cleans up), you are also stressing your cpu more, because your garbage collector has way more garbage to collect. Besides the obvious fact that calling a function and copying objects all take up CPU time as well.
  • Alastriona 2010-04-08 17:02
    Alastriona:
    OutlawProgrammer:
    Why would this have any effect on memory whatsoever? It literally does nothing.


    Actually it does. Java passes function arguements by value. What this means is that when you pass Object object to the funtion, it actually creates a copy of that object, which takes up more memory. After that you set it to null, but being java it will not immediatly deallocate the memory, it will wait for the garbage collector to do this.

    Not only are you increasing memory usage (at least until the GC cleans up), you are also stressing your cpu more, because your garbage collector has way more garbage to collect. Besides the obvious fact that calling a function and copying objects all take up CPU time as well.


    Actually, I just realised that I might have made a mistake here. I believe that what java does is actually pass the reference to the object by value. So that would mean that the only additional memory allocated is that of the reference.
  • John 2010-04-08 17:33
    Alastriona:
    Alastriona:
    OutlawProgrammer:
    Why would this have any effect on memory whatsoever? It literally does nothing.


    Actually it does. Java passes function arguements by value. What this means is that when you pass Object object to the funtion, it actually creates a copy of that object, which takes up more memory. After that you set it to null, but being java it will not immediatly deallocate the memory, it will wait for the garbage collector to do this.

    Not only are you increasing memory usage (at least until the GC cleans up), you are also stressing your cpu more, because your garbage collector has way more garbage to collect. Besides the obvious fact that calling a function and copying objects all take up CPU time as well.


    Actually, I just realised that I might have made a mistake here. I believe that what java does is actually pass the reference to the object by value. So that would mean that the only additional memory allocated is that of the reference.


    Please be quiet now, you've just contributing ill-informed noise at this point.
  • TopicSlayer 2010-04-08 18:06
    OutlawProgrammer:
    Medinoc:
    And if the programmer relies on this function, it's probable that the original object reference will never be set to null (and so, the object never deleted).


    I think this is the winner. When writing my initial comment, I wondered why the story ended with something like: "this was only one of the sources of memory leaks," when, clearly, no memory is either allocated nor freed. I can only assume that the author of the Destruction class also wrote a whole bunch of code that looks like this:


    final Map cache = new HashMap();

    Object get(String key)
    {
    Object value = cache.get(key);
    if(value == null)
    {
    value = datasource.get(key);
    cache.put(key, value);
    }
    return value;
    }

    Object remove(String key)
    {
    Object cached = cache.get(key);
    if(cached != null)
    Destruction.destroy(cached); // memory leak!
    }


    With the exception that the remove method you present contains not a memory leak, rather a logic error. One that would likely be caught given get calls subsequent the supposed remove shall continue to find the key, presumably in error.
  • yummy 2010-04-08 22:34
    Welcor:
    yummy:
    frits:
    Welcor:
    frits:


    //Assumption a[] and b[] have one element each
    void swap(Object a[], Object b[])
    {
    object temp = a[0].clone();
    a[0] = b[0].clone();
    b[0] = temp;

    }

    I fail to see how this is better than

    //Assumption a[] and b[] have one element each
    void swap(Object a[], Object b[])
    {
    object temp = a[0];
    a[0] = b[0];
    b[0] = temp;
    }

    What did those clone() calls do?


    RTM. Object.clone() creates a new copy of the Object (not just the reference). Your way might work just fine, I don't have a Java compiler at work to test it out. I do mostly C++ and C# for work. I only use Java for school projects.

    Welcor:

    Oh, and by the way - this isn't passing by reference. This is passing a copy of the reference to two array objects, and then manipulating those objects.


    The guy asked for a swap function. He didn't say how.


    1 - clone is protected.
    2 - after the function call a[0] != b[0]
    3 - depending on the implementation of the object a[0].equals(b[0]) *might* be true if the two objects are the same type.

    So much for the swap function in java, huh

    I've used a similar approach to my version (without the clone() calls) several times. It will work as expected. After the call, a[0] will be equal to what b[0] was before the call, and b[0] will be equal to what a[0] was before the call.

    I was just wondering why the clone calls were there. There should be no reason to clone the objects, since we're basically just switching a couple of pointers.



    Post your *complete* Java code for a swap function (non array) so we can have another WTF!
  • nobody 2010-04-09 03:35
    I was going to call you an idiot. But then I looked it up. http://javadude.com/articles/passbyvalue.htm

    So... I'm stfu.
  • anonymous 2010-04-09 06:31
    TRWTF is that I can't work out who is trolling and who isn't.
  • frits 2010-04-09 08:57
    Your right, the call to clone is completely uneccessary and possibly not compilable. That what happens when you don't actually try the code you post online. I should have just said you can use arrays as a pass-by-reference hack.
  • ags 2010-04-09 10:17
    Object references are passed by value. You can set the reference to null all you want, its not going to affect the callers reference.
  • Luke 2010-04-09 12:39
    I think this must've been written by one of my ex-colleagues; jeez!!!
  • yummy 2010-04-09 12:40
    frits:
    Your right, the call to clone is completely uneccessary and possibly not compilable. That what happens when you don't actually try the code you post online. I should have just said you can use arrays as a pass-by-reference hack.


    Not much of a hack, considering that the encapsulated variables -- themselves -- still won't be swapped, simply the containers holding them have been switched.
  • Maurits 2010-04-09 17:51
    Alastriona:
    what java does is actually pass the reference to the object by value


    Yes.

    Alastriona:
    So that would mean that the only additional memory allocated is that of the reference.


    It's not really "allocated" in the same sense that objects are allocated. It's just shoved on the stack or into a register.
  • hoodaticus 2010-04-10 07:55
    Wierdest reference leak ever.
  • LookingforSxxx 2010-04-10 11:29
    Hi! Is it weird that I am 23 and still a virgin?
    I would like to invite you to join my circle of friends on
    _ Black White Cupid c/o-m **—- My username is “looking4sexxx”
    Give me your comments on my photos. I’m waiting 4 u.
  • storray expert 2010-04-10 12:17
    javacoder:
    it allow the object to be garbage collected.... it is still a WTF because a one liner should be done by the caller

    No, just ... no
  • DaveK 2010-04-10 13:00
    Anonymous:
    anonymous:
    I grow tired of this conversation. Summon the dancing girls!

    Alright! Let's dance!
    If that's "dancing", then the doner at my local kebab shop must be Rudolf Nuryev.

  • DaveK 2010-04-10 13:15
    Jean-Marc:
    Java doesn't reference count... but I get what you are saying.
    *facepalm* *headdesk* *selfasskick*
    Well durrr me. You would have thought I should have known that, given that I just spent a week rewriting the internals of the boehm GC in order to support libgcj on Cygwin...

    In my defence, at least I "get" the notion of passing references by value well enough to realise that it would necessitate incrementing the reference count when instantiating the functions formal parameters... if only there had actually been one, LOL!
  • Thygrrr 2010-04-11 05:19
    diodor:
    frits:
    You know nulling objects to "help" the garbage collector is usually considered bad practice, right?

    But in J2ME is IMPERATIVE to do it or you'll run out of memory quickly.... So I'll have to read more before believe it (Im going to google it now)


    Sorry, but that's a myth (bullshit, actually, and still very popular among JavaME coders :))!

    The only case where it makes actual sense to do this is when you overwrite a reference with one to a new object, and both objects are sufficiently huge (e.g., large images) so you can expect the garbage collector to run during the second instantiation because there is not enough free memory left for the 2nd object.

    In fact, you can generalize this as "discard your references to objects you don't need anymore before you instantiate new ones that might not fit into memory". Most modern JavaME phones have plenty of heap space, so it's only really relevant when it comes to images or audio.


    HugeImage myImage = new HugeImage();
    //... later ...
    myImage = null;
    myImage = new HugeImage();

  • Tuna 2010-04-11 06:40
    Dan:
    <Java> uses mark and sweep.


    No, it doesn't. It uses a generational collector where the young generation is collected by copying.

    Thank you for playing.
  • DaveK 2010-04-11 10:23
    Tuna:
    Dan:
    <Java> uses mark and sweep.


    No, it doesn't. It uses a generational collector where the young generation is collected by copying.

    Thank you for playing.
    No, thank you for playing, since apparently you believe there is only one JVM in the world?

    I can tell you for an absolute fact that the GCJ/libjava JVM uses the Boehm GC to do mark and sweep.

  • Bob 2010-04-12 07:56
    Don't encourage foolishness. Setting things to null is a huge mistake in Java programming in all but a very small number of cases. The best case is you wind up with something set to null which should have been set to something which gave a more useful error when it was called erroneously later.
  • methinks 2010-04-12 14:07
    Thygrrr:
    diodor:
    frits:
    You know nulling objects to "help" the garbage collector is usually considered bad practice, right?

    But in J2ME is IMPERATIVE to do it or you'll run out of memory quickly.... So I'll have to read more before believe it (Im going to google it now)


    Sorry, but that's a myth (bullshit, actually, and still very popular among JavaME coders :))!

    The only case where it makes actual sense to do this is when you overwrite a reference with one to a new object, and both objects are sufficiently huge (e.g., large images) so you can expect the garbage collector to run during the second instantiation because there is not enough free memory left for the 2nd object.

    In fact, you can generalize this as "discard your references to objects you don't need anymore before you instantiate new ones that might not fit into memory". Most modern JavaME phones have plenty of heap space, so it's only really relevant when it comes to images or audio.


    HugeImage myImage = new HugeImage();
    //... later ...
    myImage = null;
    myImage = new HugeImage();






    Sorry, but this is complete hogwash - nulling a reference and overwriting it with a new reference has the exact same effect - the reference is lost either way, and this renders the object eligible for garbage collection if there are no more references to it in the so-called "root set of references".

    It is not guaranteed anyway that the first object is collected prior to the instantiation of the second one, no matter whether you overwrite its reference with null or directly with the new one.

    OTOH the VM will run the gc in any case if there should not be enough space for the second object (thus collecting the first one), again no matter if you overwrote the first reference with null or with the new reference.
  • CloneNotSupportedException 2010-04-12 16:16
    frits:
    I know java:
    nobody:
    agreed.

    you guys call yourselves coders? rule 1. stfu if you don't know and don't try to pull it out of your ass.
    rule 2. it's not pass by value. go to rule 1.


    Hmmm, pass by reference, pass by value. In Java there are two kinds of type: primitive types and reference types. There are, therefore two kinds of value: primitive values and reference values. Calls to methods are by value, the arguments being either primitive values or reference values.

    If you are unclear on this take a look at the JLS Edition 3, section 4.1 (http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html). If you can't understand what it says there then please fuck off.

    Don't persist myths like Java is pass by reference. It's misunderstandings like that that lead to code of the calibre shown in the original post.

    If you think Java is pass by reference then could you write a simple swap function?



    //Assumption a[] and b[] have one element each
    void swap(Object a[], Object b[])
    {
    object temp = a[0].clone();
    a[0] = b[0].clone();
    b[0] = temp;

    }


    A swap function that works would be even better. This will not compile. I think there may be a typo, but even then, assuming it should be Object temp = ... , clone is protected. Digging a bit further still, clone may throw CloneNotSupportedException.

    I'm not sure that you would need the clone for what you are trying to do, but, regardless of that, it's not a _simple_ swap function. Perhaps you could explain how your code should be used and what makes it simpler than simply writing the swap inline.

    In any case creation of a _simple_ swap function in Java seems to have been less than simple.
  • DH 2010-04-12 21:43
    I have to echo what some other users have said here:

    I feel much more knowledgable about Java after reading some of the woefully-off-target stabs in the dark being made by C programmers.

    As-written, is it pointless code? Yes.

    But some folks are trying a bit too hard to find more than that.
  • Java Geek 2010-04-13 18:13
    methinks:
    Thygrrr:
    diodor:
    frits:
    You know nulling objects to "help" the garbage collector is usually considered bad practice, right?

    But in J2ME is IMPERATIVE to do it or you'll run out of memory quickly.... So I'll have to read more before believe it (Im going to google it now)


    Sorry, but that's a myth (bullshit, actually, and still very popular among JavaME coders :))!

    The only case where it makes actual sense to do this is when you overwrite a reference with one to a new object, and both objects are sufficiently huge (e.g., large images) so you can expect the garbage collector to run during the second instantiation because there is not enough free memory left for the 2nd object.

    In fact, you can generalize this as "discard your references to objects you don't need anymore before you instantiate new ones that might not fit into memory". Most modern JavaME phones have plenty of heap space, so it's only really relevant when it comes to images or audio.


    HugeImage myImage = new HugeImage();
    //... later ...
    myImage = null;
    myImage = new HugeImage();






    Sorry, but this is complete hogwash - nulling a reference and overwriting it with a new reference has the exact same effect - the reference is lost either way, and this renders the object eligible for garbage collection if there are no more references to it in the so-called "root set of references".

    It is not guaranteed anyway that the first object is collected prior to the instantiation of the second one, no matter whether you overwrite its reference with null or directly with the new one.

    OTOH the VM will run the gc in any case if there should not be enough space for the second object (thus collecting the first one), again no matter if you overwrote the first reference with null or with the new reference.


    It has not the same effect.

    Try this with: -Xms24M -Xmx26M


    public class GCTest
    {

    public static void main(String[] args)
    {
    int [] trash;

    trash = new int[4 * 1024 * 1024];
    //trash = null;
    trash = new int[4 * 1024 * 1024];
    }

    }


    If you do not null the reference, you will get a 'java.lang.OutOfMemoryError: Java heap space' exception. That is because the JVM allocates memory first and then replace the reference.

    Captcha: esse, ich esse gerade nichts obwohl mein Magen knurrt !
  • asdf 2010-04-14 06:19
    Why the fuck did you first post something *completely* wrong and only after that actually find out the stuff you are talking about?
  • jverd 2010-04-16 18:01
    Tuna:
    Dan:
    <Java> uses mark and sweep.


    No, it doesn't. It uses a generational collector where the young generation is collected by copying.

    Thank you for playing.


    Don't the older generations use M&S though?
  • Jake Clarson 2010-04-17 08:03
    This is exactly the kind of sh*t you get when you insist to say that Java has call-by-reference semantics, while in fact it's strictly call-by-value in a local JVM.

    There is subtle but important difference between passing a pointer by value (what Java does) or passing a variable by reference (which Java doesn't).
  • Squid 2010-04-20 07:13
    I hate java. My teacher used to say stupid stuff as examples and give us some code to copy, then piss off out the class until it was 3 mins from ending. By which time only one person in the class had managed to get it to work and he'd used a totally different method (some smug guy that already knew how to code).

    I could never be assed to get a book as the language just seems retarded and why do people feel the need for such long variable names?
  • Wowzers 2010-04-21 14:25
    TRWTF here is the astounding amount of ignorance in the comments. I estimate that over 9 of 10 comments contain misleading, misguided or just plain incorrect information.

    Even better are the ones that take on a condescending tone after stating something completely incorrect as fact.

    Seriously, if you're not 100% sure about what you're going to say, keep your mouth shut. Especially if you're going to open it to rag on some other ignorant mutt.
  • Brian 2010-04-22 14:11
    This will at least throw compiler warning, but it is probably asking too much for someone to read those.
  • Carl 2010-06-01 02:35
    Sorry you are wrong, the method call is static so it will not create a new Destruction object every time, the second part of your answer is correct ;-)
  • withheld 2012-06-07 13:09
    s/\(Irish\)/dancing \1/