Finalize prevents "resource leak"?

As far as I can tell, " +Effective Java+ " (by Joshua Bloch) is the most recommended Java text. Therefore, I am assuming the author is credible, maybe on par with the best on this forum. Then, here is a quote from the book:
".... there is a severe performance penalty for using finalizers... So what should you do instead of writing a finalizer for a class whose objects encapsulate resources that require termination, such as files or threads? Just provide an explicit termination method, and require clients of the class to invoke this method on each instance when it is no longer needed."
I question the advisability of designing a class such that the design says "oh. by the way. when you are done using an instance of it, don't forget to call this method." Would not such a design lead to hard to find, easy to forget, resource leaks (same idea as memory leaks ). Is such a (dangerous?) practice used in real-world apps?
btw:
The issue of finalizers arose while reading about java.awt.Graphics . I read that if "g.dispose()" was not called on every instance of Graphics , if run long enough, with 100% certainity, an app would come crashing down. Some resource is exhausted. Know when it must be explicitly called, and then always put that method in a finalize block.

tatsuke wrote:
try {
ArrayList<Double> list = new ArrayList<Double>();
for(int d = 0; d < Double.MAX_VALUE;d++) {  list.add(new Double(d));  }
} catch (java.lang.OutOfMemoryError e) {
// forces gc to kill all possible objects, each's finalize block is executed?
// next, not sure what to do in any practical sense.
// just checking that i understand what is going on.
First of all, If I ever find any code like this in an production environment during a code review, then the author of that code will get a very strict talking-to at least.
I can't begin to tell you how wrong this is and at how many levels.
First of all: Who tells you that the OOM-Error is thrown in this code and not in an entirely unrelated code in another Thread that happens to be the first one to request too large a block of memory? (Not unlikely, since you allocate a lot of tiny objects and the OOM-barrier can easily be hit by another thread that tries to allocate a 512k buffer for some I/O operation.
Next: you're taxing the memory settings of the JVM, forcing it to go up to its maximum size, even when the actual requirement would a fraction of the maximum size and thus potentially forcing your application (and others) into swap and slowing them down to a grinding halt, effectively producing a denial-of-service.
Next: you produce an infinite loop, because you'll never reach Double.MAX_VALUE (try printing "Double.MAX_VALUE" and "Double.MAX_VALUE - 1d" and tell me the difference).
Next: no-one said that it's possible that the object is never collected and never finalized in all situations. Of course there are situations when it has to be collected (OOM is about the only one that comes to my mind, at the moment). But that doesn't mean that you can rely on finalize() being called in all situations. Note that nothing in the spec tells you that the GC must run when you run out of file descriptors. Running the GC could help, if someone forgot to close a stream, but it is not enforced.
Next: yes, I'm pissed of at something entirely unrelated and you just happen to be there. Sorry for that. I still think the content of my comments is correct.

Similar Messages

  • What is meant by a resource leak ?

    What is meant by a resource leak ?

    Garbage collection manages only memory, not other system resources. If your Java program has plenty of free memory, garbage collection will not be triggered automatically. Usually, however, there are other resources that are more limited than memory. For example, all OSes have limits on the number of sockets, file handles, etc. that can be open. Sometimes this limit is quite low. This is true even on a desktop, e.g. if your system has 128KB of memory, your Java program can easily allocate all the available file handles without coming near to filling up the heap. If this happens, your Java program will fail. This is what we call a resource leak; the unintentional maintenence of references to non-memory resources.
    This is why it is important in Java to explicitly manage non-memory resources. Classes which utilize non-memory resources should provide ways to explicitly allocate/deallocate those resources, independent of garbage collection. For example Socket, InputStream and OutputStream each provide explicit close() methods for deallocation of file descriptors, Window provides a dispose() method to free the window handle, etc. The way to properly use these classes is to allocate using the constructor, then deallocate using the appropriate method (deallocation is preferably done in a finally{} block, so it will execute whether or not an exception is thrown during use). These classes do release these non-memory resources in their finalize() method, but remember that the finalizer only gets called by the garbage collector, and if the object is never collected, it will never be finalized, hence will never release the resources.

  • Run-time Moveable Control resource leaks

    Hi,
    I've noticed a small resource leak issue with the Run-time Movable Control library (movectrl.fp).  The issue comes up when a control is made movable, then later the MOVECTRL_ATTR_ENABLED attribute is set to 0 to make the control non-movable, and then the control is discarded, either directly or by discarding the panel that the control is on.  
    Diving into the source code for the instrument, the reason is clear.  In the callback function DynamicCtrlCallback(...) which is chained to the control that is made movable, the first thing that happens is a check that the movable attribute is set, and if not, the function bails out with an early return.  The problem is that after this there is the handler for EVENT_DISCARD, that frees up the resources used by the movable control.  The problem is that if the movable attribute is not set, when the control is discarded the handler for the EVENT_DISCARD is never reached and therefore the resources are not freed.
    I thought I would post this to let anyone using the Run-time Movable Controls library that as a workaround you should set the MOVECTRL_ATTR_ENABLED to enabled before discarding a movable control as to not leak memory.  And so that hopefully NI can fix this in a future release .
    Thanks.

    Hi Jason D,
    No problem.  I've attached a small application. It has a button that generates a pop up with some controls on it.  It uses MakeMovableCtrl(..) to set all the controls movable, and then SetMovableCtrlAttribute(..) with MOVECTRL_ATTR_ENABLED set to 0 to make the graph control non-movable.  If you simply close the pop up (which discards the panel), in CVI's resource tracker there is some allocated memory that is not freed and a thread lock that is not discarded.  The switch on the pop up can be toggled to make the graph control movable again via SetMovableCtrlAttribute(..).  If you toggle the switch and then close the pop up you'll see that the memory is freed and the thread locks are properly discarded.  If you open/close the pop up multiple times without toggling the switch you'll see multiple blocks of non-freed memory and multiple non-discarded thread locks.
    Thanks for looking into this.
    Attachments:
    Runtime Movable Controls Test.zip ‏6 KB

  • Resource Leak in C#

    Creat64StringArray()
    stream filestream = null;
    1. Condition viewType.Equals("webbrowser"), taking true branch
    if(ViewType = "WebBrowser")
      try
                       string strPath = documents.Path; //= @ + documents.Path;
    2. Condition strPath.StartsWith("\\"), taking true branch
                     if (strPath.StartsWith("\\"))
                           strPath = @"\" + documents.Path;
    3. alloc_fn: A new resource is returned from allocation method OpenRead.
    4. var_assign: Assigning: fileStream = resource returned from System.IO.File.OpenRead(strPath).
                       fileStream = File.OpenRead(strPath);
    5. noescape: Resource fileStream is not closed or saved in Length.get.
                        fileArray = new byte[fileStream.Length];
    6. noescape: Resource fileStream is not closed or saved in Length.get.
    7. noescape: Resource fileStream is not closed or saved in Read.
    8. Throwing System.IO.IOException from call to Read.
                        fileStream.Read(fileArray, 0, (int)fileStream.Length);
        catch (IOException ex)
    10. Condition ex.Message.Contains("The process cannot access the file"), taking true branch
                     if (ex.Message.Contains("The process cannot access the file"))
                           string str = documents.Path;
                          FileInfo info = new FileInfo(str);
                          dest = DirectoryPicker.GetAppSpecificFolder(DirectoryPicker.AppFolder.DataFolder) + "\\" +info.Extension;
    11. Condition System.IO.File.Exists(str), taking true branch
                          if (File.Exists(str))
                               File.Copy(str, dest);
       CID 14867: Resource leak on an exceptional path (RESOURCE_LEAK)12. overwrite_var: Overwriting fileStream in fileStream = System.IO.File.OpenRead(dest) leaks the resource that fileStream refers to.
                              fileStream = File.OpenRead(dest);
    fileArray = new byte[fileStream.Length];
                               fileStream.Read(fileArray, 0, (int)fileStream.Length);
                                strImgArray[0] = System.Convert.ToBase64String(fileArray);
    finally()
    (filestream!=null){
    filestream.close()
    How to fix this Resource leak ? Please advice..

    Hi
    Deeyaa,
    Could you  please describe your scenario? And how did you get the resource Leak ?
    I would suggest you provide a simplified sample about this issue, It would be better to help us to figure out the root cause.
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Prevent Resource Accounts been Deleted from a Particular Resource

    Hi Everybody,
    We have a situation where we want to prevent resource accounts been deleted from a particular resource when the user is deleted from IAM. All other accounts to other resources can be deleted as normal.
    We are currently using version 5. Has anyone got any ideas on how to do this?
    I tried modifying the target list in the Delete Users workflow but had no success so far.
    Thanking you in advanced.

    In rev.6 we did that simply by disabling Delete action on the resource definition.

  • Help! setMaxInactiveInterval(-1), will it create resource leak on Server?

    Hi,
    I have a session that is set to have infinite timeout by setMaxInactiveInterval(-1). While browsing a page, the user closes his browser session.
    Does the server know when to destroy this session? Will this create a resource leak on the server?
    Is there any common way to get around it (assuming I have to use infinite timeout sessions)? Or is pretty much by definition the implication of infinite timeout sessions?
    Thanks,
    Eric.

    Does the server know when to destroy this session?Yes. After an infinite amount of time has passed. (Assuming that's really the meaning of the parameter, I don't have quick access to the documentation.)
    Will this create a resource leak on the server?Only if you have an unlimited number of distinct users. Otherwise you will over the long run have one session per user littering your server.
    Is there any common way to get around it (assuming I
    have to use infinite timeout sessions)? Or is pretty
    much by definition the implication of infinite
    timeout sessions?One way would be to allow the sessions to time out in a sensible way, and when that happens, dump their data into a database. Then when the user reconnects two weeks later, retrieve the data from the database and put it into the new session.

  • Prevent resource fork from being created on windows network shares

    I've already seen this article on how to prevent creating ds_store files on windows machines:
    http://docs.info.apple.com/article.html?artnum=301711
    But I haven't seen any way (short of buying software) to prevent the resource forks from being created. OSX creates resource forks on remote network volumes that pile up, are useless to the windows users, and creates a lot of grief.
    For every file copied to a windows share, OSX is putting a duplicate (unopenable) file with an underscore prefix:
    _file1.psd
    _file2.psd
    file1.psd
    file2.psd
    This is kind of rude network behavior, and I'd like to stop doing it.
    Isn't there some sort of terminal command similar to the .ds_store solution I posted above?

    I swear I saw a hack for that somewhere, but give up after 3 hours of searching for it!
    Seems like BlueHarvest at $10 is the best solution as it is...
    http://www.zeroonetwenty.com/blueharvest/
    Wondering if we couldn't "invent" something to add to that com.apple.desktopservices.plist file!?

  • Resource leak problem

    Hi
    Oracle Database 12.1.0.1.0 "standart edition one" installed on windows 2008 Server R2 SP1 (64 bit).
    I configure access to remote Databases MS SQL Server 2008. The access configured via "heterogeneous services".:
    1) Created ODBC source 1 : type "ODBC SQL Server 6.01.7601.17514 Microsoft Corparation", name "AOF_Statistic_140"
    2) Created ODBC source 2 : type "ODBC SQL Server 6.01.7601.17514 Microsoft Corparation", name "AOF_Statistic"
    3)created file "initAOF_Raport.ora" in "с:\app\oracle_db\product\12.1.0\dbhome_1\hs\admin"
    Сontent of the file "initAOF_Raport.ora" :
    HS_FDS_CONNECT_INFO = AOF_Raport_140
    HS_FDS_TRACE_LEVEL=0
    HS_LANGUAGE=RUSSIAN_RUSSIA.CL8MSWIN1251
    HS_IDLE_TIMEOUT=5
    HS_TRANSACTION_MODEL=READ_ONLY
    4)created file "initAOF_Statistic.ora" in "с:\app\oracle_db\product\12.1.0\dbhome_1\hs\admin"
    Сontent of the file "initAOF_Statistic.ora" :
    HS_FDS_CONNECT_INFO = AOF_Statistic_140
    HS_FDS_TRACE_LEVEL=0
    HS_LANGUAGE=RUSSIAN_RUSSIA.CL8MSWIN1251
    HS_IDLE_TIMEOUT=5
    HS_TRANSACTION_MODEL=READ_ONLY
    5) Сontent of the file "с:\app\oracle_db\product\12.1.0\dbhome_1\network\admin\listener.ora"
    SID_LIST_LISTENER =
      (SID_LIST =
      (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = с:\app\oracle_db\product\12.1.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:с:\app\oracle_db\product\12.1.0\dbhome_1\bin\oraclr12.dll")
      (SID_DESC=
      (SID_NAME= AOF_Statistic)
      (ORACLE_HOME=с:\app\oracle_db\product\12.1.0\dbhome_1)
      (PROGRAM=dg4odbc)
      (SID_DESC=
      (SID_NAME= AOF_Raport)
      (ORACLE_HOME=с:\app\oracle_db\product\12.1.0\dbhome_1)
      (PROGRAM=dg4odbc)
    LISTENER =
      (DESCRIPTION_LIST =
      (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
      (ADDRESS = (PROTOCOL = TCP)(HOST = Indas-debug)(PORT = 1521))
    6) Сontent of the file "с:\app\oracle_db\product\12.1.0\dbhome_1\network\admin\tnsnames.ora"
    ORACLR_CONNECTION_DATA =
      (DESCRIPTION =
      (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
      (CONNECT_DATA =
      (SID = CLRExtProc)
      (PRESENTATION = RO)
    ORCL =
      (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = Indas-debug)(PORT = 1521))
      (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    aof_Raport =
      (DESCRIPTION=
      (ADDRESS=(PROTOCOL=tcp)(HOST= localhost)(PORT=1521))
      (CONNECT_DATA=(SID = AOF_Raport))
      (HS=OK)
    aof_Statistic =
      (DESCRIPTION=
      (ADDRESS=(PROTOCOL=tcp)(HOST= localhost)(PORT=1521))
      (CONNECT_DATA=(SID = AOF_Statistic))
      (HS=OK)
    7) Created public links:
    CREATE PUBLIC DATABASE LINK aof_Statistic CONNECT TO "ascub" IDENTIFIED BY "111**" using 'aof_Statistic';
    CREATE PUBLIC DATABASE LINK aof_Raport CONNECT TO "ascub" IDENTIFIED BY "111**" using 'aof_Raport';
    8)created pl sql package "test_sql_hs" with following code:
    procedure raport_rep_L337_3 is
      l_dt date;
    begin
      ---- table L337 from AOF_RAPORT
      for cur1 in (select
      to_date(TO_CHAR("DateAndTime", 'DD.mm.YYYY HH24:MI:SS'),'DD.mm.YYYY HH24:MI:SS') as DateAndTime,
      "D3_Q" as d3_q,
      "D5_Q" as d5_q,
      "D7_Q" as d7_q,
      "D9_Q" as d9_q,
      to_number("D11_Q") as d11_q,
      to_number("D13_Q") as d13_q,
      to_number("Work_Time") as work_time
      from L337_3@AOF_RAPORT
      where "DateAndTime"> (l_dt-1)
      order by "DateAndTime" asc ) loop
      begin
      insert into TB$A$L337 (dateandtime,d3_q,d5_q,d7_q,d9_q ,d11_q,d13_q,work_time,UPDATE_TIME)
      values(cur1.dateandtime,cur1.d3_q,cur1.d5_q,cur1.d7_q,cur1.d9_q ,cur1.d11_q,cur1.d13_q,cur1.work_time,sysdate);
      exception when dup_val_on_index then null;
      update TB$A$L337 t set t.update_time=sysdate where t.dateandtime=cur1.dateandtime;
      end;
    end loop;
    commit;
    exception when others then
      rollback;
      sys_log(p_oid => 'raport_rep_L337', content => sqlerrm);
      raise;
    end;
    procedure static_rep_L337_3 is
      l_dt date;
    begin
      ---- table L337 from AOF_RAPORT
      for cur1 in (select
      to_date(TO_CHAR("DateAndTime", 'DD.mm.YYYY HH24:MI:SS'),'DD.mm.YYYY HH24:MI:SS') as DateAndTime,
      "D3_Q" as d3_q,
      "D5_Q" as d5_q,
      "D7_Q" as d7_q,
      "D9_Q" as d9_q,
      to_number("D11_Q") as d11_q,
      to_number("D13_Q") as d13_q,
      to_number("Work_Time") as work_time
      from L337_3@AOF_STATISTIC
      where "DateAndTime"> (l_dt-1)
      order by "DateAndTime" asc ) loop
      begin
      insert into TB$A$L337 (dateandtime,d3_q,d5_q,d7_q,d9_q ,d11_q,d13_q,work_time,UPDATE_TIME)
      values(cur1.dateandtime,cur1.d3_q,cur1.d5_q,cur1.d7_q,cur1.d9_q ,cur1.d11_q,cur1.d13_q,cur1.work_time,sysdate);
      exception when dup_val_on_index then null;
      update TB$A$L337 t set t.update_time=sysdate where t.dateandtime=cur1.dateandtime;
      end;
    end loop;
    commit;
    exception when others then
      rollback;
      sys_log(p_oid => 'raport_rep_L337', content => sqlerrm);
      raise;
    end;
    procedure rep_MSSQL_140 is
    begin
    raport_rep_L337_3;
    static_rep_L337_3
    exception when others then
      rollback;
    end;
    9) Created JOB which runs every 30 seconds function: test_sql_hs.rep_MSSQL_140
    begin
      sys.dbms_job.submit(job => :job,
      what => 'begin
    test_sql_hs.rep_mssql_140;
    exception when others then
    rollback;
    end;',
      next_date => sysdate,
      interval => 'sysdate+30/(24*60*60)');
      commit;
    end;
    PROBLEM IS:
    Initially JOB runs normally, but after 12 hours of working errors occure:
    1)code test_sql_hs.rep_mssql_140 returns error: "ORA-28511: lost RPC connection to heterogeneous remote agent using ..." permanently.
    2) At the same time I can not login to OS using any windows account, I get error "Access denied". I have "lack of resources" message in Windows system log.
    The problem disappears only when I reboot Windows service "OracleOraDB12Home1TNSListener" (process TNSLSNR.exe).
    Any idea of this issue please let me know.

    Hi,
      You say you start the job every 30 seconds and you have resource problems after about 12 hours as well as an ORA-28511 error.  That error indicates the connection between the gateway and SQL*Server has been lost for some reason.
    To follow up -
    - do you see any messages in the RDBMS alert log ?
    - how many DG4ODBC processes do you see if you look at Task Manager ?
    Although you have a 'commit' in the PL/SQL procedure it could be that the actual DG4ODBC connection is not being closed every time it is run.
    What you could try is an explicit 'close database link AOF_STATISTIC' in the code after the 'commit' statement.  This will cause the DG4ODBC process opened for the connection to be closed and a new one opened next time it is called.  This should prevent any resource problems if that is the cause of the problem.
    Regards,
    Mike

  • 9i Connection Manager Resource Leak?

    I am experiencing serious performance problems with the Connection Manager gateway (CMGW.exe) that ships with Oracle9i for Windows NT/2K.
    There appears to be a memory leak after the first connection to the Connection Manager is made. I've come across mention of a similar problem with CMGW on Solaris. Is there a fix for this problem?
    Background: my students are building Java applets to connect to Oracle9i via Oracle9i application server. The applets are hosted on the application server, so I was planning on using Connection Manager to hit the database from the application server. It works fine the first time, but due to the memory leak the application server slows to a crawl whenever another connection is attempted.
    Thanks,
    Ray Moro
    Eastern Washington University

    Use the same as you were using in 8i. Just upgrade your client (if required).

  • 9879: GDI Objects resource leak in explorer.exe (directly affects Taskbar)

    Update 1 (Nov 18): The leak seems to be exacerbated by the use of a progress bar within a given program's taskbar icon. For example, downloads with a browser show such status. In particular, media players often do this too, and since people
    tend to use media players for an hour or two at a time, the problem can worsen quickly when in use.
    ===========(Original message below)
    Twice in one day I've seen GDI Objects (as shown in Task Manager--if you add the column on the Details tab--and Process Explorer) hit 10K for Explorer.exe. The first time was after about 15 hours, the second time about 4.
    What caused me to look was a misbehaving taskbar: icons for some running programs were suddenly either blank or changed, some would do nothing when clicked, the Start menu was barely functional, my quicklaunch shortcut menu didn't work, etc.
    Killing explorer.exe and restarting it allows you to proceed as usual.
    This definitely didn't happen in the preceding builds.
    Further details provided if this turns out to be something that others see.

    Same for PS
    GDIView.ps1
    $path = Split-Path -parent $MyInvocation.MyCommand.Definition
    $searchfor = "explorer"
    $maxGDI = 6000
    $sig = @'
    [DllImport("User32.dll")]
    public static extern int GetGuiResources(IntPtr hProcess, int uiFlags);
    Add-Type -MemberDefinition $sig -name NativeMethods -namespace Win32
    $processes = [System.Diagnostics.Process]::GetProcesses()
    ForEach ($p in $processes)
    # Check for process
    if ($p.Name -ne $searchfor) { continue }
    try{
    $gdiHandles = [Win32.NativeMethods]::GetGuiResources($p.Handle, 0)
    # Check for maxGDI
    if ($gdiHandles -lt $maxGDI) { continue }
    try{
    # Log
    "$(Get-Date) The process $searchfor ($($p.id)) had $gdiHandles GDI Objects, so it is closed for sanity" | Out-File $path\Leak.log -Append
    #Write-Output "kill $($p.Id)"
    kill $p.Id -Force
    #Write-Output "start $searchfor"
    Start-Process $searchfor
    catch {
    #"Error"
    catch {
    #"Error accessing " + $p.Name
    And to start it hidden
    GDIView.vbs
    Const HIDDEN_WINDOW = 0
    strComputer = "."
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set objStartup = objWMIService.Get("Win32_ProcessStartup")
    Set objConfig = objStartup.SpawnInstance_
    objConfig.ShowWindow = HIDDEN_WINDOW
    Set objProcess = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
    objProcess.Create "powershell -file GDIView.ps1", null, objConfig, intProcessID

  • Finally & IOException

    Hi everybody,
    I'm using InputStream for reading file. I know it's a good programming practice to close every InputStream when done with reading, to prevent any resource leaks. So i would use something like this:
    InputStream is = null;
    try {
          is = new FileInputStream(someFile);
    } catch(IOException ioe) {
          // do something with exception...
    } finally {
         // closing InputStream to prevent resource leaks
          if(is != null) {
                      is.close();
    }My question is: What happens if an I/O error occurs while closeing InputStream i.e. close() method throws IOException? How could i get notified that an I/O error occurred? Should i also surround this method with a try-catch block e.g. something like this:
    } finally {
         // closing InputStream to prevent resource leaks
          if(is != null) {
                 try {
                      is.close();
                 } catch (IOException e) {
                                    System.out.println("Error", e);
    }it looks like a solution to me, but now finally block looks a bit fuzzy.
    Can anyone please help me about this topic...
    Kind regards!
    Igor

    your said
    The finally block contains the cleanup code to runafter the actual work code
    here the creation of InputStream is part of actual
    work code, but it's not inside the try-block.If that fails, there's nothing to clean up, since that's the very first step.
    Nonetheless, I would tend to do it this way, because I consider it simpler and more consistent, even thoug it adds a couple steps that are not strictly necessary:
    InputStream is = null;
    try {
      is = new ... ;
      use is
    finally {
      if (is != null) {
        try {
          is.close();
        catch (...) {
          log it
    }And again, I'd put the entire body of the try block into a utilty method to keep things tidier.
    I've tried and constructor does need the throws
    clause, but my final question is:
    Is it a good programming practice to put a method
    with throws clause (without the surrounding try-catch
    block) inside the construstor, 'casuse i've never
    seen constructors with throws clause ?If you're considering a throws clause, that means it must be possible for some step in your c'tor to fail. So, given that, the question is, what do you do if that step fails? If that step is critical to putting the new object into a valid state, then you can't just let the c'tor complete normally without handling the exception. (Note that logging the exception does not count as handling it.) You need to either provide some other, failsafe, default initialization, or declare the exception.
    There's nothing wrong with throwing an exception from the c'tor--it's the right thing to do if the c'tor can't complete its job properly.
    Of course, you can take a step back and ask whether the stuff you're doing in the c'tor actually belongs there. A c'tor's job is to put the object into a valid working state. It should do that as completely as possible, but it shouldn't do anything more than that. So you have to decide, based on your object's job, whether it's necessary to process that file to get the object into a valid initial state.

  • Resources garbage collection, can be done this way ?

    The problem
    I would like to apply the same concept of garbage collection to system resources like Files, Database resulsets, Sockets etc...
    The reasons
    I am tired of looking around desperately into a program to identify memory leak that are instead resources leak. And this is getting worse while program size grows.
    How it could be done
    -- Let's have a resource manager class from where I get the wanted resource (I will write this class, fairly easy).
    -- Let's say that this manager class is a thread that runs in a scheduled way and this is decided by me (this is also something anybody can write).
    -- Let's say that when it runs it checks for all resources (objects) that it has given to the rest of the program if the reference count greater than one. If it is > 1 then the resource is still in use, else it can be deallocated (that just means calling close and then leaving the object to garbage collect).
    What I need
    A way to know in a reliable way how many objects are having a reference to a given object. Is there such a way ?
    Evangelism on..
    Please, if anybody at Sun is reading this, this IS a TOP issue. If you look around you will see more and more issues of leaking, they are resources leakage because it is NOT easy to ALWAYS close a resource.
    Someone may say "use the finally" of yes, try to think to use the finally to deallocate memory and you will immediatly understand the mess that will come.
    Garbage collection is a good idea let's have a way to apply it to resources.
    Thanks

    I have no problem, as it is, in making applications
    reliable.As usual the problems come in deciding how to do
    things.Yes.
    >
    Which is why mine don't. Since resources are usedin
    so few places it is easy to manage their usage.We are not talking on who has the biggest gun...Eh?
    >
    The sad thing is that the problem most of
    the time is NOT yours but of somebody else thatforgot
    to clean up after himself...Sounds more like a management problem than a code
    problem. If you are allowing programmers in your
    organization to write code which leaks resources oris
    so poorly designed that other users can notproperly
    dispose of resources then it is a managementproblem.
    Ok, let's drop it here.
    I hope you will never have to deal with code other
    that yours or written by your coworkers.
    I always deal with other people's code. And they with mine. Although I occassionally work on one person projects - perhaps 2 weeks every three years. the rest of my career has always involved multi-person projects and often (if not always) involve third party libraries.
    So I believe I have dealt with others code.
    in the applications that I work on.)There is java.lang.ref in a way it seems to dowhat
    I
    want....
    I don't believe so. Finalize() more closely fitswhat
    you might want to do. java.lang.ref is used in
    building caches of disposable entities. And it is
    most definitely only useable with memory.I have a funny sensation that whatever I write you say
    no...Not necessarily.
    Thanks for your help, if anybody wants to add
    something useful to
    what I am tryng to do they are welcome.I am trying to be useful.
    I am trying to point out that you are looking for a new feature in the language that just isn't very useful to most people. I was trying to point out why it wasn't useful to most people.
    Perhaps this might help.
    Look at it this way, go look at the bug database and look at the top vote getters for things that people want fixed. Then you might trying looking through the RFEs for something like you want. If it isn't there then add it. If enough people actually want it then it will be voted for. With enough votes it would have a better chance of being added.
    Of course that presumes it could be done in the first place. Based on my memory of past topics in the forums on reference counting I suspect that the answer is no. But you might want to read those.

  • GDI Resources?

    I have had many problems using Captivate 1.0 to capture
    screen srecordings from my CAD application. I have spoken to the
    developers of the CAD program and they put it down to GDI
    resources. They told me to enable GDI resources in the columns of
    my Task Manager (right click) and check the amount of GDI resources
    being used. My CAD application maxes out at about 2375 GDI Objects,
    while Captivate 1.0 uses about 673 GDI Objects.
    Does anyone know if this is excessive? Apparently this is not
    dependent on hardware, but I don't know enough about it to be sure.
    The reason why I am asking is because whenever I drag a dialog,
    during a screen recording, Captivate shows remnants of everywhere
    my dialog box has been dragged and there's no way of getting rid of
    it. It's a very serious matter that may unfortunately prevent me
    from using the software entirely. Maybe Captivate has a resource
    leak? Maybe Captivate 2.0 solves the problem? Maybe there is a
    setting somewhere that solves it?
    In any case, I would like to hear from anyone who may be able
    to shed some light on the subject, or even solve the problem! I
    really want to use Captivate - and preferably without editing
    images to remove my dialog remnants.
    Thanks in advance,
    spritc.

    Have you adjusted the Video Acceleration option at all?
    Display Properties > Settings > Advanced >
    Troubleshoot.
    Knock that slider down a notch and try again. If no luck,
    down another
    notch and try again...until there are no more notches to try
    or the
    recording improves.
    If you can't get a decent result, perhaps try Camtasia. It's
    pretty good
    at these full-motion recordings...as that's how it captures
    the entire
    process (as a movie, not as screenshots like Captivate does).
    However,
    that can also result in pretty sizable output files. Camtasia
    automatically disables the screen acceleration (if so
    enabled), so maybe
    the same principle will work with Captivate.
    As a workaround idea for such things, do you actually have to
    show the
    window dragging? It's a pretty easy concept. Could you not
    say, "Now I'm
    going to move this window to the side..." and show your mouse
    moving to
    the window, then erase the 'wacky' frames with trails so the
    next frame
    is the window in the new location. It may be a bit...dramatic
    of a move
    but would it really hurt the instruction? I'd think only
    perhaps if the
    point of the instruction was to show users how to move
    windows...
    Also, maybe check out Display Properties > Appearance >
    Effects. If
    nothing else, perhaps unchecking 'show window contents while
    dragging'
    will solve the problem by showing the window outline during
    the drag,
    which should be a lot less 'GDI' intensive.
    Erik
    spritc wrote:
    > I have had many problems using Captivate 1.0 to capture
    screen srecordings from
    > my CAD application. I have spoken to the developers of
    the CAD program and they
    > put it down to GDI resources. They told me to enable GDI
    resources in the
    > columns of my Task Manager (right click) and check the
    amount of GDI resources
    > being used. My CAD application maxes out at about 2375
    GDI Objects, while
    > Captivate 1.0 uses about 673 GDI Objects.
    >
    > Does anyone know if this is excessive? Apparently this
    is not dependent on
    > hardware, but I don't know enough about it to be sure.
    The reason why I am
    > asking is because whenever I drag a dialog, during a
    screen recording,
    > Captivate shows remnants of everywhere my dialog box has
    been dragged and
    > there's no way of getting rid of it. It's a very serious
    matter that may
    > unfortunately prevent me from using the software
    entirely. Maybe Captivate has
    > a resource leak? Maybe Captivate 2.0 solves the problem?
    Maybe there is a
    > setting somewhere that solves it?
    >
    > In any case, I would like to hear from anyone who may be
    able to shed some
    > light on the subject, or even solve the problem! I
    really want to use Captivate
    > - and preferably without editing images to remove my
    dialog remnants.
    >
    > Thanks in advance,
    > spritc.
    >
    Erik Lord
    http://www.capemedia.net
    Adobe Community Expert - Authorware
    http://www.adobe.com/communities/experts/
    http://www.awaretips.net -
    samples, tips, products, faqs, and links!
    *Search the A'ware newsgroup archives*
    http://groups.google.com/group/macromedia.authorware

  • Freeing objects, memory leak ???

    Hey...
    I was wondering if there is something that is oposite to the new operator that free's object. I don't know if it does it automatically but let's say i want to free a buffer in the middle of a routine, what is the call that does that ?? I guess in C++ it's like something called delete
    Thanxs

    Arbitrarily setting references to null and calling System.gc will do nothing but clutter your program with useless junk and make it slower, possibly far slower. Just let the garbage collector work do its work without your help.
    What is far more useful to prevent memory leaks is to call the close or dispose or remove method on objects that you no longer want to use. This will cause the object to release resources so they can be re-used.

  • Memory Leak in NK.exe

    Hi All,
    OS: Windows Embedded Compact 7 with updates till Feb 2015.
    Hardware: AM335x based 
    Applications running: one serial port application and one tcpclient and tcpserver apps. all are managed (C#) applications
    I am facing memory leak issue with our headless device. 
    When I connect the device to LAN network, memory usage keep increases and after few hour (some times <1 hour, some times 4-5 hour) devices go to hang state due to low memory.
    I also tried to run the resource leak detector and found
           1. NK.exe heap is increasing
           2. on startup : API Handle Count = 4118, DuplicatedHandle - Count : 4,082, Size : 4,082 bytes
    After few minutes: APIHandle - Count : 49,172, Size : 49,172 bytes, DuplicatedHandle - Count : 48,810, Size : 48,810 bytes
    NK.exe heap increases as available RAM decreases.
    our application heap is constant only. please find below memory snapshots taken by devhealth.
     1. On device start up after all apps started
    2. After 1 hour of device running. - refer attachment
     where exactly might be this leak, any Guess?
    Thank you...
    rakesh

    Hi tomleijen,
    Thanks for your suggestions.
    Even we tried without any user apps, then also we found ~1 MB increase in NK.exe heap every 30-40 min.
    we have 2 images 1. with all WEC7 updates (Till feb 2015) and 2. without any of the WEC7 updates
    almost same problem we are facing with both images.
    rakesh

Maybe you are looking for