Java – is writer an atomic method?
•
Java
I want to write some strings to the file Therefore, I use the bufferedwriter class Since many threads tend to write to this file, I wonder if the write and writeline methods are atomic
In addition, I want the program to write the output to multiple files, 100 lines each (such as file. Txt0, file. Txt1,...) for example
public class Main {
static ExecutorService exec = Executors.newFixedThreadPool(5);
BufferedWriter bw;
public class myWriter implements Runnable {
String str;
myWriter (String str) {
this.str = str;
}
public void run() {
bw.write(str);
bw.writeLine();
}
}
public static void main(String[] args) {
bw = new BufferedWriter(new FileWriter("train.txt"));
for (String arg: args)
exec.execute(new myWriter(arg));
exec.awaitTermination(100000,TimeUnit.MILLISECONDS);
}
}
Can someone help me? If they are not atomic, how can I make them atomic and avoid collisions?
Solution
No, those are not atomic
If you want to write multiple tapes to the same file, use filelocks
try {
// Get a file channel for the file
File file = new File("filename");
FileChannel channel = new RandomAccessFile(file,"rw").getChannel();
// Use the file channel to create a lock on the file.
// This method blocks until it can retrieve the lock.
FileLock lock = channel.lock();
// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// File is already locked in this thread or virtual machine
}
// Release the lock
lock.release();
// Close the file
channel.close();
} catch (Exception e) {
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
