Memory Leak - GC scope

Hi,
I have a pervasive memory leak in my server application. I have used JProfiler to track it down and indeed after 10 or so hours of execution I can see clearly the Java classes which are increasing in count. For my application they are (in order of total memory size used):
byte[]
<class>[]
String
QueueLink(custom class)
Knowing where my system leaks memory is nice, but on trawling the code I cannot really see why it really leaks and therefore am unable to fix it. One thing I do not quite get about Java is the garbage collector scope. If I have a loop, like so below:
while (true)
Object o = new Object();
...do something with 'o'
then for every loop iteration 'o' is initialize to a new Object. But the old reference of o (from the previous iteration) is for all intents a purposes gone. BUT, does this get collected by the GC or does it only get collected when the scope leaves the while loop? If the latter then UNTIL the loop terminates I will "leak" memory, which would go part way to explaining my problem.
Any ideas, any suggestions on how I can fix my leak(s)?
Regards,
NC

... then for every loop iteration 'o' is initializeto a
new Object. But the old reference of o (from the
previous iteration) is for all intents a purposes
gone. BUT, does this get collected by the GC ordoes
it only get collected when the scope leaves thewhile
loop?It has nothing to do with variable scope in this
case. The object that 'o' used to reference is no
longer reachable (unless something else in that loop
made another reference to it, such as adding it to a
collection which is still reachable), so it is
eligible for GC.The question is, will it be GCed.
I remember hearing a few years back that the VM--or certain VMs--might not collect any eligible local variables until after the method completes, or something to that effect. If so, then an infinite while(true) { new Object(); } loop will exhaust the heap rather quickly. Even if that was true back then, I doubt it's true of Sun's VM today.

