File Descriptors Leak

O

Oz Levanon

Hi. I'm running a tomcat server on Linux (2.4.20-8smp) with a constant
load of users sending requests to it.
I've noticed that the number of used file-descriptors on the machine
increases with time (I use "lsof -a -d 0-10000000 | wc -l" to count
the number of used file-descriptors). Once in a while, supposedly when
the GC runs, the number goes down, but over long periods of time it
steadily increases.
I take this to mean that I have a leak somehwere.
I wanted to ask if I have to explicitly close all open files (using
FileInputStream.close and similar methods) in order to free
file-descriptors, or is it taken care of automatically by the GC
whenever it runs?
TIA, Oz.
 
S

Sergio Juan

Hi

When a File (or FileStream) is destroyed, the wrapped file is closed, if it
has not been done previously. Anyway, the objects are destroyed by the GC
(when it wants to), so it is better if you close your streams. If not, you
can also have trouble with mantaining locked files that you need to use
again.

HTH
 
T

Tim Ward

Oz Levanon said:
I wanted to ask if I have to explicitly close all open files (using
FileInputStream.close and similar methods) in order to free
file-descriptors, or is it taken care of automatically by the GC
whenever it runs?

It might be taken care of eventually by the garbage collector, on a good
day, if you're lucky, but it's *much* better to close them yourself. Oh, and
never use MappedByteBuffer for any file that isn't going to held open for
the life of the application, because it doesn't even have a close method so
you're completely stuffed.
 
R

Robert Olofsson

: I wanted to ask if I have to explicitly close all open files (using
: FileInputStream.close and similar methods) in order to free
: file-descriptors, or is it taken care of automatically by the GC
: whenever it runs?

Yes, you have to close/dispose/flush lots of things in java.
Streams, Graphics, Images, windows...

Java may have a Garbage Collector, but system resources still has
to be handled. Some of the resources have finilizer methods that
clean up things nicely, some things like oracles prepared statements
however will not clean themself up at all ( => if you dont close
you run out of cursors in the database after a while).

Basically this means that you have to write code that looks like:

InputStream is = null;
try {
is = new FileInputStream (...);
....
} finally {
if (is != null)
is.close ();
}

Add additional try/catch as needed.

By having a finally you pass your close-code before exiting
even if an exception is thrown.

/robo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top