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.

Similar Messages

  • CF 8 JVM memory is not being garbage collected.

    I am baffled by something I am seeing on my QA server. I have
    an app that we load tested but when the test completed the JVM
    memory used was not released. I used CF Server Monitor to watch the
    memory usage and sometimes it spiked to the max and either the app
    failed or I got timeout exceptions.
    This is the only app running on this server and the testing
    completed over an hour ago but the memory has not been released
    yet.
    CF Admin settings:
    Maximum JVM Heap Size (MB) 512
    The CF Server JVM Setting arguments include: -server
    -Dsun.io.useCanonCaches=false -XX:MaxPermSize=192m
    -XX:+UseParallelGC
    I found a script that uses java.lang.Runtime and
    java.lang.management.managementFactory that dumps a JVM memory
    usage profile The latest dump follows:
    JVM Monitor - ColdFusion Server - Enterprise v8,0,1,195765
    JVM Memory Monitor - struct
    Heap Memory Usage - Committed 481 MB
    Heap Memory Usage - Initial 0.00 MB
    Heap Memory Usage - Max 493 MB
    Heap Memory Usage - Used 437 MB
    JVM - Free Memory 44.0 MB
    JVM - Max Memory 493 MB
    JVM - Total Memory 481 MB
    JVM - Used Memory 449 MB
    Memory Pool - Code Cache - Used 8.80 MB
    Memory Pool - PS Eden Space - Used 6.37 MB
    Memory Pool - PS Old Gen - Used 428 MB
    Memory Pool - PS Perm Gen - Used 52.4 MB
    Memory Pool - PS Survivor Space - Used 3.50 MB
    Non-Heap Memory Usage - Committed 62.8 MB
    Non-Heap Memory Usage - Initial 18.3 MB
    Non-Heap Memory Usage - Max 240 MB
    Non-Heap Memory Usage - Used 61.2 MB
    According to the CF Server Monitor JVM memory usage builds up
    to 477 MB then the app fails or timesout.
    Session Scope memory usage: 0.27 KB
    Application Scope memory usage: 1.370 KB
    Server Scope memory usage: 3.12 KB
    Since the test ended JVM Memory Usage has dropped back to 438
    MB?
    Besides CFAdmin nothing else is running on this CF Server.
    I've read several other memory related topics but none of them have
    helped.
    Can someone tell me why the memory isn't being release? How
    can I further troubleshoot the problem?
    Thx
    pwp

    > Adam Cameron wrote:
    >
    The maximum stable heap size I've managed to get is around
    > 1.0-1.2GB, on a win32 system. On Solaris (running a
    32-bit JVM),
    > about 1.4GB. It *seems* like GC doesn't actually clear
    out RAM
    > properly if more than that much RAM is being
    addressed.
    >
    > Yes, there is a well-known
    >
    http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_19359&sliceId=1
    Not really what I was talking about. One might be able to get
    the CF
    instance to *start* with 1.8GB allocated to the heap, but it
    won't actually
    work. I've managed to get a server to idle for a reasonable
    length of time
    on 1.5GB, but as soon as the thing started to ramp up, it
    face-planted,
    once it started actually trying to *use* the higher end of
    the RAM
    allocated to it. At 1.2GB, it'll seem to run OK for a
    reasonable length of
    time, but eventually it starts leaking memory; at around 1GB,
    it was pretty
    stable.
    Hence my comment about it being *stable* at that allocation.
    Not that "it
    simply won't start if more than 1.8GB is allocated to it".
    My point was that your rule of thumb:
    maximum heap size(Xmx) = RAM(in MB) / (2 * number of servers
    using the
    JVM)
    Is not a very good one. Plug 4GB RAM (so a small server) and
    one CF
    instance into that equation. Your rule suggests I should be
    allocating 2GB
    to the heap. Which - as you yourself pointed out - won't
    work.
    Adam

  • URL class is not working in Java 1.4. However works in Java 1.3

    I have a Java program which uses URL classes through FTP connection to open any files. It works fine in Java 1.3 version. However the same program fails with
    java.io.FileNotFoundException: at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream
    when using Java 1.4 version.
    Here is the part of source code.
    try
    URL url ;
    url = new URL("ftp://"); // I have not given the full connect string here.
    URLConnection connection = url.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine) ;
    in.close();
    catch(Exception e)
    System.out.println("Error occured " + e.getMessage());
    Anyone has ideas about what is going wrong and how to correct that. I appreciate your reply.
    Thanks

    Here is the original code. I have not given the password and using as "anonymous". Again this code works fine in Java1.3. But not in Java1.4 . I appreciate your help .Is it something I have to set up in UNIX side. The exact error is
    <p>
    "Exception in thread "main" java.io.FileNotFoundException: oraom/temp.log
    at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(FtpURLConnec
    tion.java:333)
    at java.net.URL.openStream(URL.java:913)
    at temp.main(temp.java:17) "
    <P>
    import java.net.*;
    <P>
    import java.io.*;
    <P>
    import java.util.*;
    <P>
    public class temp
    <P>
    <P>
    public static void main(String args[]) throws Exception
    <P>
    <P>
    URL url = new URL("ftp://oraom:anonymous@oradev:/oraom/temp.log");
    <P>
    try
    <P>
    <P>               
    URLConnection connection = url.openConnection();
    <P>
    connection.setDoInput(true);
    <P>
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    <P>
         String inputLine;
    <P>
         while ((inputLine = in.readLine()) != null)
    <P>
         System.out.println(inputLine) ;
    <P>
         in.close();
    <P>
    <P>
    catch(Exception e)
    <P>
    <P>
    throw e;
    <P>
    <P>                                                  
    <P>
    <P>
    </P>

  • Entity Beans not getting garbage collected

    Hi,
    I am developing an application that is using EJBs utilizing several common design patterns (i.e. Session Facade, DAO, and Fast Lane Reader). All of the patterns used have come from books by Sun Microsystems Press.
    As I have understood the pattern, the Session Facade pattern uses Stateless Session Beans (SLSB) to implement a desired functionality and accesses the entity beans locally. The results from the entity beans are placed into Value Objects and passed back to the client separating any direct access with the entity beans from the client. In my case, I am using BMP for my entity beans.
    The problem I am seeing with Optimizeit is that none of my entity beans are getting garbage collected despite no references to them. The SLSB creates what entities it needs to perform a task at the local level, puts the data into a value object and goes out of scope.
    Shouldn't the entity beans get removed if the object that references them has gone away or am I missing something?
    Is there a proper way to set an entity bean (or any EJB for that matter) for garbage collection.
    thanks in advance for any help...

    You might even discover that entity beans can get created even before you use them.
    Your application server creates "pools" of bean instances that it can use when it needs to. It is part of this role, and is done in order to optimize performances.
    You cannot force them to be garbage collected. Even if you stop referencing them, the app server will.
    When your create references to a bean, it (usually) won't create an instance. It will take an existing one, and load data into it, using ejbCreate or ejbActivate.
    Hope this helps.
    /Stephane

  • Question on why Class is not being called by POST Form action

    Hello I am trying to use JavaMail and send an email to myself for a test through a JSP form. I have this line in my jsp code
    <form name="emailSendForm" action="servlet/EmailServlet/NewEmail.class" METHOD="POST" >Then this is my doPost method
    public void doPost (HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      System.out.println("Hello we are in the New Mail");
      HttpSession session = request.getSession (false);However, nothing happens when I hit my submit button. Even my system.out message is not even appearing. I am missing a piece of code? Thanks

    Where are you storing the .class file? I'm getting the idea that you are not storing it inside the WEB-INF/classes directory but in the web root like you would a JSP.
    Servlets don't work that way. I'll illustrate an example setup.
    Say I have a servlet called NewEmail and it is in the package servlet.email.
    step 1: make sure the servlet .class file is stored in the proper directory. This is webapproot/WEB-INF/classes/servlet/email/NewEmail.class. The directory structure inside the WEB-INF/classes directory matches the package of the servlet (this directory is part of the classpath of your web application).
    step 2: define the servlet in the WEB-INF/web.xml file of your web application. If you don't do this you cannot invoke the servlet.
    <servlet>
    <servlet-name>NewEmail</servlet-name>
    <servlet-class>servlet.email.NewEmail</servlet>
    </servlet>
    <servlet-mapping>
    <servlet-name>NewEmail</servlet-name>
    <url-pattern>/NewEmail</url-pattern>
    </servlet-mapping>The url-pattern defines how you will be invoking your servlet through the web. NewEmail means that you can submit to "NewEmail" or call the servlet as http://yourwebsite.com/NewEmail.
    Step 3: put the right URL in your form
    <form name="emailSendForm" action="NewEmail" method="post">
    </form>Again, check that the action attribute matches the url-pattern without the slash in front of it.
    That should do it! Unless I made a typo somewhere of course.
    Note by the way that System.out.println is NOT going to send anything to the browser, but most likely to a logfile kept by the webserver. You need to send data using the response object to make it appear in the browser.

  • How to make external SWFs garbage collected in Air for iOS?

    My app uses lots of external SWFs( well they are actually included in the app with a folder but they aren't embeded ) and they do not contain any bitmapdata, only vector graphics. The problem I'm having is that they seem to be never garbage collected and System.privateMemory keeps increasing as the app loads more SWFs.
    Since those SWFs only contain vector graphics, I simply nullify all the variables that are holding reference to SWF file and call System.gc().. But it doesn't seem to be working. What would I need to do for the garbage collector to clean the SWFs?
    I'm using Air for iOS 3.5.0.1060 and ActionScript3.0.

    Yes I'm calling System.gc() twice. I tried using loader.unloadAndStop(true) and it seems SWFs are being garbage collected but another problem has surfaced. When repeatedly loading and unloading SWF in a short period, the air garbage collector sometimes fails to work.
    I've tested loading and unloading same SWF 50k times and checked trace.  Occasionally, garbage collector misses to collect garbage like below( swf #45119 is not being garbage collected).
    [UnloadSWF] main.swf/[[DYNAMIC]]/45115
    [UnloadSWF] main.swf/[[DYNAMIC]]/45116
    [UnloadSWF] main.swf/[[DYNAMIC]]/45117
    [UnloadSWF] main.swf/[[DYNAMIC]]/45118
    [UnloadSWF] main.swf/[[DYNAMIC]]/45120
    [UnloadSWF] main.swf/[[DYNAMIC]]/45121

  • 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.........................
    }

  • Oracle JVM Garbage Collection not executing

    I am experiencing a problem with garbage collection when running a java stored procedure in an 9.2.0.3.0 Oracle database running on a Windows 2k computer.
    I have created a simple java class that represents a tree structure. Each instance of the class has a reference to it's parent and a Vecotor of all it's children. Each instance also has a Vector to hold name value pairs. I ran a program that creates 30 instances with 50 children each for a total of 1500 instances. Each instance has 30 properties(name value pairs).
    By using the debugger in JDeveloper and breakpoints I can watch the javaw.exe process's use of RAM.
    Start up: 6,788mb
    After creation of 1500 instances: 17,720
    After releasing all objects and calling System.gc(): 7,156
    I deploy the package to my Oracle database and perform the exact same routine using breakpoints and test procedures in plsql Developer. Using the breakpoints and watching the oracle.exe process's use of RAM I see:
    Start up: 81,116mb
    After creation of 1500 instances: 94,952
    After releasing all objects and calling System.gc(): 95,036
    When run in Oracle the resources are not released. Is there somthing special that needs to be called to get the garbage collector to do it's job when running in an Oracle database?
    Execution Instructions and source:
    run app.main from jdeveloper and app.main2 as a plsql stored procedure. I have included my test procedure at the end and the plsql stored procedure package declarations. I used debuggers and breakpoints to watch the process, there is probably a way to do this by outputting the current memory being used by I didn't know how. If you use debuggers and breakpoints then when running in JDeveloper put your breakpoints on the 3 assignments of breakpointVar in SimpleClass.main(...). When running the stored procedure test block put them on the 3 assignments of breakpoint_var in there.
    package mypackage2;
    public class app {
    private static SimpleClass topObject;
    public static void main(String[] args) {
    int breakpointVar;
    breakpointVar = 0;
    main2(30, 50);
    breakpointVar = 1;
    release();
    breakpointVar = 2;
    public static void main2(int numParents, int numChildren){
    SimpleClass temp;
    SimpleClass child;
    topObject = new SimpleClass();
    for(int i = 0; i < numParents; i ++){
    temp = new SimpleClass();
    addProperties(temp, 30);
    topObject.addChild(temp);
    for(int j = 0; j < numChildren; j++){
    child = new SimpleClass();
    addProperties(child, 30);
    temp.addChild(child);
    public static void release(){
    topObject.releaseAllDecendents();
    topObject.release();
    System.gc();
    private static void addProperties(SimpleClass toAddTo, int numProps){
    cimxProperty toAdd;
    for(int i = 0; i < numProps; i ++){
    toAdd = new cimxProperty("prop "+i,"value "+i);
    toAddTo.addProperty(toAdd);
    package mypackage2;
    import java.util.Vector;
    public class SimpleClass {
    private Vector _children;
    private Vector _props;
    private SimpleClass _parent;
    public SimpleClass() {
    _children = new Vector(10, 5);
    _props = new Vector(10, 5);
    _parent = null;
    public void addChild(SimpleClass toAdd) {
    toAdd._parent = this;
    _children.add(toAdd);
    public SimpleClass getChild(int index){
    return (SimpleClass)_children.get(index);
    public void addProperty(cimxProperty toAdd){
    _props.add(toAdd);
    public cimxProperty getProperty(int index) {
    return (cimxProperty)_props.get(index);
    public void releaseAllDecendents()
    SimpleClass temp;
    //remove all references to the the parent object from the children.
    for(int i = 0; i < _children.size(); i ++)
    temp = (SimpleClass)this._children.get(i);
    temp.releaseAllDecendents();
    temp._parent = null;
    temp._props.clear();
    temp._children.clear();
    temp = null;
    this._children.clear();
    public void release() {
    this._parent = null;
    this._children.clear();
    this._props.clear();
    package mypackage2;
    public class cimxProperty
    private static String _dateFormat = "MM/DD/YYYY HH:MI:SS";
    private String name;
    private String value;
    private String dataType;
    public cimxProperty()
    name = "";
    value = "";
    dataType = "";
    public cimxProperty(String Name, String Value)
    name = Name;
    value = Value;
    dataType = "UNKNOWN";
    public cimxProperty(String Name, String Value, String DataType)
    name = Name;
    value = Value;
    dataType = DataType;
    public String toString()
    return name + "["+dataType + "]: " + value;
    public void setName(String name)
    this.name = name;
    public String getName()
    return name;
    public void setValue(String value)
    this.value = value;
    public String getValue()
    return value;
    public void setDataType(String DataType)
    this.dataType = DataType;
    public String getDataType()
    return dataType;
    CREATE OR REPLACE PACKAGE JAVA_MEMORY_TEST AUTHID CURRENT_USER AS PROCEDURE release; PROCEDURE main2(p_num_parents IN NUMBER, p_num_children IN NUMBER); END JAVA_MEMORY_TEST;
    CREATE OR REPLACE PACKAGE BODY JAVA_MEMORY_TEST AS PROCEDURE release AS LANGUAGE JAVA NAME 'mypackage2.app.release()'; PROCEDURE main2(p_num_parents IN NUMBER, p_num_children IN NUMBER) AS LANGUAGE JAVA NAME 'mypackage2.app.main2(int, int)'; END JAVA_MEMORY_TEST;
    declare
    number breakpoint_var
    begin
    -- Call the procedure
    breakpoint_var := 0;
    java_memory_test.main2(30, 50);
    breakpoint_var := 1;
    java_memory_test.release();
    breakpoint_var := 2;
    end;

    When run in Oracle the resources are not released. Is there somthing special that needs to
    be called to get the garbage collector to do it's job when running in an Oracle database?Curious - I was always under the impression that you can not force garbage collection. All you could do was request it, and the JVM was free to do that when it was "good 'n ready", usually in a separate thread.
    I gather this from the API docs for system.gc() where it says "Calling this method suggests that the Java virtual machine expend effort ..." and the word "suggests" imlies that it is not required to run.

  • 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.

  • 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.

  • Local ref garbage collection within "nested" JNI calls

    I am using a JVM started in C++ to make calls to java classes. The C++ code makes JNI call into the JVM which instantiates a java class. The java class, in the course of execution, makes other JNI calls. All this happens on one thread of execution.
    What I am seeing is that local references from the native methods being called by the java class are not being released until the initial C++ native call exits. The JNI spec (text included below) seems to indicate there is registry of "nonmovable local references to Java objects" which "keeps the objects from being garbage collected". Is there only one such registry which does not get deleted until the initial C++ native call exits? If so, this would explain what I am seeing. How do I get around it?
    Thanks,
    Iztok
    From the JNI spec:
    "To implement local references, the Java VM creates a registry for each
    transition of control from Java to a native method. A registry maps nonmovable local references to Java objects, and keeps the objects from being garbage collected. All Java objects passed to the native method (including those that are returned as the results of JNI function calls) are automatically added to the registry. The registry is deleted after the native method returns, allowing all of its entries to be garbage collected."

    When I say "initial" I mean the initial C++ JNI call into a JVM running in a C++ process as shown in the pseudo code below. initNativeFunc() makes a call to Foo.doSomething() function which calls nativeFunc2 (another native function). Only a local reference to Retval was created in nativeFunct2, so when nativeFunct2 returns and the Retval is no longer used in Foo it should be a candidate for garbage collection. But this is not what happens. The Retval from nativeFunc2 is not being cleaned up until Foo.doSomething() returns. If I make the loop in Foo.doSomething() long enough, NewDoubleArray() returns a NULL when it runs out of memory.
    void initNativeFunc() {
    jclass clazz = env->FindClass("Foo");
    jmethodID mid = env->GetMethodID(clazz, "doSomething", "()V");
    env->CallVoidMethod(clazz, mid, ...);
    JNIEXPORT jobject JNICALL nativeFunc2() {
    jclass clazz = env->FindClass("Retval");
    jmethodID mid = env->GetMethodID("Retval, "<init>", "()V");
    jobject retval= env->NewObject(clazz, mid);
    jdoubleArray da = env->NewDoubleArray(100000);
    jfieldID fid = ...
    env->SetObjectField(retval, fid, da);
    return retval;
    public class Foo {
    public native void nativeFunc2();
    public void doSomething() {
    for (int i = 0; i < 100; i++) {
    Retval retval = nativeFunc2();
    }

  • Avoiding Garbage Collection

    Hi,
    Does anyone know of a general design pattern that allows an object to remain
    in memory without being garbage collected ? I'm not clear whether or not
    the singleton pattern fulfills this requirement. I basically want to have a
    Global constants class (constants are loaded from a properties file) that
    remains in memory so that it can be used by various components. The
    constants are loaded from a properties file initialially. So if that class
    gets garbage collected, then the next time that class is accessed, it will
    have to reload from the props file. This is a performance issue, and I
    would like to find a solution around it.
    I will probably want to have other services such as a LoggingService,
    JNDIService that I want started up, and for it to remain in memory. I know
    you can register startup classes with WL, but do those classes remain in
    memory ?
    I'm been trying to find an answer to these questions. Hopefully someone
    will have them.
    Thanks.

    One way to do it is to bind your constants class into JNDI during
    start-up.
    -- Rob
    Jamie Tsao wrote:
    >
    Hi,
    Does anyone know of a general design pattern that allows an object to remain
    in memory without being garbage collected ? I'm not clear whether or not
    the singleton pattern fulfills this requirement. I basically want to have a
    Global constants class (constants are loaded from a properties file) that
    remains in memory so that it can be used by various components. The
    constants are loaded from a properties file initialially. So if that class
    gets garbage collected, then the next time that class is accessed, it will
    have to reload from the props file. This is a performance issue, and I
    would like to find a solution around it.
    I will probably want to have other services such as a LoggingService,
    JNDIService that I want started up, and for it to remain in memory. I know
    you can register startup classes with WL, but do those classes remain in
    memory ?
    I'm been trying to find an answer to these questions. Hopefully someone
    will have them.
    Thanks.--
    Coming Soon: Building J2EE Applications & BEA WebLogic Server
    by Michael Girdley, Rob Woollen, and Sandra Emerson
    http://learnweblogic.com

  • JInternalFrame & Garbage Collection

    I am looking for a work-around for the long standing bug [4759312|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4759312]. In this bug, the JDesktopFrame maintains a reference to the last JInternalFrame to be closed, preventing it from being garbage collected. The recommendation that I have seen elsewhere is to remove everything from the JInternalFrame's contentPane so that those component's can be collected even if the JInternalFrame is not. However, that approach is not working for me. Here is an example that demonstrates the problem:
    Edited: Removed example as it contained some typos, see below
    If you create a new window, and then close it, the SimplePanel it stays in memory. My debugger shows that it's only references are it's button and layout manager. However, the button is referenced from JInternalFrame.lastFocusOwner, which is probably what is preventing it from being collected.
    How can I clear this reference? Is there another workaround to this bug that works better?
    Sorry, if this has been addressed before - the search on the old forums.sun.com is taking several minutes to respond to a query.
    Edited by: 797984 on Sep 30, 2010 11:49 AM

    6.th JInternalFrame raised (Netbeans debuger has correct delay) you can test it if you runs your code with builded profilier (Profile)
    run BuiltIn Profilier in NetBeans and check which Object exists, are still registred in current JVM instance,
    import java.awt.Window;
    import javax.swing.JInternalFrame;
    import javax.swing.event.InternalFrameAdapter;
    import javax.swing.event.InternalFrameEvent;
    public class TopLevelDesktop extends javax.swing.JFrame {
        private static final long serialVersionUID = 1L;
        private javax.swing.JDesktopPane desktopPane;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JButton newSimpleInternalWindow;
        private javax.swing.JButton gcButton;
        private javax.swing.JLabel maxMemory;
        private javax.swing.JLabel totalMemory;
        private javax.swing.JLabel usedMemory;
        private javax.swing.JLabel freeMemory;
        public TopLevelDesktop() {
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setMinimumSize(new java.awt.Dimension(400, 300));
            jPanel1 = new javax.swing.JPanel();
            jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.Y_AXIS));
            desktopPane = new javax.swing.JDesktopPane();
            newSimpleInternalWindow = new javax.swing.JButton();
            newSimpleInternalWindow.setText("New Internal Window");
            newSimpleInternalWindow.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    final JInternalFrame internalFrame = new JInternalFrame("Hi", true, true, true, true);
                    internalFrame.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
                    internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
                        @Override
                        public void internalFrameClosed(InternalFrameEvent e) {
                            e.getInternalFrame().getContentPane().removeAll();
                            e.getInternalFrame().getContentPane().requestFocusInWindow();
                            remWins(internalFrame);
                            Runtime runtime = Runtime.getRuntime();
                            long total = runtime.totalMemory();
                            long free = runtime.freeMemory();
                            long max = runtime.maxMemory();
                            long used = total - free;
                            System.out.println("Remove new JInternalFrame : " + Math.round(max / 1e6) + " MB available");
                            System.out.println("Remove new JInternalFrame : " + Math.round(total / 1e6) + " MB allocated");
                            System.out.println("Remove new JInternalFrame : " + Math.round(free / 1e6) + " MB free");
                            System.out.println("Remove new JInternalFrame : " + Math.round(used / 1e6) + " MB used");
                    internalFrame.getContentPane().add(new SimplePanel());
                    internalFrame.pack();
                    internalFrame.setVisible(true);
                    desktopPane.add(internalFrame);
                    Runtime runtime = Runtime.getRuntime();
                    long total = runtime.totalMemory();
                    long free = runtime.freeMemory();
                    long max = runtime.maxMemory();
                    long used = total - free;
                    System.out.println("Add new JInternalFrame : " + Math.round(max / 1e6) + " MB available");
                    System.out.println("Add new JInternalFrame : " + Math.round(total / 1e6) + " MB allocated");
                    System.out.println("Add new JInternalFrame : " + Math.round(free / 1e6) + " MB free");
                    System.out.println("Add new JInternalFrame : " + Math.round(used / 1e6) + " MB used");
            jPanel1.add(newSimpleInternalWindow);
            gcButton = new javax.swing.JButton();
            gcButton.setText("Run Garbage Collection");
            gcButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    Runtime runtime = Runtime.getRuntime();
                    runtime.gc();
                    long total = runtime.totalMemory();
                    long free = runtime.freeMemory();
                    long max = runtime.maxMemory();
                    long used = total - free;
                    maxMemory.setText(Math.round(max / 1e6) + " MB available");
                    totalMemory.setText(Math.round(total / 1e6) + " MB allocated");
                    freeMemory.setText(Math.round(free / 1e6) + " MB free");
                    usedMemory.setText(Math.round(used / 1e6) + " MB used");
                    System.out.println("Add new JInternalFrame : " + Math.round(max / 1e6) + " MB available");
                    System.out.println("Add new JInternalFrame : " + Math.round(total / 1e6) + " MB allocated");
                    System.out.println("Add new JInternalFrame : " + Math.round(free / 1e6) + " MB free");
                    System.out.println("Add new JInternalFrame : " + Math.round(used / 1e6) + " MB used");
            jPanel1.add(gcButton);
            maxMemory = new javax.swing.JLabel();
            totalMemory = new javax.swing.JLabel();
            usedMemory = new javax.swing.JLabel();
            freeMemory = new javax.swing.JLabel();
            jPanel1.add(maxMemory);
            jPanel1.add(totalMemory);
            jPanel1.add(usedMemory);
            jPanel1.add(freeMemory);
            getContentPane().add(jPanel1, java.awt.BorderLayout.WEST);
            getContentPane().add(desktopPane, java.awt.BorderLayout.CENTER);
            pack();
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TopLevelDesktop().setVisible(true);
        public void remWins(JInternalFrame internalFrame) {
            Window[] w;
            w = Window.getOwnerlessWindows();
            int n = 0;
            n = w.length;
            if (n > 1) {
                for (int i = 2; i <= w.length;) {
                    w[i - 1].setVisible(false);
                    i++;
            n = 0;
            n = internalFrame.getComponentCount();
            if (n > 0) {
                //Component[] a = panel.getComponents();
                 /*Component[] components = panel.getComponents();
                String compName = "";
                for (int i = 0, l = components.length; i < l; i++) {
                /*if (components[i] instanceof JButton) {
                JButton button = (JButton) components;
    if (button.hasFocus()) { // from which component
    String btnMane = button.getName();
    } else if (components[i] instanceof JComboBox) {
    } else if (components[i] instanceof JTextField) {
    } else if (components[i] instanceof JTable) {
    } else if (components[i] instanceof JScrollPane) {
    } else */
    /*if (components[i] instanceof JPanel) {
    JPanel pnl = (JPanel) components[i];
    compName = pnl.getName();
    compName = pnl.getUIClassID();
    compName = pnl.toString();
    int n1 = 0;
    n1 = pnl.getComponentCount();
    if (n > 0) {
    Component[] components1 = pnl.getComponents();
    String compName1 = "";
    for (int i1 = 0, l1 = components1.length; i1 < l1; i1++) {
    /*if (components[i] instanceof JButton) {
    JButton button = (JButton) components[i];
    if (button.hasFocus()) { // from which component
    String btnMane = button.getName();
    } else if (components[i] instanceof JComboBox) {
    } else if (components[i] instanceof JTextField) {
    } else if (components[i] instanceof JTable) {
    } else if (components[i] instanceof JScrollPane) {
    } else */
    /*if (components1[i1] instanceof JPanel) {
    JPanel pnl1 = (JPanel) components1[i1];
    compName1 = pnl1.getName();
    compName1 = pnl1.getUIClassID();
    compName1 = pnl1.toString();
    pnl1 = null;
    pnl = null;
    internalFrame.removeAll();
    Runtime runtime = Runtime.getRuntime();
    long total = runtime.totalMemory();
    long free = runtime.freeMemory();
    long max = runtime.maxMemory();
    long used = total - free;
    System.out.println("Remove new JInternalFrame : " + Math.round(max / 1e6) + " MB available");
    System.out.println("Remove new JInternalFrame : " + Math.round(total / 1e6) + " MB allocated");
    System.out.println("Remove new JInternalFrame : " + Math.round(free / 1e6) + " MB free");
    System.out.println("Remove new JInternalFrame : " + Math.round(used / 1e6) + " MB used");
    hint inside remWins, plus minus citiBus                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Smart collection shows as not in a collection

    I am hoping my 100% answered questions are kept up with this one :O)
    I am trying to do a collection that contains all images that are not in a collection (including smart collections).
    1) Is this possible?
    I ask because logic says that if the search finds images then puts them in this collection, that wil mean that they are no longer without a collection, a bit of a continuous circle!
    2) I have tried to do the above with what I thought was sucess, 6000 of my 11,000 images were found which I initially thought to be correct. However on thorough investigation I have found that images in SMART collections are classed as not being in a collection. I proved this by right clicking the image and selecting "Show in Collection" and every smart collection image always returns the greyed out "Not in a collection".
    By the way, the search I set up was:
    Collection.....Doesn't contain......a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z
    Any ideas?

    Thanks for the answers.
    Its a shame LR seems to class smart collections as more of a query or a search rather than an  "automatic" collection. It would be nice to filter to show all photos NOT in any type of collection, which would make deleting images easier (for me anyway).
    An example was I have some poor quality photos which I deleted (I don't want to  bloat my catalog!) only to find out later that they belonged to a smart collection which had a particular significance which I wanted to keep. I had right clicked on them to see if they were in a collection, which showed as none.
    This means that in my type of workflow I can sadly not use smart collections and all of their advantages.
    Hopefully in LR 3.0?

  • Garbage collection – local variable

    I have a doubt in garbage collection.
    Please look int the below code.
    I hope that even if i didn't make myLocalVar = null; , i believe that garbage collection happens immediately,
    Please let me know am i right ?
    void method() {
      MyClass myLocalVar = null;
      try {
        myLocalVar = get_reference_to_object();
        //.. do more here ...
      } finally {
        if (myLocalVar != null) {
          myLocalVar.close(); // it is resource which we should close
        myLocalVar = null; // THIS IS THE LINE I AM TALKING ABOUT
    }

    JEisen wrote:
    es5f2000 wrote:
    I'm pretty sure that there's no guarantee that GC will run at termination time. That's what causes the issue with finalize(). It is theoretically possible to start a program, run it, and cleanly terminate it without getting a GC.True. I meant more that memory will be freed when the program terminates, not necessarily garbage collected. :)
    I just read about the finalize() gotcha -- never knew that. So is it possible for a program to exit without releasing I/O resources if they were being closed in finalize()?Yes and no.
    The basic answer is yes, however when the VM quits from an OS level the handles/locks/etc that were being used by the VM will, god willing, be released.
    A better example though is something like JDBC where you have remote resources waiting on a signal to be released. Having clean up code in finalize could well never be called and in that case the remote resources would be held on to.

Maybe you are looking for