where is the file descriptor leak in this code?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Mike_Wertheim
Posted On:   Friday, September 26, 2008 12:59 PM

The following "stringToFile" method is called in a synchronized block to append a String to a file. The synchronized block ensures that no 2 threads are calling this method concurrently. However, the system crashes after running for about 12 hours. The exception is "Too many open files". Can anyone find the problem? public static void createParentDirectoryIfNeeded(String path) { String dirPath = path.substring(0, path.lastIndexOf('/')); File dir = new File(dirPath); if (!dir.exists()) { dir.mkdirs(); } } public static void stringToFile(String s, String path, boolean append) { FileWriter fileWriter = null; try    More>>

The following "stringToFile" method is called in a synchronized block to append a String to a file. The synchronized block ensures that no 2 threads are calling this method concurrently. However, the system crashes after running for about 12 hours. The exception is "Too many open files".


Can anyone find the problem?


			

public static void createParentDirectoryIfNeeded(String path) {
String dirPath = path.substring(0, path.lastIndexOf('/'));
File dir = new File(dirPath);
if (!dir.exists()) {
dir.mkdirs();
}
}

public static void stringToFile(String s, String path, boolean append) {
FileWriter fileWriter = null;
try {
createParentDirectoryIfNeeded(path);

// create file if it doesn't already exist
File file = new File(path);
file.createNewFile();

if (s != null) {
fileWriter = new FileWriter(file, append);
fileWriter.write(s.toCharArray());
}
} catch (IOException ioe) {
ErrorHandler.handleError(ioe, LOG);
} finally {
if (fileWriter != null) {
try {
fileWriter.close();
} catch (IOException ioe) {
ErrorHandler.handleError(ioe, LOG);
}
}
}
}
   <<Less

Re: where is the file descriptor leak in this code?

Posted By:   Stephen_McConnell  
Posted On:   Monday, September 29, 2008 01:30 PM

You may be creating the file, but you NEVER close it.... The object may be gone, but the file is still open.


Stephen McConnell

About | Sitemap | Contact