Bookmark Topic Watch Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
How do I fix exceptions that indicate "Too many open files"?

This problem is caused by poor programming practice. Some programmers get into bad habits when writing small applications, then when they graduate to applications that are long-lived, like web applications and daemons, they start to get errors. Remember, every time one opens a file, socket, database connection and so on, one MUST close that resource. What's more, one must close it in the finally block of a try-catch-finally structure.

This is the WRONG way to use files:

Without explicitly closing a file-like resource, the resource may linger forever.

Sometimes a programmer will explicitly handle closing a resource, but in the wrong place:

What happens should an exception occur? The resource is not closed properly.

The correct way to handle closing a resource is as follows:

No matter what happens in the try or catch blocks, the finally block will get executed. If you want to know more about handling exceptions, consult the Java Tutorial chapter on Exceptions

Now this is fine and good in a small program with few resources, but in a non-trivial program we may have dozens or even hundreds of resources. How can we track down the code that is causing the problem?
There are operating system tools that can tell us what resources are in use for a particular program. lsof is available in the Unix world. Here is a tutorial on how to use it.
In the Windows world, Process Explorer provides the same functionality in an easy-to-use GUI.
Once you know what resources are hanging around, it should be a simple matter to go to the code that uses those resources and find the code that is not handling the resources properly.



JavaIoFaq
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
    Bookmark Topic Watch Topic
  • New Topic