Я хочу реализовать два простых приложения в Java, которые взаимодействуют друг с другом, сохраняя и читая данные из общего файла, отображенного в памяти. Одно из приложений должно сохранить некоторые данные - например, два целочисленных значения. Другое приложение должно получить данные и вывести значения на консоль.
Вопрос в том, как связать эти два приложения (например, производитель / потребитель)? Как Читатель может узнать, что есть новое значение для чтения из MappedByteBuffer?
Writer. java
public class Writer {
static int length = 512;
public static void main(String[] args) {
try {
RandomAccessFile file = new RandomAccessFile("test2", "rw");
FileChannel channel = file.getChannel();
MappedByteBuffer out = channel.map(FileChannel.MapMode.READ_WRITE, 0, length);
out.putInt(1);
out.putInt(2);
out.putInt(3);
out.putInt(4);
out.force();
channel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Читатель. java
public class Reader
{
public static void main(String[] args) throws Exception
{
try (RandomAccessFile file = new RandomAccessFile("test2", "r"))
{
//Get file channel in read-only mode
FileChannel fileChannel = file.getChannel();
//Get direct byte buffer access using channel.map() operation
MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
if (buffer != null) {
IntBuffer ibuf = buffer.asIntBuffer();
int currentPos = 0;
while(ibuf.hasRemaining()) {
int c = ibuf.get();
currentPos = ibuf.position();
if(c != 0) {
System.out.println(currentPos + " -> " + c);
}
}
}
}
}
}