• (cs) in reply to Bonghit

    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.

  • (cs) in reply to kingmike

    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?

  • (cs) in reply to OutlawProgrammer
    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 (unregistered)

    The real WTF is actually the comments by some who does not understand pass by value/ref.

  • diodor (unregistered) in reply to frits
    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 (unregistered) in reply to Steve W
    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 (unregistered) in reply to Optical Aleutian
    Optical Aleutian:
    Anonymous:
    anonymous:
    I grow tired of this conversation. Summon the dancing girls!
    Alright! Let's dance!

    [image]

    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 (unregistered) in reply to Anonymous
    Anonymous:
    anonymous:
    I grow tired of this conversation. Summon the dancing girls!
    Alright! Let's rotate our favourite barbie dolls over a mirror!

    [image]

    FTFY

  • Kempeth (unregistered)

    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 (unregistered)

    you are not alone in this universe brother

  • Anonymous coward (unregistered)

    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 (unregistered) in reply to DaveK
    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 (unregistered) in reply to Bonghit
    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 (unregistered) in reply to Anonymous coward
    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 (unregistered) in reply to Optical Aleutian
    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.
  • (cs) in reply to diodor
    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.

  • (cs) in reply to Welcor
    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 (unregistered)

    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 (unregistered)

    TRWTF is that this little piece of code has created 3 pages of comments.

  • (cs) in reply to tiller
    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 (unregistered) in reply to Jaime
    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 (unregistered)

    TRWTF is not calling 'finalize()'...

  • (cs) in reply to Anonymous coward
    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 (unregistered) in reply to frits
    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 (unregistered) in reply to frits
    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).
  • (cs) in reply to pcooper
    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 (unregistered)

    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 (unregistered)

    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 (unregistered) in reply to OMGWTFJON

    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 (unregistered) in reply to newfweiler
    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.

  • (cs) in reply to dkf
    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 (unregistered) in reply to yummy
    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.

  • (cs) in reply to Steve W
    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 (unregistered)

    "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 (unregistered) in reply to OutlawProgrammer
    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 (unregistered) in reply to 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.

  • John (unregistered) in reply to Alastriona
    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 (unregistered) in reply to OutlawProgrammer
    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 (unregistered) in reply to Welcor
    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 (unregistered) in reply to Lunkwill

    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 (unregistered)

    TRWTF is that I can't work out who is trolling and who isn't.

  • (cs) in reply to Welcor

    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 (unregistered) in reply to javacoder

    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 (unregistered)

    I think this must've been written by one of my ex-colleagues; jeez!!!

  • yummy (unregistered) in reply to frits
    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.

  • (cs) in reply to Alastriona
    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 (unregistered)

    Wierdest reference leak ever.

  • LookingforSxxx (unregistered)

    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 (unregistered) in reply to javacoder
    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
  • (cs) in reply to Anonymous
    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.

Leave a comment on “Java Destruction”

Log In or post as a guest

Replying to comment #:

« Return to Article