Permalink
Browse files

Fix bug where context file could get truncated during shutdown hook

  • Loading branch information...
1 parent f7b3968 commit 1c498fc2950e9d26e54a9edd3e7e9434b5a117b2 @toddlipcon committed Aug 8, 2011
@@ -82,7 +82,11 @@ private String readString() {
}
public LockingContext readContext(int id) {
- mBuffer.position(id);
+ try {
+ mBuffer.position(id);
+ } catch (IllegalArgumentException iae) {
+ throw new IllegalArgumentException("Invalid pos: " + id);
+ }
return new LockingContext(readString(),
readString(),
readString());
@@ -31,14 +31,16 @@
@ThreadSafe
public final class ContextFileWriter
implements ContextWriterIfc {
- private final FileChannel mChannel;
+ private final File mFile;
+ private FileChannel mChannel;
private int mNextFilePosition = 0;
private final Logger mLogger;
private ByteBuffer mBuffer = ByteBuffer.allocateDirect(8192);
private boolean mShutdownHookExecuted = false;
public ContextFileWriter(Logger logger, File file) throws IOException {
mLogger = logger;
+ mFile = file;
mLogger.info("Opening for writing: " + file.getAbsolutePath());
RandomAccessFile raFile = new RandomAccessFile(file, "rw");
raFile.setLength(0);
@@ -54,6 +56,18 @@ private synchronized void shutdownHook() {
try {
if (mChannel.isOpen()) {
writeBuffer();
+ } else {
+ // the JDK seems to close off the file channel during
+ // the shutdown hook. So, we reopen it here and seek
+ // to the last known end of the file
+ RandomAccessFile raFile = new RandomAccessFile(mFile, "rw");
+ mChannel = raFile.getChannel();
+ try {
+ mChannel.position(mNextFilePosition - mBuffer.position());
+ writeBuffer();
+ } finally {
+ mChannel.close();
+ }
}
} catch (IOException e) {
e.printStackTrace();

0 comments on commit 1c498fc

Please sign in to comment.