Here's a snippet code which throws NullPointerException at in.close() randomly (And I know java8 supports try-with-resources whilst this snippet uses the old style):
public static byte[] readReqFile(String filename) throws IOException {
File f = new File(filename);
if (!f.exists()) {
throw new FileNotFoundException(filename);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream((int)f.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(f));
int buf_szie = (int)f.length();
byte[] buffer = new byte[buf_szie];
int len = 0;
while (-1 != (len = in.read(buffer, 0, buf_szie))) {
bos.write(buffer, 0, len);
}
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
in.close(); <-- Throws NullPointerException at this line
} catch (IOException e) {
e.printStackTrace();
}
bos.close();
}
}
public static void main( String[] args ) throws IOException, InterruptedException
{
String folderA, folderB;
while (/*Find a file in folderA*/) {
Moves the file into folderB
readReqFile(/*the file in folderB*/);
}
}
The process of the code is like this. There's a program (called ProgramA below) creating files at folderA, and if this snippet code finds a new file in folderA, it moves the file into folderB and read it. And then I find this snippet of code throws NullPointerException at "in.close()" randomly.
And the interesting thing is, if ProgramA creates files regularly, say create one every 0.1 seconds. The above code is ok and never throw NPE after trying 1000 times. If ProgramA creates files with random interval from 0.1s to 3s, the above code throws NPE after got every 40-50 files.
My java version is 1.8.0_111
My guess is that maybe the jvm does something to optimize the code, and it meets some bug when dealing random input. But it's just a guess. Does anyone know the reason?
Aucun commentaire:
Enregistrer un commentaire