Should i set null those reference variable object created inside of funtion

hi,
I create object inside of a member function . after finish execute that method those variable should set null to be garbage collection or no need ?
   public void sampleFun(){
       Object obj = new Object();
        // some work
     obj = null ;  //// ----------- > this need or not ?
}after finished that method execution should i set
   obj = null;explicitly or no need ?? plz

No, there's no need.
When the reference variable passes out of scope, it ceases to exist, so it doesn't reference the object any more. As soon as an object has no references pointing to it, it is available for garbage collection.
Your rule of thumb should be: don't do anything about garbage collection unless you know why you're doing it. And even then don't do it unless you can prove you need to.
Dave.

Similar Messages

  • Garbage collection of objects created inside a method

    I have method and inside the method I create new Objects I mean I instantiate objects using new and call some methods on these objects.
    once the method execution is completed and control goes to caller of the method will all the object created inside the method will be garbage collected ?
    here with code
               public List<StgAuditGeneral> getAudits(
              List<StgAuditGeneral>  audits= new ArrayList<StgAuditGeneral>();
                  for(Map<String, String> result :results ){
                   audits.add(new MapToObject<StgAuditGeneral>() {
                        @Override
                        public StgAuditGeneral getObject() {
                                             StgAuditGeneral  stg= new StgAuditGeneral();
                             return stg;
                   }.getObject());
              }in the above method I cam creating tons of objects wil they be garbage collected immediatedly after jvm leaves the method ?

    user11138293 wrote:
    I have method and inside the method I create new Objects I mean I instantiate objects using new and call some methods on these objects.
    once the method execution is completed and control goes to caller of the method will all the object created inside the method will be garbage collected ?If there are no reachable references, to those objects, then when the method ends, they become eligible for GC. If and when they are actually collected is something we can't know or control, and generally don't care about. The only guarantee is that everything that can be collected will be collected before an OutOfMemoryError is thrown. So from our perspective, once it's eligible for collection, it is effectively collected.
    If you pass references to those objects to something else that holds onto them after the method ends, then they are still reachable, and not eligible for collection.
    However, you almost never need to even think about whether something is eligible for GC or not. It works pretty intuitively.

  • Which sw comp. should be set 'modifiable' (SE03) to edit objects in SOLAR01

    Hi,
    our SM7.1 is globaly set to modifiable but the Software Components and Namespaces in detail are set to 'not modifiable in SE03
    When we try to upload Documents in SOLAR01, we get the error 'System setting does not allow changes to be made to object SHI3 XXXXXXXXXX'
    Which component must be set to modifiable in SE03 to edit objects in SOLAR01 ?
    best regards
    Christoph

    Hi sunny,
    thank you very much....
    It helps
    best regards
    Christoph

  • Obtaining a reference to an object created in another page

    Hello, In my webapp, i have a controller servlet which delegates the task to appropriate handler classes. My handler class performs the database access, then packages the result set object into a vector. I then create a new object of a javabean with a setPost() method which houses the output. My question is after this is done i forward control to the appropriate jsp for display. But how can i reference the object created in the page before. Will the request.setAttribute() method work for passing the reference to the object, to that jsp page? In other words i just want to access an object created in a different sevlet. Any help would be much appreciated
    thanks
    Gabriel

    Hi
    Yes, if you set the attribute, in this case the Java Bean in the request, it will be available in the JSP to where the request has been forwarded. Note however that the Object's lifetime is limited by that of the request. For Objects which need longer lifetimes you could place them either in the session or the ServletContext. The latter case will give the Object application wide scope and also a lifetime limited only by the lifetime of the application.
    Good Luck!
    Eshwar Rao
    Developer Technical Support
    Sun microsystems inc
    http://www.sun.com/developers/support

  • Difference between reference variable and object ?

    I am getting confused with reference variable and object ?
    1. int a; // is a variable
    2. Car c = new Car(); // is a object of car type
    Suggest me what are the difference between the two.....

    jverd wrote:
    Shelby wrote:
    Something about an interned string literal?_
    I remember something from class about the way Java treats strings that contain the same data. yawmark
    posted a link for me that cleared up my confusion. thanks yawmark.
    >>
    Can you actually point back to the original reference?Not clear what you're asking here. Nothing points to references. References point to objects.
    Goodness, correct wording is as important as getting the syntax right, isn't it? ;-} What I was trying to ask is if it is possible to point back to the same String once you change the pointer on the variable?
    And you answered my question succintly with the rest of your post. thanks jverd
    >
    String str = "abc";
    str = null;'At this point, we've lost the reference to the original String object. However, at runtime, the VM will still be maintaining it in the constant pool. For any non-constant-pooled object, as we're writing our code, we'd have no way to refer to that object again. In this case, we are able to refer to the same object later in our code by simply using the same string literal. "abc" elsewhere in our code will cause the VM to give us a reference to that same pooled String. Same goes for Integer, etc. in the range -128..127.
    However, it's not good design to rely on this. If your design requires you to later point to "the same object" (as opposed to any object of a compatible type and holding the same contents), then you should explicitly maintain a reference to it. In the case of Strings, you really shouldn't care whether it's the same object or not. All you care about is the character sequence that defines the String's state.

  • What is the use of setting null values to Objects?

    What is the use of setting null values to Objects?
    regards,
    namanc

    It's more of a safety trap within java to handle the "programmers are still humans" exception.
    String myname;
    // print what???? Forgot to initialize the name!
    System.out.println(myname);Java will complain about myname not being initialized. It won't when you do this:
    String myname = null;
    // allright, your name is null
    System.out.println(myname);In the second case you are showing to java that you know what you are doing.

  • Is down casting possible in Java objects(reference variables)?

    I hope, Java up casting and down casting is possible in Java primitive variables like int float and so on.
    My doubt is,Does in object of Java(reference variables) support down casting?

    makpandian wrote:
    the ques i asked here is popped from my mind.We know that.
    But i did not get answer .Because you didn't do any research.
    Than s why i ask this here..That's the wrong approach. Do some research first. Use google, a textbook, a tutorial, the JLS, write some code, etc. etc.
    After spending time and effort doing that, if you still have questions, indicate clearly what you read and what part you didn't understand. The way you're doing it is NOT an effective way to learn, and it's a waste of everyone's time.

  • Why Java provides Object cloning even if there is Object reference variable

    In both cases original value get changed. What is the difference between these (clonable interface & Object reference variable)

    Cloneable is a way to make a copy of an object, so that you now have two objects, usually with the same state. Assigning the value in one reference variable to another variable (I can only assume that's what you're talking about, as your question is not clear at all) does not create another object.

  • How to create a local object reference variable in teststand sequence file programatically using C#

    I want to create a local object reference variable in a TestStand sequence file programatically using C#.

    Hi,
    Accoring to your reply in this Thread
    http://forums.ni.com/ni/board/message?board.id=330&thread.id=26984
    Just try this example. There you will create a numeric variable during excuting a sequence!
    Hope this is what you are looking for. 
    Please attach all your questions here.
    juergen
    =s=i=g=n=a=t=u=r=e= Click on the Star and see what happens :-) =s=i=g=n=a=t=u=r=e=
    Attachments:
    CTestStandDialog.zip ‏31 KB

  • Find out references to objects (garbage collection)

    Is there an easy way to find out, which references prevent the garbage collector from collecting my old objects, which I expect should be collected? Something like System.out.println(...)

    if you just want an object to be garbage collected, just
    make sure you de-reference is completely.CMueller obviously doesn't know which references prevent garbage collection so naturally he cannot set those references to null, now can he?
    o = null; // sets the value to null and drops all the referencesThat is simply not true. Removing a reference to an object doesn't affect any other references to that object.
      Object o1,o2;
      //create an object and make o1 reference it
      o1=new Object();
      //make o2 reference the same object as o1 references
      o2=o1;
      //now there are two references to the object
      //make o1 reference null
      o1=null;
      //at this point there is still one reference (o2) to
      //the object and therefore the object is NOT garbage
      //which means that it can NOT be collected by the GC- Marcus Sundman

  • Not able to Pass Reference Variables to Deferred task

    Hi All,
    I am not able to Pass the reference variables to Deferred task, With the following code, I am getting null values (for the passed refs) in Deferred Task.
    Code is as:
    <Action id='1' name='Set Deferred Task Action' application='com.waveset.session.WorkflowServices'>
    <Argument name='op' value='addDeferredTask'/>
    <Argument name='type' value='User'/>
    <Argument name='name' value='$(empId)'/>
    <Argument name='authorized' value='true'/>
    <Argument name='task' value='WF_User Deferred Task'/> // Task defination
    <Argument name='date'>
    <Date>2008-11-19T14:50:18.840Z</Date>
    </Argument>
    <Argument name='taskDefinition'>
    <block trace='true'>
    <defvar name='usrObject'> // This is the variable I am passing to 'WF_User Deferred Task'
    <new class='com.waveset.object.GenericObject'/>
    </defvar>
    <invoke name='setAttributes'>
    <ref>usrObject</ref>
    <map>
    <s>accId</s>
    <ref>empId</ref>
    <s>updStatus</s>
    <ref>newStatus</ref>
    </map>
    </invoke>
    </block>
    </Argument>
    </Action>
    <Transition to='End'/>
    Please suggest me.
    Thanks,
    Ravi.

    yeah, you don't have your usrObject available in the deffered task however all variables that you put inside the usrObject are avialble. Like <ref>accId<ref> and <ref>updStatus</ref>. If you still need them organized hierarchically, you might try to add one more level to the object before passing it to addDefferedTask
                <block>
                  <defvar name='objWrapper'>
                    <new class='com.waveset.object.GenericObject'/>
                  </defvar>
                  <defvar name='usrObject'>
                    <new class='com.waveset.object.GenericObject'/>
                  </defvar>
                  <invoke name='setAttributes'>
                    <ref>usrObject</ref>
                    <map>
                      <s>accId</s>
                      <s>yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy</s>
                      <s>updStatus</s>
                      <s>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</s>
                    </map>
                  </invoke>
                  <invoke name='setAttributes'>
                    <ref>objWrapper</ref>
                    <map>
                      <s>usrObject</s>
                      <ref>usrObject</ref>
                    </map>
                  </invoke>
                  <ref>objWrapper</ref>
                </block>I hope you ve got the idea. Cheerz.

  • Persistant Status Bar Notification ... error 'SP.UI.Status' is null or not an object

    I want to show a status bar that needs to be persistent on a page. for this I used the following in my master page
    function ShowStatusBarMessage(title, message)
    var statusId = SP.UI.Status.addStatus(title, message, true);
    SP.UI.Status.setStatusPriColor(statusId, 'yellow'); /* Set a status-color */
    HTML, call the JS method:
    <a onclick="ShowStatusBarMessage('Title'!','Awesome message!')">
    Display Status Bar message!
    </a>
    ref:
    http://www.zimmergren.net/archive/2010/03/17/sp-2010-dynamically-displaying-messages-to-your-users-with-the-notification-and-status-bar-areas-in-sharepoint-2010.aspx
    But what I want is
    to call the function on load. So I used pushed ny function to _spBodyOnLoadWrapper using _spBodyOnLoadFunctionNames.push("YourFunctionName");,
    it throws an error 'SP.UI.Status' is null or not an object
    Next I created and
    deployed a webcontrol and did a registerclientscript, that too gives me 'SP.UI.Status' is null or not an object
    // Define the name and type of the client scripts on the page.
    String csname1 = "AlertScript";
    Type cstype = this.GetType();
    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;
    // Check to see if the startup script is already registered.
    if (!cs.IsStartupScriptRegistered(cstype, csname1))
    StringBuilder cstext1 = new StringBuilder();
    cstext1.Append("<script type=text/javascript> alert('Hello World!');");
    cstext1.Append("var statusId = SP.UI.Status.addStatus('title', 'message', true);");
    cstext1.Append("SP.UI.Status.setStatusPriColor(statusId, 'yellow'); </");
    cstext1.Append("script>");
    cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
    What am I missing ?
    How can I get to show a status bar on load of any page, just as you get a health analyzer message when you get into the Central Admin?
    Thanks, Mano
    Mano Mangaldas | Blog : http://howtosharepoint.blogspot.com 

    Ok, for some reason, it is not working for me. Below are the code that didnt work for me
    <script type="text/javascript">
    function ShowStatusBarMessage(title, message)
    var statusId = SP.UI.Status.addStatus(title, message, true);
    SP.UI.Status.setStatusPriColor(statusId, 'red');
    ShowStatusBarMessage('Title!','Awesome message!');
    </script>
    This too didnt work
    <script type="text/javascript">
    function ShowStatusBarMessage()
    var statusId = SP.UI.Status.addStatus('Some title', 'Some message', true);
    SP.UI.Status.setStatusPriColor(statusId, 'red');
    _spBodyOnLoadFunctionNames.push("ShowStatusBarMessage");
    </script>
    I did try to register client script block programatically, that too didnt work
    String csname1 = "AlertScript";
    Type cstype = this.GetType();
    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;
    // Check to see if the startup script is already registered.
    if (!cs.IsStartupScriptRegistered(cstype, csname1))
    StringBuilder cstext1 = new StringBuilder();
    cstext1.Append("<script type=text/javascript>");
    cstext1.Append("var statusId = SP.UI.Status.addStatus('title', 'message', true);");
    cstext1.Append("SP.UI.Status.setStatusPriColor(statusId, 'yellow'); </");
    cstext1.Append("script>");
    cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
    Any help appreciated.
    But the below code works..
    <script type="text/javascript">
    function ShowStatusBarMessage(title, message)
    var statusId = SP.UI.Status.addStatus(title, message, true);
    SP.UI.Status.setStatusPriColor(statusId, 'yellow'); /* Set a status-color */
    </script>
    <a onclick="ShowStatusBarMessage('Title!','Awesome message!')" href="#">
    Display Status Bar message!
    </a>
    Thanks
    mano
    Mano Mangaldas | Blog : http://howtosharepoint.blogspot.com 

  • FABridge.flash.root() is null or not an object

    Hello everyone! I'm having a problem with Flex-Ajay Bridge in
    an aspx page. Days ago I could access flex variables from
    javascript without problems, but now I can´t. This is my flex
    code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    xmlns="*" layout="absolute" height="194" width="374"
    creationComplete="init()">
    <fab:FABridge xmlns:fab="bridge.*" bridgeName="flash"
    id="flash"/>
    <mx:Script>
    <![CDATA[
    import mx.controls.Alert;
    public function init():void
    mx.controls.Alert.show("ready");
    ]]>
    </mx:Script>
    <mx:Label x="227" y="171" text="Probemos......"
    fontSize="14"/>
    <mx:TextInput x="140" y="27" id="pki"/>
    <mx:TextInput x="140" y="76" id="pkf"/>
    <mx:TextInput x="140" y="122" id="nc"/>
    <mx:Label x="27" y="29" text="PKI" fontSize="14"/>
    <mx:Label x="27" y="78" text="PKF" fontSize="14"/>
    <mx:Label x="27" y="123" text="Max. Carriles"
    fontSize="14"/>
    </mx:Application>
    It's just some text boxes and labels. I want to access those
    labels from javascript, so I wrote in my html page this:
    <html xmlns="
    http://www.w3.org/1999/xhtml"
    >
    <head runat="server">
    <title>Inventario de Carriles con Flex</title>
    <script
    src="JS/FABridge.js"type="text/javascript"></script>
    <script type="text/javascript" language="javascript">
    function setMessage()
    var flexApp = FABridge.flash.root();
    alert("1");
    alert("2");
    flexApp.pki().setText("1");
    flexApp.pkf().setText("2");
    flexApp.nc().setText("3");
    </script>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <table>
    <tr>
    <td>
    <object
    classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="374"
    height="194" >
    <param name="movie" value="FlexApp\Inventario.swf"/>
    <param name="quality" value="high"/> <
    <embed src="FlexApp\Inventario.swf" width="374"
    height="194" align="middle" quality="high" pluginspage="
    http://www.macromedia.com/go/getflashplayer"
    type="application/x-shockwave-flash"></embed>
    </object>
    </td> (...............)
    When I click in the button, the js fuction starts executing
    but when it tries to initialize the flexApp variable it shows an
    error: flexApp.flash.root() is null or not an object.......... can
    you please help me? I tried everything and didn't manage to solve
    this problem, I know that the flex .swf is initialized but I don't
    know why the javascript can't access it :(
    Does someone knows what can I do in order to solve this???
    Thanks!!!
    Regards,
    Mariana

    Hi,
    javascript isn't made by sun, so you won't find it here, but google can help you out:
    http://www.google.se/search?hl=sv&ie=UTF-8&q=javascript+forum&btnG=S%C3%B6k&meta=
    /Kaj

  • Is it possible in java to pass reference of object in Java?

    Hello,
    I'm relativily new to Java but I have "solid" knowledge in C+ and C# .NET+.
    Is it possible in java to pass reference of object in Java? I read some articles about weakreferences, softreferences, etc. but it seems that it's not what I'm looking for.
    Here is a little piece of code I wrote:
    package Software;
    import java.util.Random;
    * @author Rodrigue
    public class RandomText
        private Random rand = new Random();
        private Thread t;
        private String rText = "Rodrigue";
        public RandomText()
            t = new Thread()
                @Override
                public void run()
                    try
                        while(true)
                            UpdateText();
                            sleep(100);
                    catch(InterruptedException ex)
            t.start();
        private void UpdateText()
            int i = rand.nextInt();
            synchronized (rText)
                rText = String.valueOf(i);
        public String GetText()
            return rText;
    }It's just a class which start a thread. This class updates a text with a random integer 10 times per second.
    I would like to get a reference on the String rText (like in C++ ;) yes I know, I must think in Java :D). So, like that, I could get one time the reference, thanks to the GetText function, and update the text when my application will repaint. Otherwise, I always have to call the GetText method ... which is slow, no?
    Are objects passed by reference in java? Or, my string is duplicated each time?
    Thank you very much in advance!
    Rodrigue

    disturbedRod wrote:
    Ok, "Everything in Java is passed by value. Objects, however, are never passed at all.". Reference of object is passed by value too.
    But, how to solve my problem in Java_? I have an object which is continually modified in a thread. From an another side, this object is continually repainted in a form.I'm not sure I totally understand your problem. If you pass a reference to an object, then both the caller and the method point to the same object. Changing the internal state of the object (e.g. by calling a setter method) through one reference will be observed through both references, since they both point to the same object.
    No, calling a method is not particularly slow. Especially if it's just a simple getter method that returns the value of a member variable.
    If this is happening in a multithreaded context, you'll have to use proper synchronization to ensure that each thread sees the others' changes.

  • Loosing references to objects

    I am accessing Lite using Java using the JAC API's: POLConnection, POLClass etc.
    The program is temporarily and eratically loosing references to objects and then find them again.
    The program logs on and looks up the objects it needs, checking the refernces have been found and are not null. A button initiates a query to uses these objects to retrieve data. It eratically raise a null pointer exception, the connection or class reference is null. By pressing the button again the query works ok, even though the connection and class objects have not been reset, they are suddenly no longer null.
    Help.

    May I be so bold to make a suggestion here?
    In future questions like this should be posted in a more appropriate forum. Like here http://forum.java.sun.com/forum.jspa?forumID=37
    This could be of more help to you because there are in fact users like this guy http://forum.java.sun.com/profile.jspa?userID=658641 who actually work for Sun on the VM and answer questions in there.
    So you could get a real answer rather than a bunch of guessing or idiotic contributions from Questie and the like.

Maybe you are looking for