Similar Messages

  • How Do I identify a Memory Leak?

    I know this is not enought information but...
    My application used 3 hashtables in a Data object to store application data. I retrive this data from an XML file. I also download XML and merge it into andother XML file. Some of these hashtables contain object that contain more hashtables.
    I am trying to use JProbe Profiler to find the leak. I notice the memory increases when I load the data into objects and put them into hash tables. I also notice an increase when I am merging newly downloaded XML into the current XML data. I am useing Nodelists and NOdes to get the data.
    Does anyone have any tips or suggestion on how to find a memory leak?
    Thank you,
    Al

    7 MB of XML file, loaded into a DOM? You realize, of
    course, that DOMs are data structures that take up
    memory, too, right?Yes I do. I load it into DOM then go through the Document and put the XML data into a custom file format (seialized objects). The data is sent from the server in the form of XML.
    There's your problem. If you load X MB into memory
    and keep it around as long as your application is
    running, that's not necessarily a "leak". Yeah I realized this but it seems that if I load 7MB of my objects into hashtables my memory usage shouldn't increase by 30MB. I just assumed it would stay around 10MB.
    The real issue is trading memory for CPU. If keeping
    them in memory is crashing your app with OOM errors,
    by all means just keep those objects in memory for as
    long as you need them and then let the GC clean them
    up. Don't put them in a Map, just let them have a
    narrow method scope. Recreate them every time you
    need them. Yes I'm beginning to see the light.
    I'm sure you're thinking, "But recreating them will
    cost CPU and slow down my app!" Yes, that's why it's
    a tradeoff between memory and CPU.
    Do you really need the whole document in memory at
    once? If you're just cherry picking a few values out
    of it, maybe you can use a SAX parser instead of a
    DOM.
    No I don't need all that data at once.
    >
    Either you're screwed or you need to rethink this.
    You'd better hope that it's really not needed at
    every moment for every client.After rethinking, I'm going to keep the serialized data in the file until I need it. Rather than searching through a hashtable for the object I want I will search the file.
    What are your JVM settings for -Xms and -Xmx? Maybe
    increasing those will do the trick.I did increase them and it helped a little, but I can still get a OutOfMemoryError if I try.
    Are you sure these are the culprits? Have you
    profiled the app to see if there are other sources of
    leaks?Yes I have been profiling the application. It seems that there is a memory leek. I am just having trouble identifing it. I know the memory increases at 2 points. When I load the XML data into the DOM and when I load the DOM into my Custom object and then into the Hashtables.
    Last resort? Buy more physical memory. It's cheap.I think I am going to keep unused data out of memory and access it form a file. After I make this change I think my memory usage will drop alot. I will profile again after I have this change made to see if there is a memory leak.
    Thanks for you help,
    Al

  • Memory leak in GUI ??

    hey all...
    i have developed my java app.
    if i leave ir running overnight and come back to it, it size is around 100,000k !
    if i minimise the main window for my app (into the taskbar) and then click the taskbar to send it back onto the screen, it returns to the normal 10,000k....
    why is this..?
    is their some sort of memory leak in my gui?
    do i need to code in some sort of refresh() for the gui ?
    ive gone through all my code and checked for other causes of a memory leak and im fairly sure its the gui..
    thanks...

    Thanks for a good addition. I started to take care on these things when I wanted to make my classes reusable by me and by other people - like creating a library. There are situations you can't be sure your observable object will get out of scope. And - sometimes maintaining code for removing a listener takes less effort then maintaining that observable object will be garbage collected! Sometimes an opposite however.
    Denis Krukovsky
    http://dotuseful.sourceforge.net/

  • Help with Java Memory Leak in URLConnection

    Hi everyone,
    I can't seem to find the memory leak in the below code, if anyone could help, i would greatly appreciate it. The jist of the code is: I open up a URLConnection to update a ColdFusion page that takes in URL parameters passed in my URL. Then, I get the response. I also check for proxy usage and take that into consideration when making the connection.
    I have one class to handle the Connections, Connect.java:
         * Connection using Username and Password, as well as boolean option to use Basic Proxy Authentication
         public Connect(String pHost, String pPort, String urlString,
                             String pUsername, String pPassword, boolean useProxy) {
              this.pHost = pHost;
              this.pPort = pPort;
              this.urlString = urlString;
              this.pUsername = pUsername;
              this.pPassword = pPassword;
              this.useProxy = useProxy;
         * Get the Input Stream from the Connection given a specific URL
         public java.io.InputStream getInputStream(String urlString) {
              if (urlString == null) urlString = this.urlString;
                 exDialog = new ExceptionDialog(new javax.swing.JFrame());
              try {
                   String auth = "";
                   if (useProxy) {
                        System.getProperties().put("proxySet", "true");
                        System.getProperties().put("proxyHost", pHost);
                        System.getProperties().put("proxyPort", pPort);
                        String authString = "";
                        if (pUsername != null && pUsername != "") authString = pUsername + ":";
                        else authString = "username:";
                        if (pPassword != null && pPassword != "") authString = authString + pPassword;
                        else authString = authString + "password";
                        auth = "Basic " + new sun.misc.BASE64Encoder().encode(authString.getBytes());
                   java.net.URL url = new java.net.URL(urlString);
                   java.net.HttpURLConnection conn = (java.net.HttpURLConnection)url.openConnection();
                   if (useProxy) conn.setRequestProperty("Proxy-Authorization", auth);
                   conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)");
                   conn.setDoInput( true );
                   conn.setDoOutput( true );
                   conn.connect();
                   return conn.getInputStream();
              } catch (java.io.IOException ioe) {
                   exDialog.showForThrowable(ioe.toString(),ioe);
                   return null;
         }I call the code in Download.java:
    Connect conn = new Connect(sm.pHost, sm.pPort, null, sm.pUser, sm.pPass, sm.useProxy);
    new BufferedReader(new InputStreamReader(conn.getInputStream(sUpdateURL)));
    in.close();For some reason, as I loop through this call, the memory footprint of my program grows through every iteration, eventually resulting in a Java Out of Memory error. I can't track the leak down and it's fairly frustrating. If anyone can help, that would be greatly appreciated. Thanks!

    One place there might be a memory leak is in the line
    exDialog = new ExceptionDialog(new javax.swing.JFrame());Even though the JFrame object goes out of scope when the ExceptionDialog method returns, JFrames stay around until they are closed, even though in this case it isn't even shown on the screen.

  • Possible memory leak in JSF � help needed

    Hi,
    We are developing a JSF application using the following:
    SUN JSF 1.1_02-b08
    Tomahawk 1.1.3
    Tomcat 5.5
    Our application includes pages with lists; these lists are held and extracted from backing beans.
    We are using these beans in request scope with <t:saveState> tag (to avoid holding the lists in the session all the time).
    We tested the application using JProbe and found out that each bean that was used in the saveState was added to the view (to the session) , each time we entered the page , and the bean was not released until the end of the session (instead of only one instance of the backing bean).
    After I found this problem, I added the following context params to the web.xml:
    com.sun.faces.NUMBER_OF_VIEWS_IN_SESSION = 1 (instead of the default 15)
    com.sun.faces.NUMBER_OF_VIEWS_IN_LOGICAL_VIEW_IN_SESSION = 1 (instead of the default 15)
    We tested the application again, and now no unnecessary instances of the beans were held in the session (in the view).
    BUT , now when we use the browser �Back� button, and returning to a page with a list, when selecting an item from the list, no action is performed (the list in the server side does not exist).
    My questions are:
    1)What is the meaning (difference) of each of the context param : NUMBER_OF_VIEWS_IN_SESSION , NUMBER_OF_VIEWS_IN_LOGICAL_VIEW_IN_SESSION
    2)What are the recommended values for these parameters, to minimize session memory, and to enable the usage of the browser �Back� button.
    Thank you all,
    Lior.

    Me too.
    Please somebody knows how can we avoid memory leak problems in JSF 1.1 ?
    Thansk in advanced

  • Memory Leaking message when run the log in page in Jdev 11.1.2

    Hi
    I am re design our 10g application in Jdev 11.1.2, I am using .jsf and ADF business component.
    at the moment, the project has only two pages. login and home page.
    when I run the login page, I see the message below. this is happening during the deployment process to the embeded weblogic
    <ADFContext> <getCurrent> Automatically initializing a DefaultContext for getCurrent.
    Caller should ensure that a DefaultContext is proper for this use.
    Memory leaks and/or unexpected behaviour may occur if the automatic initialization is performed improperly.
    This message may be avoided by performing initADFContext before using getCurrent().
    For more information please enable logging for oracle.adf.share.ADFContext at FINEST level.
    Anyone know why?
    thanks

    Hi Timo
    Thanks for your reply, I read the thread you pointed to.
    however, I am not sure my is related to the case mentioned. I am re design the application from scratch in Jdev 11.1.2, and my adfc-config.xml is as simple as this:
    <?xml version="1.0" encoding="windows-1252" ?>
    <adfc-config xmlns="http://xmlns.oracle.com/adf/controller" version="1.2">
    <view id="Login">
    <page>/commom/Login.jsf</page>
    </view>
    <view id="home">
    <page>/commom/home.jsf</page>
    </view>
    <control-flow-rule id="__2">
    <from-activity-id>*</from-activity-id>
    <control-flow-case id="__3">
    <to-activity-id>Login</to-activity-id>
    </control-flow-case>
    </control-flow-rule>
    <control-flow-rule id="__4">
    <from-activity-id>Login</from-activity-id>
    <control-flow-case id="__5">
    <from-outcome>success</from-outcome>
    <to-activity-id>home</to-activity-id>
    </control-flow-case>
    </control-flow-rule>
    <managed-bean id="__1">
    <managed-bean-name>backing_login</managed-bean-name>
    <managed-bean-class>com.mycompany.view.backing.login</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    </adfc-config>
    also, I am using a session filter registered in web.xml --- basically, if the page is not Login.jsf then redirect to Login.jsf page. but even though I removed the session filter.java from the web.xml , it still show the message.

  • Memory leak with jsp and beans

    The application we have created has one particular page that is designed to stay up in the browser and refresh with new information from database queries once every 60 seconds. Running with Tomcat3.2.1 and IE5.5
    The problem is that the memory usage of java.exe continues to grow until the machine crashes from out of memory. It does take more than 24 hours to crash.
    Things I have tried to do to track down the problem or eliminate the problem.
    - I have explicitly set the scope of the beans to "page"
    - I have watched the DatabaseAccess.class (the beans are all extended from this class) and put in code to watch how many instantiations of the class are made and subsequently garbage collected. This appears to be where the memory leak may reside - hundreds of instantiations from some other source than the page I am displaying.
    - the top frame makes database queries for security and display of a menu system dependant upon security clearance. It does not set any time for refresh (refresh == 0). Nor does it explicitly set a scope for the beans.
    - I have run a different jsp engine to see if this was directly related to Tomcat - same problem with resin2.0.0
    The main jsp page that is in the bottom section of the page has the following code:
    ** only the relevant lines are included here
    <%@ include file="../../common.jsp" %>
    <%
         refresh=60;
    %>
    <head>
    <%@ include file="../../meta_head.jsp" %>
    </head>
    <body bgcolor="#FFFFFF" text="#003399" link="#660099" vlink="#990099" alink="#006666" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
    <%@ include file="../../access.jsp" %>
    <%@ include file="../../page_title.jsp" %>
    <jsp:useBean id="Line" class="jsp.Line" scope="page" />
    <jsp:useBean id="Machine" class="jsp.Machine" scope="page"/>
    <jsp:useBean id="Alarm_log" class="jsp.Alarm_log" scope="page"/>
    contents of meta_head.jsp
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <META HTTP-EQUIV= "expires" content = "0">
    <META HTTP-EQUIV="Pragma" CONTENT="no_cache">
    <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache" forua="true">
    <META NAME="robots" content="NOINDEX,NOFOLLOW">
    <%
    if (refresh > 0)
    %>
    <meta http-equiv="Refresh" content="<%= refresh %>">
    <%
    If anyone has some suggestions on how to trap this memory leak, it would be terrific. Or, some other things to try to stop the instantiation of the DatabaseAccess object (perhaps setting the scope of the beans in the header to "session" or "application"?).
    Thanks in advance.
    Roberta

    jsp:useBean tags scope declaration :
    page = Create a new instance on each load.
    session = Load instance from the session, if not there, create one
    application = Load instance from the ServletContext, if not there, create one.
    Not sure how you are populating the data variables, but make sure you are closing all ResultSet, (Prepared)Statement, and Connection objects.

  • I think I've got a memory leak and could use some advice

    We've got ourselves a sick server/application and I'd like to gather a little community advice if I may. I believe the evidence supports a memory leak in my application somewhere and would love to hear a second opinion and/or suggestions.
    The issue has been that used memory (as seen by FusionReactor) will climb up to about 90%+ and then the service will start to queue requests and eventually stop processing them all together. A service restart will bring everything back up again and it could run for 2 days or 2 hours before the issue repeats itself. Due to the inconsistant up time, I can't be sure that it's not some trouble bit of code that runs only occasionally or if it's something that's a core part of the application. My current plan is to review the heap graph on the "sick" server and look for sudden jumps in memory usage then review the IIS logs for requests at those times to try and establish a pattern. If anyone has some better suggestions though, I'm all ears! The following are some facts about this situation that may be usefull.
    The "sick" server:
    - CF 9.0.1.274733 Standard
    - FusionReactor 4.0.9
    - Win2k8 Web R2 (IIS7.5)
    - Dual Xeon 2.8GHz CPUs
    - 4GB RAM
    JVM Config (same on "sick" and "good" servers):
    - Initial and Max heap: 1536
    -server -Xss10m -Dsun.io.useCanonCaches=false -XX:PermSize=192m  -XX:MaxPermSize=256m -XX:+UseParNewGC -Xincgc -Xbatch -Dcoldfusion.rootDir={application.home}/../ -Dcoldfusion.libPath={application.home}/../lib -Dcoldfusion.dotnet.disableautoconversion=true
    What I believe a "healthy" server graph should look like (from "good" server):
    And the "sick" server graph looks like this:

    @AmericanWebDesign, I would concur with BKBK (in his subsequent reply) that a more reasonable explanation for what you’re seeing (in the growth of heap) is something using and holding memory, which is not unusual for the shared variables scopes: session, application, and/or server. And the most common is sessions.
    If that’s enough to get you going, great. But I suspect most people need a little more info. If this matter were easy and straightforward, it could be solved in a tweet, but it’s not, so it can’t.
    Following are some more thoughts, addressing some of your concerns and hopefully pointing you in some new directions to find resolution. (I help people do it all the time, so the good news is that it can be done, and answers are out there for you.)
    Tracking Session Counts
    First, as for the observation we’re making about the potential impact of sessions, you may be inclined to say “but I don’t put that much in the session scope”. The real question to start with, though, is “how many sessions do you have”, especially when memory use is high like that (which may be different than how many you have right now). I’ve helped many people solve such problems when we found they had tens or hundreds of thousands of sessions.  How can you tell?
    a) Well, if you were on CF Enterprise, you could look at the Server Monitor. But since you’re not, you have a couple of choices.
    b) First, any CF shop could use a free tool called ServerStats, from Mark Lynch, which uses the undocumented servicefactory objects in CF to report a count of sessions, overall and per application, within an instance. Get it here: http://www.learnosity.com/techblog/index.cfm/2006/11/9/Hacking-CFMX--pulling-it-all-togeth er-serverStats . You just drop the files (within the zip) into a web-accessible directory and run the one CFM page to get the answer instantly.
    c) Since you mention using FusionReactor 4.0.9, here’s another option: those using FR 4 (or 4.5, a free update for you since you’re on FR 4) can use its available (but separately installed) FusionReactor Extensions for CF, a free plugin (for FR, at http://www.fusion-reactor.com/fr/plugins/frec.cfm). It causes FR to grab that session count (among many other really useful things about CF) to log it every 5 seconds, which can be amazingly helpful. And yes, FREC can grab that info whether one is on CF Standard or Enterprise.
    And let’s say you find you do have tens of thousands of sessions (or more). You may wonder, “how does that happen?“ The most common explanation is spiders and bots hitting your site (from legit or unexpected search engines and others). Some of these visit your site perhaps daily to gather up the content of all the pages of your site, crawling through every page. Each such page hit will create a new session. For more on why and how (and some mitigation), see:
    http://www.carehart.org/blog/client/index.cfm/2006/10/4/bots_and_spiders_and_poor_CF_perfo rmance
    About “high memory”
    All that said, I’d not necessarily conclude so readily that your “bad” memory graph is “bad”. It could just be “different”.
    Indeed, you say you plan to “look for sudden jumps in memory usage“, but if you look at your “bad” graph, it simply builds very slowly. I’d think this supports the notion that BKBK and I are asserting: that this is not some one request that “goes crazy” and uses lots of memory, but instead is the “death by a thousand cuts” as memory use builds slowly.  Even then, I’d not jump at a concern that “memory was high”.
    What really matters, when memory is “high” is whether you (or the JVM) can do a GC (garbage collection) to recover some (or perhaps much) of that “high, used memory”. Because it’s possible that while it “was” in use in the past (as the graph shows), it might no longer be “in use” at the moment . 
    Since you have FR, you can use its “System Metrics page” to do a GC, using the trash can in the top left corner of the top right-most memory graph. (Those with the CFSM can do a GC on its “Memory Usage Summary” page, and SeeFusion users can do it on its front page.)
    If you do a GC, and memory drops q lot, then you had memory that “had been” but no longer ”still was” in use, and so the high memory shown was not a problem. And the JVM can sometimes be lazy (because it’s busy) about getting to doing a GC, so this is not that unusual. (That said, I see you have added the Xincgc arg to your JVM. Do you realize that tells the JVM not to do incremental GCs? Do you really want that? I understand that people trade jvm args like baseball cards, trying to solve problems for each other, but I’d argue that’s not the place to start. In fact, rarely do I find myself that any new JVM args are needed to solve most problems.)
    (Speaking of which, why did you set the – xss value? And do you know if you were raising or lowering it form the default?)
    Are you really getting “outofmemory” errors?
    But certainly, if you do hit a problem where (as you say) you find requests hanging, etc., then you will want to get to the bottom of that. And if indeed you are getting “outofmemory” problems, you need to solve those. To confirm if that’s the case, you’ll really want to look at the CF logs (specifically the console or “out” logs). For more on finding those logs, as well as a general discussion of memory issues  (understanding/resolving them), see:
    http://www.carehart.org/blog/client/index.cfm/2010/11/3/when_memory_problems_arent_what_th ey_seem_part_1
    This is the first of a planned series of blog entries (which I’ve not yet finished) on memory issues which you may find additionally helpful.
    But I’ll note that you could have other explanations for “hanging requests” which may not necessarily be related to memory.
    Are you really getting “queued” requests?
    You also say that “the service will start to queue requests and eventually stop processing them all together”. I’m curious: do you really mean “queuing”, in the sense of watching something in CF that tells you that? You can find a count of queued requests, with tools like CFSTAT, jrun metrics, the CF Server Monitor, or again FREC. Are you seeing one of those? Or do you just mean that you find that requests no longer run?
    I address matters related to requests hanging and some ways to address them in another entries:
    http://www.carehart.org/blog/client/index.cfm/2010/10/15/Lies_damned_lies_and_CF_timeouts
    http://www.carehart.org/blog/client/index.cfm/2009/6/24/easier_thread_dumps
    Other server differences
    You presented us a discussion of two servers, but you’ve left us in the dark on potential differences between them. First, you showed the specs for the “sick” server, but not the “good” one. Should we assume perhaps you mean that they are identical, like you said the JVM.config is?
    Also, is there any difference in the pattern of traffic (and/or the sites themselves) on the two servers? If they differ, then that could be where the explanation lies. Perhaps the sites on one are more inclined to be visited often by search engine spiders and bots (if they sites are more popular or just have become well known to search engines). There are still other potential differences that could explain things, but these are all enough to hopefully get you started.
    I do hope that this is helpful. I know it’s a lot to take in. Again, if it was easier to understand and explain, there wouldn’t be so much confusion. I do realize that many don’t like to read long emails (let alone write them), which only exacerbates the problem. Since all I do each day is help people resolve such problems (as an independent consultant, more at carehart.org/consulting), I like to share this info when I can (and when I have time to elaborate like this), especially when I think it may help someone facing these (very common) challenges.
    Let us know if it helps or raises more questions. :-)
    /charlie

  • Memory Leak in WindowsTreeUI?

    I'm hunting memory leaks in my app (of which there are alarmingly many), and have just stumbled across one which appears to be a bug in the class com.sun.java.swing.plaf.windows.WindowsTreeUI
    When the tree is populated, each treenode contains a reference to a node in our own rather large data structure.
    When we close the application-level model, we also call tree.setModel(null) and expect the tree to lose all its references. From a memory management point of view, it is important that the entire old model goes out of scope before we start loading a new one.
    If the tree is visible, everything works as expected.
    But if the tree is not visible (but still in scope) e.g. because we overlay a component in a JLayeredPanel, we get some dangling references in the (private) drawingCache member of the WindowsTreeUI class. And a single dangling reference keeps the whole caboodle in scope until something else comes along.
    I have a bad feeling I'm going to have code around painfully by substitiuting in some lite dummy model and then modifying all the event handlers that get confused as a result.
    Or does anyone have a bright idea how I can persuade the drawingCache to flush itself (presumably this only happens on windows)?
    Ian

    I also had a similar problem. My app has a number of large jtrees (200-300 nodes) with other data objects attached. I was doing a simple null of the JTree thinking that it would be GC'd. Using the NetBeans profiler I could see that it never went away. I found one location where I was temporarily hang on to node references within Swing controls. I've eliminated those. I then released the listeners I specifically assigned. There seems to be other listeners hanging on to node references. I have found little in the way of documentation or advice on how to clean these up. As a work around, when I'm done with a JTree, I traverse the nodes bottom up and remove each node from its parent (DefaultMutableTreeNode - removeNodeFromParent() ). This seems to work. The NetBeans profiler shows the vast majority of the JTree objects as GC'd. I'm sure this is not a perfect solution but it seems to be serviceable.
    I would appreciate hearing about any experiences in getting JTrees to GC.

  • Memory Leak with JDialog in Java 1.4.2_07

    Hello!
    All books I have read say to close a JDialog, it is enough to call the Method "dispose". Now I have written my first applikation an with every Dialog I open, the Software needs more RAM. With every Dialog I open, my software needs 1,5 MB RAM.
    I can`t reuse the Dialogs, because the user needs to look at view at the same time
    The Question is, how to close a JDialog correct that the GC can clean all Objects in RAM.
    Here are my Example Programm where you can view the differences. I tryed a view things out. With every Dialog the software needs xxx kb of RAM (its only a little example).
    Look at the Task Manager to look the real RAM needage.
    Thanks for Help
    Rainer
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    public class TestRAMUsage extends JFrame {
         private JPanel jContentPane = null;
         private JMenuBar jJMenuBar = null;
         private JMenu fileMenu = null;
         private JMenuItem exitMenuItem = null;
         private JButton jB_showandclose_normal = null;
         private JButton jB_showandclose_advanced = null;
          * This method initializes jB_showandclose_normal     
          * @return javax.swing.JButton     
         private JButton getJB_showandclose_normal() {
              if (jB_showandclose_normal == null) {
                   jB_showandclose_normal = new JButton();
                   jB_showandclose_normal.setBounds(new java.awt.Rectangle(43,30,214,18));
                   jB_showandclose_normal.setText("open/close Dialog normal x 50");
                   jB_showandclose_normal.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             for (int i = 0; i < 50; i++) {
                                  TestDialog td = new TestDialog();
                                  td.show();
                                  td.close_normal();
                             System.gc();
              return jB_showandclose_normal;
          * This method initializes jB_showandclose_advanced     
          * @return javax.swing.JButton     
         private JButton getJB_showandclose_advanced() {
              if (jB_showandclose_advanced == null) {
                   jB_showandclose_advanced = new JButton();
                   jB_showandclose_advanced.setBounds(new java.awt.Rectangle(16,76,260,18));
                   jB_showandclose_advanced.setText("open/close Dialog advanced x 50");
                   jB_showandclose_advanced.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             for (int i = 0; i < 50; i++) {
                                  TestDialog td = new TestDialog();
                                  td.show();
                                  td.close_advanced();
                             System.gc();
              return jB_showandclose_advanced;
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              TestRAMUsage application = new TestRAMUsage();
              application.show();
          * This is the default constructor
         public TestRAMUsage() {
              super();
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setJMenuBar(getJJMenuBar());
              this.setSize(300, 200);
              this.setContentPane(getJContentPane());
              this.setTitle("Application");
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(null);
                   jContentPane.add(getJB_showandclose_normal(), null);
                   jContentPane.add(getJB_showandclose_advanced(), null);
              return jContentPane;
          * This method initializes jJMenuBar     
          * @return javax.swing.JMenuBar     
         private JMenuBar getJJMenuBar() {
              if (jJMenuBar == null) {
                   jJMenuBar = new JMenuBar();
                   jJMenuBar.add(getFileMenu());
              return jJMenuBar;
          * This method initializes jMenu     
          * @return javax.swing.JMenu     
         private JMenu getFileMenu() {
              if (fileMenu == null) {
                   fileMenu = new JMenu();
                   fileMenu.setText("File");
                   fileMenu.add(getExitMenuItem());
              return fileMenu;
          * This method initializes jMenuItem     
          * @return javax.swing.JMenuItem     
         private JMenuItem getExitMenuItem() {
              if (exitMenuItem == null) {
                   exitMenuItem = new JMenuItem();
                   exitMenuItem.setText("Exit");
                   exitMenuItem.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             System.exit(0);
              return exitMenuItem;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class TestDialog extends JDialog {
         private static final long serialVersionUID = -4326706771573368209L;
         private JPanel jContentPane = null;
         private JButton jB_drucken = null;
         private JTextField jTF_hallo = null;
         private JButton jB_close = null;
          * This is the default constructor
         public TestDialog() {
              super();
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setSize(541, 255);
              this.setTitle("Speicher Dialog");
              this.setContentPane(getJContentPane());
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(null);
                   jContentPane.add(getJB_drucken(), null);
                   jContentPane.add(getJTF_hallo(), null);
                   jContentPane.add(getJB_close(), null);
              return jContentPane;
          * This method initializes jB_drucken
          * @return javax.swing.JButton
         private JButton getJB_drucken() {
              if (jB_drucken == null) {
                   jB_drucken = new JButton();
                   jB_drucken.setBounds(new java.awt.Rectangle(45, 88, 211, 19));
                   jB_drucken.setText("Sag Hallo Welt");
              return jB_drucken;
          * This method initializes jTF_hallo
          * @return javax.swing.JTextField
         private JTextField getJTF_hallo() {
              if (jTF_hallo == null) {
                   jTF_hallo = new JTextField();
                   jTF_hallo.setBounds(new java.awt.Rectangle(269, 88, 228, 19));
              return jTF_hallo;
          * This method initializes jB_close
          * @return javax.swing.JButton
         private JButton getJB_close() {
              if (jB_close == null) {
                   jB_close = new JButton();
                   jB_close.setBounds(new java.awt.Rectangle(196, 179, 109, 22));
                   jB_close.setText("Schlie�en");
                   jB_close.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             try {
                                  // setVisible(false);
                                  dispose();
                                  removeAll();
                                  // getContentPane().removeAll();
                                  // finalize();
                             } catch (Throwable e1) {
                                  // TODO Auto-generated catch block
                                  e1.printStackTrace();
              return jB_close;
          * Dispose the Dialog
         public void close_normal() {
              dispose();
          * Set all Variables to null
          * Remove all Container
          * dispose the Dialog
          * and finalize it!
         public void close_advanced() {
              // System.out.println(this.);
              dispose();
              // show();
              jContentPane = null;
              jB_drucken = null;
              jTF_hallo = null;
              jB_close = null;
              getContentPane().removeAll();
              removeAll();
              try {
                   finalize();
              } catch (Throwable e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    } // @jve:decl-index=0:visual-constraint="10,10"

    I have use Methods in some Software Produkts. But if your Software
    use 30 MB in RAM the Runtime classes say 12 MB used. I don`t think
    that this works hereThe 12 MB is the memory used of the available 30 MB memory available. Once the VM get its memory from the OS, it does not have to return the memory back to the OS right away.
    By calling System.gc() does nt guarentee the garbage collector to be activated right away. you are just asking the garbage collector to run when it get a chance. Since the emeory is not near the max memory available...the gc is likely not going to run. Futhermore, if your application is running..the gc is likely wont run, unless memory is needed when you reach the max limit.
    because the user want to view at more than one Dialog at the same
    timeunderstandable..i just hope the 50 dialogs is just for testing the memory. i can't imagine any user would want to open 50 dialog at the same time =)
    And the other is, that the Variables in the Dialog class wouldn`t clean
    in RAM (that was the reason to set all to null!)why would it not be? When you dispose the dialog, the object will be null out..so when the garbage collector kick in, it will reclaim the memory. Now, if you have references to object in the dialog, that reference will be null out as well..the object may still exist (by having another live object having a reference to it)...the garbage collector would reclaim the dialog memory..but not the "live" object that the dialog has reference to.
    I ran the application..testing both button.
    The top button..there were little memory consumption..the second button consume a little memory bit-by-bit. I see no memory leak here. What happens is you called GC() 50 times..but it will only run one time when it get a chance...by nulling out the variables, and calling finalize()..it actually slow down the garbage collecting...that's why you should not even obther with having those two method. Furthermore, finalize method may not even be called.
    Memory leak occurs when you have a reference from an object still hanging around, but that object is no longer needed. This is a design issue.
    example
    public class A{
        Item item = new Item();
        public void getItem(){ return item; };
    public class B{
        Item item;
        public B(A a){
            item = a.getItem();
    A a = new A();
    B b = new B(a);
    a = null;when a is null out..the item reference is null, but the actual object still exist and 'b' has a reference to it. so by nulling out those object does not mean you just got rid of the object. it's better to let the object scope run out..and the garbage collector to collect it.. When you null out the object, you could accidentally null out an object that some other object may be using.

  • What is memory leak in Java context?

    I am looking for a precise definition here...

    If you are looking for HOW a memory leak can show up in java, here are a few examples:
    A stack implemented on an array can have a memory leak if the object's position in the array isn't set to null after the object is popped off the stack (I think I first saw that in "effective java", by joshua bloch, if you want to look more into that).
    Another way: interning strings to the jvm can cause a memory leak, because once a string is interned, it is stuck there forever, even if all other references to the string are gone, and the string will never again be used.
    Furthermore, any flyweight concept that doesn't have a strategy for pruning away unused object (objects with 0 external remaining references) will be a memory leak of a sort.
    Hash maps are another place you can run into this problem. They may hold the only reference to both objects of a pair, and hence, since the key exists nowhere else, the pair is basically useless, but the map does prevent them from being garbage collected.
    What's the common link? The all have to do with some data structure or another maintaining obsolete references to objects. Since objects can't go out of scope if they are stored in a data structure that doesn't go out of scope, they cannot be garbage collected.
    - Adam

  • Memory Leak in 8.1 sp5

    Has anyone experienced a memory leak when a webservice (jws)
    returns a large string (5-15 Meg). The string itself is a XML. When the webservice is called numerous times it eventually runs out of memory.

    We have seen exactly the same behaviour you just described, also related to webservices that return large XML response documents. Initially we had the test console enabled, which consumed all the memory rapidly. Once this was disabled, we've been seeing the exception messages that you've been getting. We did have an issue where the JVM was configured with too much memory (sounds counter intuitive), and we found the max JVM size should be less than 2MB (we're now using 1.3MB). This reduce the frequency of the error occuring, but it does still occasionally happen.
    I did some testing where I watched the memory used by weblogic when returning a large XML document. The XML document size was around 8MB when saved as a txt file. From the weblogic console server->monitor->performance page, the memory consumed by weblogic when returning this XML document was much larger than I expected. In fact weblogic used about 100MB of memory and the memory graph went up very steeply when returning this document. I adjusted my JVM memory settings and found that if I had less than approximately 80MB of free memory, then my webservice couldn't return this large XML response document without getting the OutOfMemory error. This test was done using a weblogic server that had just booted up and so had no scope for garbage collection of memory.

  • Listener memory leaks

    Just noticed these warnings in my Tomcat log files.
    Not sure if they are cause for concern or if they indicate some mis-configuration on my side. Maybe some from the Oracle APEX team can take a look at it. Thanks.
    01-Dec-2014 17:38:25.924 WARNING [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [apex] appears to have started a thread named [UCP-worker-thread-24] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
    sun.misc.Unsafe.park(Native Method)
    java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
    java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
    java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    java.lang.Thread.run(Thread.java:745)
    01-Dec-2014 17:38:25.928 SEVERE [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [apex] created a ThreadLocal with key of type [org.apache.xmlbeans.impl.store.CharUtil$1] (value [org.apache.xmlbeans.impl.store.CharUtil$1@7de8083f]) and a value of type [java.lang.ref.SoftReference] (value [java.lang.ref.SoftReference@4f4bdbe7]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
    01-Dec-2014 17:38:25.928 SEVERE [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [apex] created a ThreadLocal with key of type [org.apache.xmlbeans.XmlBeans$1] (value [org.apache.xmlbeans.XmlBeans$1@11a5e205]) and a value of type [java.lang.ref.SoftReference] (value [java.lang.ref.SoftReference@3faf4a40]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
    01-Dec-2014 17:38:25.929 SEVERE [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [apex] created a ThreadLocal with key of type [org.apache.xmlbeans.impl.schema.SchemaTypeLoaderImpl$1] (value [org.apache.xmlbeans.impl.schema.SchemaTypeLoaderImpl$1@23b147a]) and a value of type [java.util.ArrayList] (value [[java.lang.ref.SoftReference@133e6339]]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
    01-Dec-2014 17:38:25.929 SEVERE [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks The web application [apex] created a ThreadLocal with key of type [org.apache.xmlbeans.impl.store.Locale$1] (value [org.apache.xmlbeans.impl.store.Locale$1@2db50e91]) and a value of type [java.lang.ref.SoftReference] (value [java.lang.ref.SoftReference@680dac2d]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.

    There was another time that I dabbled in this idea.
    But it always comes back to objects cleaning up
    after themselves. Now if its not your code and you
    cant ensure good behavior, then perhaps there is
    cause. But I'd keep an assert and report the issue
    if I saw it trigger.What would fire the assert? The Listener will never be garbage collected while it is listening to something. I assume that you are talking about when the listener is a Swing Object like a JFrame. I don't really like to use gui components as listeners.
    If you have to write a clean up method, it kind of defeats the value of having automatic garbage collection to a degree. I like to be able to let my Objects just fall out of scope or just become unreachable when they are no longer needed without having to actively manage their deallocation.

  • Memory Leak: Do I need to explicitly free memory reference for collection?

    Hi,
    My web application uses JRockit JDK 1.4.2, Java Servlet, JSP &Struts. It is a clustered environment using WL 8.1 sp 4. I am investigating whether there are any memory leaks in the application & what are best practices to avoid leaks.
    A specific scenario is as follows:
    For an incoming request, the struts action class creates object �O� (of class A) and set �O� as a request attribute. This request attribute is used to display values on the JSP.
    Now, class A has a heavily nested structure: Class A has object of class B, where B has a HashSet of objects of type C and where C has an object of type D and E.
    Though I set this object �O� in request scope, do I need to explicitly nullify any of the references within object �O�? Can �not doing this� result in a memory leak?
    Thanks in advance,
    sjaiprakash

    jEnv->ReleaseStringUTFChars((jstring) jStr, str);free(str); //Is this line valid or outright wrong?Outright wrong.
    Another question is if ReleaseStringUTFChars actually frees str then will it set str to NULL?No, that's impossible by the semantics of C and C++.
    I guess not as we are not sending this pointer by reference.Exactly, so what you described is impossible. No need to ask really.
    My last question is if str is NULL then calling ReleaseStringUTFChars over it can cause any problem?How could it be null? If it comes from GetStringUTFChars that's impossible, and if it doesn't you don't have any business calling ReleaseStringUTFChars() on it, whatever its value.

  • Memory leaks

    Hi.
    I have a problem with the use of memory of my application. It has graph and pivottable components with bean classes that manages them. These classes are defined at level of session. It suposes that the instances of these classes will be erased by the garbage collector when i invalidate the session, but it doesn't happen and the memory remains busy.
    I see with jmap and jhat that there are some ADF classes that reference my instances and i don´t know how can i remove these references. I've tried to use FacesContext.release(), but i've had problems with its use and i don't known where i can use this method.
    Thanks!

    Hi.
    I still have the same problem, but now i've changed the numbers of instances that are saved into session scope. They are only 3, but the whole application is referenced by these three instances and take up much space.
    I've read that the static members may produce memory leaks, but all of my static members are generic types.
    I've tried to clean up my session scope by removing session attributes before finishing session.invalidate(). I do this into the HttpSessionListener.sessionDestroyed().
    ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
    HttpSession session = (HttpSession) ectx.getSession(false); //referencia
    try {
    ectx.redirect("login.jsp");
    FacesContext.getCurrentInstance().responseComplete();
    } catch (Exception ex) {
    try {
    ectx.redirect("error.jsp");
    Logger.getLogger(GestorCM.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
    } catch (IOException ex1) {
    Logger.getLogger(GestorCM.class.getName()).log(Level.SEVERE, ex1.getMessage(), ex1);
    try {
    session.invalidate();
    FacesContext.getCurrentInstance().release();
    auxiliar.MyHttpSessionListener.InnerFacesContext.setFacesContextAsCurrentInstance(null);
    } catch (Exception ex) {
    Logger.getLogger(GestorCM.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
    And HttpSessionListener.sessionDestroyed():
    String var = (String) session.getAttributeNames().nextElement();
    while (session.getAttributeNames().hasMoreElements()) {
    var = (String) session.getAttributeNames().nextElement();
    session.removeAttribute(var);
    I don't know if these things that i'm doing are correct and i don't know if i have to configurate something to avoid memory leaks in ADF.
    PD: I have problems with FacesContext.getExternalContext() after this.
    PD2: I'm working with Tomcat 7 and ADF 11.1.3.
    Thaks for all.

Maybe you are looking for

  • 0fi_gl_4 enhancement

    Hi Experts, I tried to enhance GL extractor. But once done, the FI doc number (BKPF -BELNR) is replaced by RBKP- BELNR. Not really able to figure out whats wrong in the code.. I am attaching the code...Can anyone please help..very urgent.. (Coding do

  • How to get the end of a download action ?

    Hello ! My web application must download zip file. Actually, the servlet's code for download is like this : response.setContentType("application/download"); response.setHeader("Content-Disposition","inline; filename=DownloadFile"); ServletOutputStrea

  • How to print sales order acknowledgement while printing purchase order

    how to print sales order acknowledgement while printing corresponding purchase order in me22n

  • Burning large QT .mov file to DL-DVD for backup

    Hello To be clear. I am not interested in creating a DL-DVD for playback on a set top DVD player connected to a television. Rather, I haver a 6+GB .mov file that I would prefer to keep intact and burn to a DL-DVD. I need to do this mainly for backup

  • Can a script run faster?

    I've written a script that uses Adobe Soundbooth to compile and manipulate audio clips. Generating an 8 minute track via the script, however, takes about 5+ minutes. (Soundbooth must import and manipulate the files 1 by 1). Furthermore, during this t