まず、お互いをサポートする2つのプロセスが同時に実行されています。 1つのプロセスは、タイムスタンプで区切られたデータのスナップショットを含む単純なフラットファイルを読み込みます。このアプリケーションは単にファイルロックなしでこのファイルを開き、スナップショットを読み込んでtopology.netviz
という別のファイル(ファイルロック付き)に配置します。 2番目のアプリケーションはtopology.netziv
(ファイルロック付き)を読み取り、そのデータを一時ファイルに転送して、他のプロセス間でロックを保持するプログラミングの待ち時間を短縮します。2 ProcessessでのJavaファイルのロック
私の問題は次のように簡単です: 2番目のプロセスで一時ファイルにデータを転送すると、奇妙な文字/破損したデータが転送されます。私は皆さんが何が問題かを感じ取れるように、以下のコードをいくつか用意しました。
プロセス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");
}
私は2行のコードを切り替え、IOExceptionを受け取りました。プロセス1は、データを正確に吐き出しているようです。 –
@ミッチェル - 例外は何ですか? –