I've got a class, which is locking files. (See below.) Now, I've got a unit test, which asserts the successful locking between two threads in the same VM. However, I'd actually have the locks working between two VM's. Which brings up the question: How would I lauch another JVM in a separate process?
Thanks,
Jochen
public class FileLocker {
public static interface StreamAccessor {
InputStream getInputStream();
OutputStream getOutputStream();
}
public static void runLocked(File pFile, Consumer<StreamAccessor> pConsumer) {
Function<StreamAccessor,Object> function = (sa) -> { pConsumer.accept(sa); return null; };
callLocked(pFile, function);
}
public static <T> T callLocked(File pFile, Function<StreamAccessor,T> pConsumer) {
try (final RandomAccessFile raf = new RandomAccessFile(pFile, "rw");
final FileChannel channel = raf .getChannel();
final FileLock lock = channel.lock()) {
final StreamAccessor sa = new StreamAccessor() {
@Override
public OutputStream getOutputStream() {
return Channels.newOutputStream(channel);
}
@Override
public InputStream getInputStream() {
return Channels.newInputStream(channel);
}
};
final T t = pConsumer.apply(sa);
return t;
} catch (Throwable thr) {
throw Exceptions.show(thr);
}
}
}