多个jvm写同一个文件

每次都在文件末尾添加一行,顺序无要求

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class FileWriter {

	private final File file;

	public void write(String str) throws IOException {
		synchronized (this) {
			doWrite(str);
		}
	}

	public FileWriter(File file) {
		this.file = file;
	}

	private void doWrite(String line) throws IOException {
		try (FileOutputStream os = new FileOutputStream(file, true)) {
			try (FileLock lock = os.getChannel().lock()) {
				FileChannel fc = os.getChannel();
				fc.write(ByteBuffer.wrap((line + System.lineSeparator()).getBytes()));
			}
		}
	}

}

测试:

public class FileWriteTest {

	public static void main(String[] args) throws Exception {
		FileWriter fileWriter = new FileWriter(new File("f:/test/test.txt"));
		ExecutorService es = Executors.newCachedThreadPool();
		for (int i = 0; i < 100; i++) {
			es.submit(new Runnable() {

				@Override
				public void run() {
					try {
						fileWriter.write(ProcessHandle.current().pid() + "..." + UUID.randomUUID().toString());
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			});
		}

		es.shutdown();
		es.awaitTermination(10, TimeUnit.MINUTES);
	}
}

FileLock是jvm级别的锁,并非针对某个线程,因此在同一个jvm,多线程的情况下需要加同步