Revisited: static synchronized vs garbage collected

A forum thread (http://forum.java.sun.com/thread.jsp?forum=4&thread=466049&start=0&range=15&hilite=false&q=) from last November addressed issues involving the relative merits of using static methods vs. the garbage collection issues that might attend conventional object instantiation. The discussion extended into use of synchronized code and threading, but from it, I've failed to gather an understanding of a few subtleties.
I understand the dangers of using class-level variables within servlets, however, I'm still puzzled as to the thread-safety of 1) static class-level variables in servlets, and 2) using static methods residing in "utility" type classes from within servlets. I also realize these matters are not confined to servlets, but extend to any multi-threaded environment. I'm particularly unclear as to when, or if, the methods of the static class-level variable/objects need to be synchronized; with the same question applied to the static methods of the "utility" classes.
From the forum thread mentioned above, it would seem that synchronization is NOT needed since parameters and method-level variables are specific to the executing threads. I believe this essentially means that static methods should not rely on the state of their containing class (under most applications). In a situation where the method's code is not trivial or "lightweight" (e.g. database access), would not the overhead associated with the swapping in and out of thread-specific variables lead to performance issues?
My particular situation involves an ecommerce site running websphere. We are experiencing sporadic episodes where the VM starts running low on memory, will occasionally recover but will also occasionally crash. In pursuing this wild goose, my first suspicion was a thread deadlocking problem since it's not reliably reproducible. Most of the log entries point to a static method in one of these "utility" classes, yet I can find no non-static class level variables either in the utility or the servlet. However, none of these static methods are synchronized.
Sorry for the ramble, and thanks for any help.
Regards,
Joe

Because static variables, by their very nature, are only instantiated once, you MUST syncronise them to be safe in a multi threaded environment, otherwise you will get unexpected results.
As you rightly mention, servlets also optimise the instantiation of class level variables and effectively make them static as well, so they are shared amongst all instaniations of a servlet.

Similar Messages

  • Static class garbage collection

    Can garbage collector can garbage collect static classes ?.
    My doubt is that when you access a static class , that class is loaded through its class loader ( when first time that class is referenced ).
    So when did the garbage collector collects this static class ( assume that static class no longer referred ).
    Please do more information,
    What are the ways to prevent garbage collector for a particular class ( Assume that i m implementing a singleton for my java runtime)
    thanks and regards
    Renjith.

    Can garbage collector can garbage collect static classes ?. Static classes are nothing special in terms of class loading - they are only different in visibility for linking.
    Perhaps you mean static members of classes?
    My doubt is that when you access a static class ,
    that class is loaded through its class loader ( when
    first time that class is referenced ). Classes are always loaded through classloaders. Objects of those classes are allocated from the heap, and the object instances refer to the class object.
    Objects (either instances, or classes themselves) are garbage collected when they are no longer live (i.e. no live object refers to them). (This is a somewhat recursive definition, and sometimes, you can have cyclic dependencies that make garbage collection tricky, but the GC, while it has to be conservative for correctness, usually gets it right).
    So for a static member to be garbage-collected, the class has to be garbage-collected first. The class cannot be GC'ed until all references to it go away (this includes all dynamically allocated objects of that type, and the class loader that loaded that class).
    And yes, class loaders can go away, but only if they are created by your program. The system class loader (which is the default classloader you get if you don't create any class loaders of your own) never goes away, so any class loaded from CLASSPATH will never be unloaded.
    (As an example, servlet containers - e.g. Tomcat, Weblogic, etc.) allocate one or more classloaders for each webapp. When the webapp is un-deployed, the classloaders are "orphaned", and they, and any classes loaded by them (from the WEB-INF/lib and WEB-INF/classes directories) are unloaded and garbage-collected. (After all the dynamic objects of those classes are GC'ed, of course).
    >
    So when did the garbage collector collects this
    static class ( assume that static class no longer
    referred ).
    Please do more information,
    What are the ways to prevent garbage collector for a
    particular class ( Assume that i m implementing a
    singleton for my java runtime)
    thanks and regards
    Renjith.

  • How can I prevent class garbage collection????

    Hi,
    Is there a way to prevent a class from being garbage collected without using the -noclassgc option? Is there some code I can include in a class that tells the JVM not to garbage collect that particular class?
    Thanks in advance,
    Jacob.

    The code shown below (slightly modified from yours) should work correctly on any 1.0.x throught 1.4 JVM.
    Look at this article for further info: http://www.javaworld.com/javaworld/javatips/jw-javatip52.html
    public class SQLManager extends PoolManager {
        private static SQLManager myself;
        //code.........................
        public static SQLManager getInstance() {
            // This version of a getInstance method suffers from the use of the
            // broken (unreliable) double checked locking idiom.  It should never
            // be used on a system with more than one processor and is ill-advised
            // any other time.  It can  lead to accesses to uninitialized objects.
            // See http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html
            // or http://c2.com/cgi/wiki?DoubleCheckedLockingIsBroken
            // So despite its common appearance in books and pattern repositories,
            // it should not be used.
            if (myself == null) {
                synchronized(SQLManager.class) {
                    if (myself == null)
                        myself = new SQLManager();
            return myself;
        private SQLManager() {
            livethread();
            //code.........................
        void livethread()
            System.out.println("##############################################################");
            System.out.println("###################Live Thread called#########################");
            System.out.println("##############################################################");
            Thread thread = new Thread()
                public void run()
                    // added this code to ensure that run() actually is getting
                    // called
                    System.out.println("##############################################################");
                    System.out.println("#################### Thread Started ##########################");
                    System.out.println("##############################################################");
                    Class myClass = SQLManager.class;
                    while (true)
                        try
                            synchronized (myClass)
                                myClass.wait();
                        catch (InterruptedException ex)
                            System.out.println("##############################################################");
                            System.out.println("###################Thread interrupted#########################");
                            System.out.println("##############################################################");
                        finally
                            System.out.println("##############################################################");
                            System.out.println("################### Something Happened #########################");
                            System.out.println("##############################################################");
                    System.out.println("##############################################################");
                    System.out.println("#################### Thread Dead?? ##########################");
                    System.out.println("##############################################################");
            thread.setDaemon(true);
            System.out.println("##############################################################");
            System.out.println("#################### Starting Thread #########################");
            System.out.println("##############################################################");
            thread.start();
        //code.........................
    }

  • URL class is not being garbage collected

    I have created two instances of the URL class to specify a file location for each image. I use com.symantec.itools.javax.swing.icons.ImageIcon class to display images specified by each URL instance as icons inside a button. The setImageLocation method(URL location) of the ImageIcon class sets the location to be displayed by this icon. The following is the code snippets used to create the ImageIcon instances:
    private URL greenIconURL;
    private URL redIconURL;
    com.symantec.itools.javax.swing.icons.ImageIcon green_icon = new com.symantec.itools.javax.swing.icons.ImageIcon();
    com.symantec.itools.javax.swing.icons.ImageIcon red_icon = new com.symantec.itools.javax.swing.icons.ImageIcon();
    try
    greenIconURL = new java.net.URL
    ("file:./images/greenline.gif");
    green_icon.setImageLocation(greenIconURL);
    catch (java.net.MalformedURLException error) { }
    try
    redIconURL = new java.net.URL
    ("file:./images/redline.gif");
    red_icon.setImageLocation(redIconURL);
    catch (java.net.MalformedURLException error) { }
    I am using JProbe 5.0.1 Memory to determine the loitering objects when I remove the button from the JInternalFrame. I am using Java 1.2.2_08 version. The JProbe Memory Leak Doctor indicates that each URL instance has a reference to an entry in a HashMap table. The reference graph from the root set has a reference to SoftCache to HashMap to HashMap$Entry. To make this URL instance eligible for garbage collection, JProbe Memory Leak Doctor indicates I must remove the entry from the HashMap. How do I get access to this HashMap to remove the entry? If this is a problem with the version of the JDK, please let me know. Thank you in advance for your assistance.

    <root>Statics
    -->sun.misc.SoftCache->java.util.HashMap->java.util.Has
    Map$Entry[]->java.util.HashMap$Entry->java.net.URL
    I do not an instance of HashMap in my class.
    Therefore, the HashMap is either created by URLclass
    or the
    com.symantec.itools.javax.swing.icons.ImageIcon
    class.SoftCache seems to have a normal HashMap inside
    it/* Hash table mapping keys to ValueCells */
    private Map hash;but if that is the HashMap in JProbe
    information then the URL would have to be a key in
    the map - otherwise there'd be another object in the
    chain of class SoftCache.ValueCell
    are you certain that the java.net.URL's in that
    hashmap are your ones?
    out of curiosity - are you certain that the URL's are
    the/a problem (are you getting an OutOfMemoryError?)
    asjfThe button that contains the URL's is the only one on the JInternalFrame. The JProbe Memory Debugger displays the java.net package name, the URL class name, the count (2), and the Count Change (+2). When I remove the button from the JInternalFrame, the aforementioned numbers on the Instance Summary remain the same. The snapshot of the Java Heap reveals that the two instances of the URL class are still there. The Memory Leak Doctor shows the reference graph from the root set:
    <root>Statics->SoftCache->HashMap->HashMap$Entry[]->HashMap$Entry->URL
    When I right click on the arrow between HashMap$Entry[] and HashMap$Entry to remove the reference, I receive the message: "Congratulations this object can be garbage collected..." It appears like private instance of Map in SoftCache is holding a strong reference.
    I am not getting an OutOfMemoryError exception.

  • Do you think JOptionPane dialogs force garbage collection afterwards?

    I ask because I've made a nested static class to implement my own file selection tool; the problem is that each time I call it the old JPanel is being recalled and so the components get re-added to it each time it's called, resulting in n versions of each file for every n times you open it.
    I'm running myDialog.dispose() upon exiting, so is my only option now manual garbage collection? How could I force it to be garbage collected? Because System.gc() seems to have no effect.

    Strictly speaking there is no way to force garbage collection, so, no, JOptionPane will not be doing it.
    You almost certainly have a leak in your code. Post it and we may be able to help.

  • Preventing garbage-collection of a RMIRegistered server object

    I am developping a client/server RMI application, and keep facing occasional ObjectNotFioundException: no such object in table, when the client tries to invoke method on the server stub retrived from the RMIRegistry.
    The Javadoc and online documentation say this means the server object has been GC'ed since it has been registered in the RMIRegistry.
    Following the advice found at: http://www.nabble.com/java.rmi.NoSuchObjectException:-no-such-object-in-table-t260095.html,
    I register the server in a RMIRegistry I obtain through LocateRegistry.getRegistry(), and not createRegistry().
    But I still face these exceptions.
    Assuming the issue is really due to the server object being garbage-collected, I tried to keep a static reference to the server but it didn't help (the Main class was probably garbage-collected itself).
    As a last hope, I've set up a "keep-alive" thread in the server VM, that keeps a direct reference to the server object (not the stub), and regularly invokes something on it. With this mechanism I never face the exception.
    This solution looks obviously clumsy.
    Is there a neater way to prevent garbage collection of the server object?
    Note that I use dynamic stubs (Java5-style).

    Without seeing some code, I'm not sure what you are doing. Also the link you supplied is broken.
    You always need to keep a live reference to your implementation class. How you do this is your business. Using a separate thread is over-kill.
    I set a reference to the implementation class in the start up class and use a never ending wait() to make sure the start up class thread (with the main()) lives forever.

  • Premature Garbage Collection of Remote Objects

    I have a problem with distributed garbage collection and RMI. In CSPoker we try to support RMI for client-server communication. The client looks up the server through the registry, calls the login method and receives back a Remote Object reference called ServerContext. The client can register Remote even listener Objects with the server.
    In both directions we occasionally see:
    java.rmi.NoSuchObjectException: no such object in table
    The behaviour is completely unpredictable. Some developers never see it, others see it all the time. Even on the same machine, sometimes it failes immediately
    and sometimes it fails after a while. One person running the Sun JRE 6 on Windows has this poblem most frequently.
    Can this be a bug or do we misinterpret something? The way we see it, as long as the client leases the Remote Object it shouldn't be GCed. All tests are run on localhost so no network partition can occur.
    The problem would probably be solved if we hold static references to all Remote Objects in the local JVM. This is not an option because we want the Objects to be GCed once the lease expires.
    Here are 2 debugging outputs of server runs with RMI logging enabled:
    http://cspoker.pastebin.com/f27a7d6fc
    As you can see, the lease requests are coming through but a NoSuchObjectException is thrown and the Object is finalized.
    http://cspoker.pastebin.com/f732797d2

    Thanks for the quick reply.
    For instance:
    11:56:02,427 DEBUG (org.cspoker.common.api.shared.context.ForwardingRemoteServerContext.java:72) [finalize] - Garbage collecting old context: org.cspoker.server.rmi.export.ExportingServerContext@15a8767
    07.11.2008 11:56:02 sun.rmi.server.UnicastServerRef logCall
    FEINER: RMI TCP Connection(2)-10.0.4.106: [10.0.4.106: sun.rmi.transport.DGCImpl[0:0:0, 2]: java.rmi.dgc.Lease dirty(java.rmi.server.ObjID[], long, java.rmi.dgc.Lease)]
    07.11.2008 11:56:03 sun.rmi.transport.Transport serviceCall
    FEIN: RMI TCP Connection(2)-10.0.4.106: [10.0.4.106] exception:
    java.rmi.NoSuchObjectException: no such object in table
            at sun.rmi.transport.Transport.serviceCall(Transport.java:129)
            at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:466)
            at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:707)
            at java.lang.Thread.run(Thread.java:595)The context Object is exported and returned to the client here :
    return (ExternalRemoteServerContext) UnicastRemoteObject.exportObject(context, 0);Then [the object|http://code.google.com/p/cspoker/source/browse/trunk/server/rmi/src/main/java/org/cspoker/server/rmi/export/ExportingServerContext.java?r=1023] that was just exported is GCed.
    11:56:02,427 DEBUG (org.cspoker.common.api.shared.context.ForwardingRemoteServerContext.java:72) [finalize] - Garbage collecting old context: org.cspoker.server.rmi.export.ExportingServerContext@15a8767Then a lease request comes in:
    FEINER: RMI TCP Connection(2)-10.0.4.106: [10.0.4.106: sun.rmi.transport.DGCImpl[0:0:0, 2]: java.rmi.dgc.Lease dirty(java.rmi.server.ObjID[], long, java.rmi.dgc.Lease)]Then the client calls a method on the remote object and the NoSuchObjectException is thrown.
    The behaviour is non-deterministic in any case but yes, on the Linux JVM I'm not seeing the problem, somebody on Windows gets it all the time.

  • Swing Transferhandler prevents garbage collection of one Component

    While searching for memory leaks in my app I found out that an object wasn't garbage collected because of a static reference from javax.swing.TransferHandler.
    Once an app has called TransferHandler.exportAsDrag, TransferHandler keeps alive one static reference to a SwingDragGestureRecognizer.
        public void exportAsDrag(JComponent comp, InputEvent e, int action) {
            int srcActions = getSourceActions(comp);
            // only mouse events supported for drag operations
         if (!(e instanceof MouseEvent)
                    // only support known actions
                    || !(action == COPY || action == MOVE || action == LINK)
                    // only support valid source actions
                    || (srcActions & action) == 0) {
                action = NONE;
            if (action != NONE && !GraphicsEnvironment.isHeadless()) {
             if (recognizer == null) {
              recognizer = new SwingDragGestureRecognizer(new DragHandler());
                recognizer.gestured(comp, (MouseEvent)e, srcActions, action);
         } else {
                exportDone(comp, null, NONE);
    ....As you can see there is a call to recognizer.gestured(comp, (MouseEvent)e, srcActions, action). This object saves a reference to the component comp.
    This means that the last Component for which the exportAsDrag method was called (and the gestured call was reached); and all objects refererred to by the Component can not be garbage collected.
    I think in a normal application this will be not much of a problem because it's only a reference to a single Component; but still I think this is not very nice.
    Should I report this as a bug somewhere?

    Something similar seems to happens to JInternalFrame.lastFocusOwner
    Oh well, I guess I shouldn't worry too much about single references; I don't think they immediately cause memory leaks..

  • This byte array is not garbage collected?

    imageBytes[] does not seem to ever be garbage collected. I've pinpointed a SINGLE LINE that, when commented out, will prevent the memory leak. What could possibly be wrong with this line?
    Running this code results in a "OutOfMemoryError: Java heap space" after roughly a minute on my machine. I'm using JRE version 1.5.0_08.
    import javax.imageio.ImageIO;
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    // creates images to send to ImageConsumer
    public class ImageProducer {
         static BufferedImage bufferedImage;
         static Robot robo;
         static byte[] imageBytes;
         public static void main(String args[]) {
              try {
                   robo = new Robot();
              } catch(Exception e) {
                   e.printStackTrace();
              PipedOutputStream pos = new PipedOutputStream();
              new ImageConsumer(pos).start();
              bufferedImage = robo.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
              try {
                   ObjectOutputStream oostream = new ObjectOutputStream(pos);
                   ByteArrayOutputStream baos = new ByteArrayOutputStream();
                   ImageIO.write(bufferedImage, "JPG", baos);
                   baos.flush();
                   imageBytes = baos.toByteArray();
                   while (true) {
                        ImageIO.write(bufferedImage, "JPG", baos);
                        baos.flush();
                        // THIS SEEMS TO BE WHERE THE MEMORY LEAK OCCURS: imageBytes
                        // If you comment the following line out, there will be no
                        // memory leak. Why?  I ask that you help me solve this.
                        imageBytes = baos.toByteArray();
                        baos.reset();
                        oostream.writeObject(imageBytes);
                        pos.flush();
              } catch (Exception e) {
                   e.printStackTrace();
    // This thread reads the image data into bImg
    class ImageConsumer extends Thread {
         BufferedImage bImg;
         PipedInputStream pis;
         ImageConsumer(PipedOutputStream pos) {
              try {
                   pis = new PipedInputStream(pos);
              } catch (IOException e) { e.printStackTrace();}
         public void run() {
              try {
                   ObjectInputStream oinstream = new ObjectInputStream(pis);
                   while (true) {
                        byte[] imageBytes = (byte[])oinstream.readObject();
                        ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
                        bImg = ImageIO.read(bais);
              } catch (Exception e) {e.printStackTrace();}
    }

    while (true) {
         ImageIO.write(bufferedImage, "JPG", baos);
         baos.flush();
         // THIS SEEMS TO BE WHERE THE MEMORY LEAK OCCURS: imageBytes
         // If you comment the following line out, there will be no
         // memory leak. Why? I ask that you help me solve this.
         imageBytes = baos.toByteArray();
         baos.reset();
         oostream.writeObject(imageBytes);
         pos.flush();
    }I have only briefly gone through the code, but why are you flushing it right before calling that line. Won't the byte array returned always be empty right after flushing the stream?

  • Garbage-collecting the cloned objects

    public class Clone implements Cloneable {
    public static void main(String[] arg) {
    Clone i0, i1;
    i0 = new Clone();
    System.out.println("Created: " + i0);
    try{
    i1 = (Clone)i0.clone();
    System.out.println("Cloned: " + i1);
    } catch(CloneNotSupportedException e){
    e.printStackTrace();
    i0 = null;
    i1 = null;
    System.gc();
    public Object clone() throws CloneNotSupportedException {
    return super.clone();
    public void finalize() {
    System.out.println("Finalizing " + this);
    With the example above you can notify that with Hotspot VM of JDK1.3 the
    finalize() method will not be called for the cloned object; though,
    running the sample with the classic VM, the finalize() will be
    called for both objects.
    Bypassing the finalize() can be made intended, in order to avoid
    multiple "release" or "close" calls on the same object, eg. if the
    finalize() has to close a file or a JDBC-connnection. But then why
    is it called in the classic VM? Is it sure that the cloned object
    too will be garbage-collected?

    Here's the proper way to write a clone() method:
    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
    }There's no reason for a clone() method to declare that it throws CloneNotSupportedException. Doing so just makes code that uses the clone() method more complicated unnecessarily.
    Here's the proper way to write a finalizer:
    protected void finalize() {
        try {
            // perform subclass cleanup
        } finally {
            super.finalize();
    You should always make finalize() protected to help ensure that only the garbage collector calls it, and it should always call super.finalize() to ensure that the superclass finalization can happen.
    Now, to your question. There's no way to guarantee that an object will be garbage collected or finalized. In fact, finalizers are so notoriously hard to write correctly that Java 2 added PhantomReferences to allow a simpler way to clean up objects.
    If you want an object to release resources, such as closing a file or releasing a database connection, provide a close() or dispose() or release() method in the class and close the resources there. Even if you could guarantee that your finalizer is called or if you used PhantomReference queues to perform cleanup, this cleanup would probably not happen in a timely manner. Finalizers are not C++ destructors -- if you need to release resources, add a method to do that.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • GUI Garbage Collection

    Hi Everyone.
    This is very urgent. I need to perform a possible garbage collection of a heavy GUI stuff when it is not in use. Each of the GUI stuff is created from an action listener for the various menu items. I did try using WeakReference but its very hard to know that when the collection will take place.
    Here is the code snippet for the situation...
    //this is application's main frame class...
    public class MyApplication extends JFrame
    JMenuItem menu1, menu2;
    WeakReference ref_MyPanel;
    //earlier it was a strong reference of MyPanel over here
    public static void main(String [] args)
    //instantiating this class and showing that here ...
    //This is called from menu1's action listener..
    void showGUI()
    JFrame f = new JFrame();
    if(ref_MyPanel.get()!=null)
    f.getContentPane().add((MyPanel)ref_MyPanel.get());
    else
    MyPanel mp = new MyPanel();
    ref_MyPanel=new WeakReference(mp);
    f.getContentPane().add(mp);
    mp=null;//clearing the strong refernce
    f.show();
    //A GUI class which needs to be reclaimed when done
    class MyPanel extends JPanel
    double [] a;
    MyPanel1()
    a = new double [1000000]; //making the panel instance heavy
    What i want is to reclaim the memory occupied by MyPanel instance after its Frame being closed. I even tried calling the System.gc() from the MyPanel instance's parent frame's WindowListener -> windowClosed() but it didn't help. Actually this is suffering me a lot as there are several menu items and several GUIs are being instantiated similar to those of MyPanel as shown above. Do i need to change this design to achieve the objective?
    Can anyone help?

    We saw a significant memory improvement in our system when we used this
    utility. Try using this handy class to recursively remove each component
    For JFrames & JApplets I think it was
    ComponentCleaner.cleanComponent ( myFrame.getContentPane() );
    For Frames & Applets
    ComponentCleaner.cleanComponent ( myFrame );
    Also, for every addActionListener(), addComponentListener() etc call,
    you want a removeActionListener(), removeComponentListener() call.
    The listeners store references to the visual components if I remember rightly. So avoid anonymous listener classes, and have proper cleanup methods to remove the listeners.
    (code below)
    regards,
    Owen
    import java.awt.Container;
    import java.awt.Component;
    import javax.swing.RootPaneContainer;
    public class ComponentCleaner
        public static void cleanComponent(Component baseComponent)
            if (baseComponent == null) // recursion terminating clause
                return ;
            Container cont;
            Component[] childComponents;
            int numChildren;
            // clean up component containers
            if(baseComponent instanceof Container)
                // now clean up container instance variables
                if (baseComponent instanceof RootPaneContainer)
                   // Swing specialised container
                    cont = (Container)baseComponent;
                    numChildren = cont.getComponentCount();
                    childComponents = cont.getComponents();
                    for(int i = 0;i < numChildren;i++)
                        // remove each component from the current container
                        // each child component may be a container itself
                        cleanComponent(childComponents);
    ((RootPaneContainer)cont).getContentPane().remove(childComponents[i]);
    ((RootPaneContainer)cont).getContentPane().setLayout(null);
    else
    { // General Swing, and AWT, Containers
    cont = (Container)baseComponent;
    numChildren = cont.getComponentCount();
    childComponents = cont.getComponents();
    for(int i = 0;i < numChildren;i++)
    // remove each component from the current container
    // each child component may be a container itself
    cleanComponent(childComponents[i]);
    cont.remove(childComponents[i]);
    cont.setLayout(null);
    } // if component is also a container

  • A question about JNI references, persistence, and garbage collection

    I am writing a library to allow our Java developers to access C functions in our product. I want people on the Java side to be able to instantiate instances of a new object (on the C side), say "Map", and I want those objects to persist until they are destroyed on the Java side. I am thinking of creating a wrapper for the native methods, which stores an identifier for the instance of an object. When the C object is accessed, the identifier is passed to the C code which looks up the correct object in a table. I understand that if I use the NewGlobalReference call in JNI I can get objects to persist.
    When it is time for garbage collection I plan to override finalize() to call the C code and tell it to remove the Global Reference.
    Here's what I have in mind
    public class JMap() {
         private static int id;
         static {
              System.loadLibrary("libMap");
              /*Call C method which instantiates object and creates a GlobalReference
              which is stored in table. Returns ID for reference*/
              id = _init();
         public void setSize(int x, int y) {
              _setSize(id, x, y);
         public void finalize() {
              _finalize(id);
              super.finalize();
         private native int _init();
         /*calls DeleteGlobalReference for the reference matching this id*/
         private native void _finalize(int id);
         private native void _setSize(int id, int x, int y);
    }Is this the right thing to do? Have I understood the way JNI works with regard to GlobalReferences?
    Any comments, tips or pointers would be appreciated :)

    This probably should have been posted in the Native Methods sub-forum, I have reposted there:
    http://forum.java.sun.com/thread.jspa?threadID=657667
    Mods please delete this post :)

  • Nested object reference after garbage collection

    I have a question about how GC works.
    Assume I have a Class A which has a reference to class B inside it. I create a object of class B and assign to member variable of class A.
    Now when obja is no longer needed, I set it null. And when GC runs, the object will be removed from memory. But should I also need to explicitly set objb to null. If i don't set it, will it also get garbage collected when obja is being removed from memory?
    public class ClassA {
    private ClassB objB = new ClassB();
    private static void main(String args[]) {
    ClassA obja = new ClassA();
    obja = null;
    }

    801625 wrote:
    But should I also need to explicitly set objb to null.No.
    If i don't set it, will it also get garbage collected when obja is being removed from memory?If there are no other references outside of classA to the object referenced by objB (in your case an instance of ClassB) then it will be garbage collected.
    Note - the only time one needs to set a reference to null is if one wants the object it references to be eligible for GC before the reference goes out of scope. There is a slight complication to this - depending on the JVM implementation, if a reference is defined in a block internal to a method then even though it goes out of scope when execution goes out of the block anything it references may not be eligible for GC until the method exits.

  • How garbage collection works in spring framework?

    Hi,
    Whether we are using or not, all objects are created and stored in beanfactory in spring frramework.
    So how garbage collection will work here?
    Thanks in advance

    It depends on the scope, by default beans are singletons and will not be garbage collected.
    http://static.springframework.org/spring/docs/2.0.x/reference/beans.html#beans-factory-scopes

  • Animation gets slow when program needs a Garbage Collect.

    So nonetheless, I should probably develop a new animation algorithm, yes?
    I am looping through a seperate thread that calls the setSize() methods a bunch of times. Works really nice when memory isnt bad, but when I need to garbage collect, and apparantly java doesnt agree, it gets really slow. Later one is really able to see when a GC is actually done, and it goes back to normal.
    Here is my algorithm,
    public static boolean raisePanel(final VCMSComponentFrame p, final boolean anim)
            if (p.getState() == VCMSComponentFrame.State.RAISED ||
                p.getState() == VCMSComponentFrame.State.ANIMATING)
                return false;
            new Thread(new Runnable()
                public void run()
                    p.setState(VCMSComponentFrame.State.ANIMATING);
                    if (anim)
                        for (int i = p.getHeight(); i <= FULL_PANEL_HEIGHT; i++)
                            try
                                p.setSize(p.getWidth(), i);
                                JComponent parent = (JComponent)p.getParent();
                                int index = findIndex(p);
                                for (int j = index + 1; j < parent.getComponentCount() && j != 0; j++)
                                     parent.getComponent(j).setLocation(parent.getComponent(j).getX(), parent.getComponent(j).getY() + 1);
                                //Viewport Panel
                                parent.setSize(parent.getWidth(), parent.getHeight() + 1);
                                //Structure Frame
                                VCMSStructurePanel panel = (VCMSStructurePanel)parent.getParent();
                                parent.getParent().setSize(panel.getWidth(), panel.getHeight() + 1);
                                //Structure Siblings.
                                JPanel master = (JPanel)panel.getParent();
                                index = findStructureIndex(panel);
                                for (int j = index + 1; j < master.getComponentCount() && j != 0; j++)
                                    master.getComponent(j).setLocation(master.getComponent(j).getX(), master.getComponent(j).getY() + 1);
                                Thread.sleep(1);
                            catch (Exception ex)
                    else
                        p.setSize(p.getWidth(), FULL_PANEL_HEIGHT);
                        JPanel parent = (JPanel)p.getParent();
                        int index = findIndex(p);
                        //Viewport Panel
                        parent.setSize(parent.getWidth(), parent.getHeight() + FULL_PANEL_HEIGHT - SHORT_PANEL_HEIGHT);
                        //Structure Frame
                        VCMSStructurePanel panel = (VCMSStructurePanel)parent.getParent();
                        parent.getParent().setSize(panel.getWidth(), panel.getHeight() + FULL_PANEL_HEIGHT - SHORT_PANEL_HEIGHT);
                        //Component Siblings
                        for (int j = index + 1; j < parent.getComponentCount() && j != 0; j++)
                            parent.getComponent(j).setLocation((int)parent.getComponents()[j].getLocation().getX(), (int)parent.getComponents()[j].getLocation().getY() + FULL_PANEL_HEIGHT - SHORT_PANEL_HEIGHT);
                        //Structure Grandparent
                        JPanel master = (JPanel)panel.getParent();
                        index = findStructureIndex(panel);
                        for (int j = index + 1; j < master.getComponentCount() && j != 0; j++)
                            master.getComponent(j).setLocation((int)master.getComponent(j).getLocation().getX(), (int)master.getComponent(j).getLocation().getY() + FULL_PANEL_HEIGHT - SHORT_PANEL_HEIGHT);
                    p.setState(VCMSComponentFrame.State.RAISED);
            }).start();
            //System.gc();
            return true;
        }any help appreciated!

    sierratech wrote:
    Only a guess, but this may have something to do with Threads and Swing.
    http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html.
    Many Swing updates should be called in the Event Dispatch thread, and it looks like you may be calling some of these in your new Thread.
    Try using SwingUtilities.invokeLater() and see if that helps. Alternatively, rewrite your code to remove the Thread and do everything in the event Dispatch thread using javax.swing.Timer. Again, just a guessThanks for the Idea, but this option doesnt even show the animation.
    One Idea I got from a "Swing Hacks" directory works like this:
    Remove the components for animation.
    Create an image of the components.
    Overide the Paint method.
    Animate the images via paint method.
    Remove the images.
    Add back the components.
    But I look at that and my stomach cringes.
    Any other Ideas?

Maybe you are looking for

  • My computer wont recognise my iphone when i plug it in.

    When i plu g my iphone into my computer it will, my windows 7 computer will no longer recognise it. I have tried diff ports and cable, then tried my laptop which it did work on, then tried a ipod touch on to this computer and it recognised that. I ha

  • Does sql server could export a partition from a partition table ?

    Dear :    Does sql server could export a partition from a partition table ?    For example, I need to export all old partition,which is '2013' and drop them.  It is easy in oracle. but how to do with sql server 2012 ?

  • Code for Rediret from one webapplication to another in Application Page (Layout folder)

    There is a requirement to redirect from one web application to another using an intermediate SharePoint application page where we have tried SPUtility.Redirect/Response.Redirect however SPUtility.Redirect or Response.Redirect is referring the current

  • Empty item in the first position of a select box

    Hello. I'm trying to reproduce a very common behaviour of combo-boxes with Spry, without much success. My code populates a combo-box trough a Spry XML dataset. All the items are correctly displayed; the first element in the XML is showed as the defau

  • Stacking not working

    All the menu items associated with stacking are greyed out on my Lightroom 1 on Windows XP installation. I can't find any way of enabling them. I have tried selecting images in the library module and creating virtual images with no joy ( creating vir