Return local object from function

Discussion in 'Java' started by Sean Hsien, Jul 18, 2006.

  1. Sean Hsien

    Sean Hsien Guest

    Hi all,

    I'm a newbie in Java. Was wondering what is the behaviour for the code
    below:

    myType obj = foo();

    where the function foo() is defined below:

    myType foo()
    {
    myType a = new myType();
    ...
    return a;
    }

    What happens? Below are 3 alternatives that i can think of so far:
    1. assignment be unsuccessful as the local object goes out of scope
    once foo() ends
    2. assignment is successful (copy ctor) before local object is cleaned
    up from memory
    3. assignment is successful and "obj" now points to same memory
    location as "a"

    Thanks and much appreciated.

    Sean
     
    Sean Hsien, Jul 18, 2006
    #1
    1. Advertising

  2. Sean Hsien

    Stefan Ram Guest

    "Sean Hsien" <> writes:
    >1. assignment be unsuccessful as the local object goes out of
    >scope once foo() ends


    Identifiers have scope, objects do not have scope.

    >2. assignment is successful (copy ctor) before local object is
    >cleaned up from memory


    In Java, there is no »copy ctor«.

    >3. assignment is successful and "obj" now points to same memory
    >location as "a"


    Yes.
     
    Stefan Ram, Jul 18, 2006
    #2
    1. Advertising

  3. Sean Hsien

    Mark Space Guest

    Stefan Ram wrote:
    > "Sean Hsien" <> writes:
    >> 1. assignment be unsuccessful as the local object goes out of
    >> scope once foo() ends

    >
    > Identifiers have scope, objects do not have scope.


    Just to add a bit more, recall that a local variable is allocated like this:

    int methodName( int argument )
    {
    String s = new String();

    That is, you must use "new." There's no way to put an object on the
    stack. Primitives, yes (int, boolean, references, etc.), but not
    objects. So you're guaranteed that any object is still on the heap when
    a function exits.

    >
    >> 2. assignment is successful (copy ctor) before local object is
    >> cleaned up from memory

    >
    > In Java, there is no »copy ctor«.


    Thank God.

    >
    >> 3. assignment is successful and "obj" now points to same memory
    >> location as "a"

    >
    > Yes.


    It pretty much works like this in C:

    int funcName( int argument )
    {
    char* s = calloc( 15, sizeof (char) );

    except that s is reference counted and you don't have to worry about
    free()ing it later. Isn't Java nice? I has the smart bits from C with
    out the icky stuff.
     
    Mark Space, Jul 18, 2006
    #3
  4. Some simple rules:

    * C++ pointers are called "references" in Java. There is nothing in Java
    like a C++ reference.
    * Local variables in Java are either scalars or references to objects
    * There are no global variables. Static fields of Java classes are similar
    to C++ globals, but they're explicitly allocated when the class is loaded,
    not when the program starts up.
    * Objects themselves are always dynamically allocated. .Thus, objects never
    go out of scope.
    * There is no such thing as explicit dealocation in Java (i.e.no delete
    operator).
    * Scalars and references are never dynamically allocated.
    * Objects are made up of scalars and pointers. Unlike in C++, one object
    never contains another.
     
    Mike Schilling, Jul 18, 2006
    #4
  5. Sean Hsien

    Oliver Wong Guest

    "Mark Space" <> wrote in message
    news:pv_ug.69308$...
    > Stefan Ram wrote:
    >> "Sean Hsien" <> writes:
    >>> 1. assignment be unsuccessful as the local object goes out of
    >>> scope once foo() ends

    [ No. ]
    >
    > Just to add a bit more, recall that a local variable is allocated like
    > this:
    >
    > int methodName( int argument )
    > {
    > String s = new String();
    >
    > That is, you must use "new." There's no way to put an object on the
    > stack. Primitives, yes (int, boolean, references, etc.), but not objects.
    > So you're guaranteed that any object is still on the heap when a function
    > exits.


    Some modern JVMs "intelligently" decided when to put an object on the
    stack or heap for you, depending on what it predicts the code will do next.
    The simplest way to express the rule is "Don't worry about objects
    disappearing while you're still using them". It'll never happen, unless you
    start doing fancy stuff with the WeakReference or SoftReference classes.

    [...]
    >>
    >>> 3. assignment is successful and "obj" now points to same memory
    >>> location as "a"

    >>
    >> Yes.

    >
    > It pretty much works like this in C:
    >
    > int funcName( int argument )
    > {
    > char* s = calloc( 15, sizeof (char) );
    >
    > except that s is reference counted and you don't have to worry about
    > free()ing it later. Isn't Java nice? I has the smart bits from C with
    > out the icky stuff.


    It doesn't nescessarily use reference counting. How the JVM does garbage
    collection is implementation specific. So don't worry about stuff like
    "Reference counting? Oh no! That means I have to avoid cyclic references!"
    No, don't worry about that. Everything "just works" behind the scenes.

    - Oliver
     
    Oliver Wong, Jul 18, 2006
    #5
  6. Sean Hsien

    Mark Space Guest

    Oliver Wong wrote:
    >
    > Some modern JVMs "intelligently" decided when to put an object on the
    > stack or heap for you, depending on what it predicts the code will do
    > next. The simplest way to express the rule is "Don't worry about objects
    > disappearing while you're still using them". It'll never happen, unless
    > you start doing fancy stuff with the WeakReference or SoftReference
    > classes.


    Right, good point. I'd read that in a discussion about Java garbage
    collection and optimization, and I forgot about it. Conceptually, all
    objects go on the heap. Really, there may be optimization when
    possible, and small, local objects might be allocated somewhere besides
    the heap.

    >
    > It doesn't nescessarily use reference counting. How the JVM does
    > garbage collection is implementation specific. So don't worry about
    > stuff like "Reference counting? Oh no! That means I have to avoid cyclic
    > references!" No, don't worry about that. Everything "just works" behind
    > the scenes.


    Also a good point. I think checking out info about Java garbage
    collection would be a good idea. I remember reading about this, and
    also the claim that modern garbage collectors where also faster than
    most C++ de-allocation schemes, due to batching and performance analysis
    at runtime.

    But conceptually, it's like reference counting, in that objects go away
    when the last reference to them disappears.
     
    Mark Space, Jul 18, 2006
    #6
  7. Sean Hsien

    Mark Space Guest

    Mike Schilling wrote:
    > Some simple rules:
    >
    > * C++ pointers are called "references" in Java.


    Is this really true? I thought that Java references were 64 bits (8
    bytes) on 32 bit systems, meaning that Java references are twice as big
    as a pointer and there's therefore more going on in there than a simple
    pointer.

    Does anyone know what common JVM implementations stuff in a reference
    besides just a pointer?

    > There is nothing in Java
    > like a C++ reference.


    Well, I think references in Java are a lot like references in C++. :)
    Java doesn't have the same operations on a reference that C++ does, but
    the actual reference itself is similar and fulfills a similar purpose.


    > * There is no such thing as explicit dealocation in Java (i.e.no delete
    > operator).


    I think you can force garbage collection in Java. Or fine tune it.


    > * Objects are made up of scalars and pointers. Unlike in C++, one object
    > never contains another.


    Well, conceptually the reference is the object. References in Java can
    be used for aggregation. But literally yes, Java doesn't make objects
    contiguous in memory within another object.


    Just my 2 bucks. I don't mind being wrong, sometimes I even learn
    something.
     
    Mark Space, Jul 18, 2006
    #7
  8. Sean Hsien

    Oliver Wong Guest

    "Mark Space" <> wrote in message
    news:swavg.132075$...
    > Mike Schilling wrote:


    >> * There is no such thing as explicit dealocation in Java (i.e.no delete
    >> operator).

    >
    > I think you can force garbage collection in Java. Or fine tune it.


    You can ask for garbage collection by calling System.gc(), but it's a
    legal implementation for the JVM to ignore the request.

    Some JVMs accept command line arguments so that you can select between
    different flavours of garbage collectors.

    - Oliver
     
    Oliver Wong, Jul 18, 2006
    #8
  9. "Mark Space" <> wrote in message
    news:swavg.132075$...
    > Mike Schilling wrote:
    >> Some simple rules:
    >>
    >> * C++ pointers are called "references" in Java.

    >
    > Is this really true? I thought that Java references were 64 bits (8
    > bytes) on 32 bit systems, meaning that Java references are twice as big as
    > a pointer and there's therefore more going on in there than a simple
    > pointer.


    There's no guarantee of the size of a pointer in either Java of C++.
    Anyway, I'm talking about how they're used, not how they're implemented. If
    you're a C++ programmer learning Java, you're better off thinking of them as
    pointers.

    >
    >> There is nothing in Java like a C++ reference.

    >
    > Well, I think references in Java are a lot like references in C++. :)
    > Java doesn't have the same operations on a reference that C++ does, but
    > the actual reference itself is similar and fulfills a similar purpose.


    The main thing that distnguishes a C++ reference from a C++ pointer is that
    the reference can't be reset: it points to the same object for its entire
    lifetime. This is not true of Java references. Likewise, Java references
    can be null, while C++ references cannot.

    Note that the exception that occurs when trying to dereference a Java
    reference is a NullPointerException; they pretty clearly got renamed to
    "reference" at some point.

    >
    >
    >> * There is no such thing as explicit dealocation in Java (i.e.no delete
    >> operator).

    >
    > I think you can force garbage collection in Java. Or fine tune it.


    You can give the GC hints, with no guarantee they'll have any effect.
    Unlike in C++, you cannot say "Tear down this specific object, now, and free
    its memory." That's why, where it's very common to put cleanup logic in C++
    destructors, it's uncommon to put similar logic in Java finalizers: because
    there's no guarantee when (or whether) the finalizers will run.

    >
    >
    >> * Objects are made up of scalars and pointers. Unlike in C++, one object
    >> never contains another.

    >
    > Well, conceptually the reference is the object. References in Java can be
    > used for aggregation. But literally yes, Java doesn't make objects
    > contiguous in memory within another object.


    Well, it might In Java, you don't really know anything about how things
    are laid out in memory :)

    In C++, when object B is contained inside A, their lifetimes are connected.
    B is constructed as part of A's construction, and the same with destruction.
    B cannnot be deleted except as a side-effect of deleting A. In Java, A can
    point to B, but if something else points to B as well, B can outlive A.

    That is C++ can both aggregate objects directly and make trees of objects
    with pointers (or references). Java only has trees.
     
    Mike Schilling, Jul 18, 2006
    #9
  10. Mark Space wrote:
    > Oliver Wong wrote:
    >>
    >> Some modern JVMs "intelligently" decided when to put an object on
    >> the stack or heap for you, depending on what it predicts the code will
    >> do next. The simplest way to express the rule is "Don't worry about
    >> objects disappearing while you're still using them". It'll never
    >> happen, unless you start doing fancy stuff with the WeakReference or
    >> SoftReference classes.

    >
    > Right, good point. I'd read that in a discussion about Java garbage
    > collection and optimization, and I forgot about it. Conceptually, all
    > objects go on the heap. Really, there may be optimization when
    > possible, and small, local objects might be allocated somewhere besides
    > the heap.
    >
    >>
    >> It doesn't nescessarily use reference counting. How the JVM does
    >> garbage collection is implementation specific. So don't worry about
    >> stuff like "Reference counting? Oh no! That means I have to avoid
    >> cyclic references!" No, don't worry about that. Everything "just
    >> works" behind the scenes.

    >
    > Also a good point. I think checking out info about Java garbage
    > collection would be a good idea. I remember reading about this, and
    > also the claim that modern garbage collectors where also faster than
    > most C++ de-allocation schemes, due to batching and performance analysis
    > at runtime.
    >
    > But conceptually, it's like reference counting, in that objects go away
    > when the last reference to them disappears.
    >


    An object can go away while there are still references to it, as long as
    it cannot "be accessed in any potential continuing computation from any
    live thread"

    The distinction really does matter. Suppose objects x and y each have a
    reference to the other, and that is the only reference to each of them.

    A system in which objects go away when the last reference to them
    disappears wound not be able collect either until the other has been
    collected.

    A Java implementation is allowed to note that both are unreachable, and
    collect them both.

    Patricia
     
    Patricia Shanahan, Jul 18, 2006
    #10
  11. Sean Hsien

    Mark Space Guest

    Patricia Shanahan wrote:
    > A Java implementation is allowed to note that both are unreachable, and
    > collect them both.


    Right. The aforementioned cyclic references. This had been mentioned,
    so I didn't touch on it.
     
    Mark Space, Jul 18, 2006
    #11
  12. Sean Hsien

    Chris Uppal Guest

    Mark Space wrote:

    > Is this really true? I thought that Java references were 64 bits (8
    > bytes) on 32 bit systems, meaning that Java references are twice as big
    > as a pointer and there's therefore more going on in there than a simple
    > pointer.


    Typical JVM implementations use raw pointers to implement Java's references --
    i.e. 32-bits on a 32-bit machine


    > Does anyone know what common JVM implementations stuff in a reference
    > besides just a pointer?


    Nowt.

    FWIW, I haven't heard of /any/ JVM implementation which uses tagged pointers --
    though I imagine that implementations which run on tagged hardware will do. In
    fact I haven't heard of software-only tagging used for any language
    implementation since Icon. Doesn't mean there aren't implementations I don't
    know about, though...

    -- chris
     
    Chris Uppal, Jul 19, 2006
    #12
  13. Sean Hsien

    Chris Uppal Guest

    Mark Space wrote:

    > Really, there may be optimization when
    > possible, and small, local objects might be allocated somewhere besides
    > the heap.


    AFAIK, that optimisation is not in the current Sun JVMs. There's a fair bit of
    talk about such optimisations appearing in forthcoming releases, but I don't
    know whether it's intended to make 1.6 -- nor how effective the implementation
    will be in practise.


    > Also a good point. I think checking out info about Java garbage
    > collection would be a good idea. I remember reading about this, and
    > also the claim that modern garbage collectors where also faster than
    > most C++ de-allocation schemes, due to batching and performance analysis
    > at runtime.


    It /ought/ to be faster -- for the simple reason that it gets used more, and so
    should be the target of more performance work. But I suspect that the big
    gains (if any, and rememberiing that there are losses too) is that the
    design-space is expanded to include reduced-overhead program designs which
    would be unmaintainable in C++.


    > But conceptually, it's like reference counting, in that objects go away
    > when the last reference to them disappears.


    That could be misleading if it gives the impression that finalisation (in its
    various flavours) will happen immediately or at a predictable time.

    -- chris
     
    Chris Uppal, Jul 19, 2006
    #13
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. David Thielen
    Replies:
    2
    Views:
    801
    Marek Lange
    Sep 12, 2003
  2. Greenhorn
    Replies:
    15
    Views:
    839
    Keith Thompson
    Mar 6, 2005
  3. Sullivan WxPyQtKinter
    Replies:
    10
    Views:
    677
    Antoon Pardon
    Nov 8, 2007
  4. George2
    Replies:
    5
    Views:
    556
    James Kanze
    Jan 25, 2008
  5. Mark
    Replies:
    7
    Views:
    1,327
    Keith Thompson
    Feb 4, 2011
Loading...

Share This Page