Win a copy of Serverless Applications with Node.js this week in the NodeJS forum!
    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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • paul wheaton
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Ron McLeod
  • Tim Moores
  • salvin francis
  • Carey Brown
  • Tim Holloway
  • Frits Walraven
  • Vijitha Kumara
  • Mark post as helpful
  • send pies
  • 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.

WARNING! Do not activate jet boots indoors or you will see a tiny ad:
Create Edit Print & Convert PDF Using Free API with Java
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!