首先,我有两个同时运行的进程,它们相互支持。一个进程读取一个简单的平面文件,其中包含由时间戳分隔的数据快照。此应用程序只需打开此文件(不带文件锁定),读取快照并将其放入另一个名为topology.netviz
的文件中(带文件锁定功能)。第二个应用程序读取topology.netziv
(带有文件锁定)并将数据传输到临时文件中,以减少在其他进程之间保持锁定的编程的延迟。
我的问题很简单:当我在第二个过程中将数据传输到临时文件时,会传输奇怪的字符/损坏的数据。我在下面提供了一些代码,让你们了解可能的问题。
流程1:
try {
// Determine if File Exists
topologyFile = new File(Settings.NODE_TOPOLOGY_PATH);
if (!topologyFile.exists())
topologyFile.createNewFile();
// FileChannel Gives the Ability to Create a File Lock
FileChannel channel =
new RandomAccessFile(topologyFile, "rwd").getChannel();
// Use the FileChannel to Create a Lock on the 'distance.dat' (Blocking Method)
FileLock lock = channel.lock();
// Delete Files Contents
channel.truncate(0);
// Convert 'data' into ByteBuffer
ByteBuffer buffer = ByteBuffer.wrap(data);
// Write 'buffer' to 'channel'
channel.write(buffer, 0);
// Release Lock
lock.release();
// Close Channel
channel.close();
}
catch(IOException error)
{
System.out.println("Topology Thread: FileChannel; I/O Error Occured");
}
catch(NonWritableChannelException error)
{
System.
out.println("Topology Thread: FileChannel; File is not Writeable");
}
流程2:
try {
// Determine if File Exists
topologyFileTemp = new File("tmp/topology.dat");
if (topologyFileTemp.exists())
topologyFileTemp.delete(); // Should Never Occur Unless Program Crashes
// Recreate 'topologyFileTemp'
topologyFileTemp = new File("tmp/topology.dat");
topologyFileTemp.createNewFile();
// Determine if File Exists
topologyFile = new File("topology.netviz");
if (!topologyFile.exists())
topologyFile.createNewFile(); // Should Never Occur
// Initialize Data Container from 'topology.netviz' in the Form of Bytes
ByteBuffer topologyData =
ByteBuffer.allocate((int)topologyFile.length());
// FileChannel Gives the Ability to Create a File Lock for 'topology.netviz'
FileChannel rChannel =
new RandomAccessFile(topologyFile, "rwd").getChannel();
// Use the FileChannel to Create a Lock on the 'distance.dat' (Blocking Method)
FileLock lock = rChannel.lock();
// Grab Data from 'topology.netviz'
rChannel.read(topologyData);
// Release Lock
lock.release();
// Close Channel
rChannel.close();
// FileChannel Gives the Ability to Create a File Lock for 'tmp/topology.dat'
FileChannel wChannel =
new RandomAccessFile(topologyFileTemp, "rw").getChannel();
// Reset Buffers Position
topologyData.position(0);
// Write 'topologyData' to 'tmp/topology.dat'
wChannel.write(topologyData);
// Close the file
wChannel.close();
}
catch(IOException error)
{
System.out.println("Topology Thread: FileChannel; I/O Error Occured");
}
catch(NonWritableChannelException error)
{
System.out.
println("Topology Thread: FileChannel; File is not Writeable");
}
一个潜在的问题是进程#1在关闭通道之前释放了锁。由于关闭通道会刷新未完成的写入,这可能意味着数据是在锁定释放后写入的,这可能会导致损坏。
另一种可能性是,字节在写入之前已经损坏。。。或者在写入器和读取器使用的格式之间存在不匹配。