1

I hava a memory mapped file where I can write values as follows:

public class HelloWorld{

    public static void main(String []args){

        try {
            // OPEN MAPPED MEMORY FILE
            file = new RandomAccessFile("myMemoryMappedFile", "rw");

            // ASSIGN BUFFER
            fileBuffer = file.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, 1024);

            // INITIALIZE ALL FILE TO 1
            for (int i = 0; i < fileSize; i++)
            {
                fileBuffer.put((byte) 1);
            }

            MyClass myClass = new MyClass();
            myClass.writeExternal(???????);    // HOW DO I LINK THE fileBuffer and the ObjectOutput?

        } catch (FileNotFoundException ex) {
            System.err.println("Error while opening a new database: file not found.");
            return false;

        } catch (IOException ex) {
            System.err.println("Error while opening a new database: IO exception.");
            return false;
        }

    }

}

And I have a class which implements Externalizable which overrides writeExternal method:

public class MyClass implements Externalizable {

    public long epochBegin = -1;
    public long epochEnd = -1;
    public int data = -1;

    public MyClass(){
    };    

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {

        byte[] epochBeginByte = ByteBuffer.allocate(4).putInt((int)this.epochBegin).array();
        byte[] epochEndByte = ByteBuffer.allocate(4).putInt((int)this.epochEnd).array();
        byte[] dataByte = ByteBuffer.allocate(4).putInt((int)this.data).array();

        out.write(epochBeginByte);
        out.write(epochEndByte);
        out.write(dataByte);

        out.flush();

    }

}

I would like to invoke the method writeExternal over the memory mapped file myMemoryMappedFile at position 10 bytes. So in the file, at byte 10 there will be 12 bytes containing the variables this.epochBegin, this.epochEnd and data.

Unfortunatelly I am totally stuck on how to link both things, the memory mapped file and the writeExternal procedure. Any tip on how to continue is welcomed.

M.E.
  • 4,955
  • 4
  • 49
  • 128
  • 1
    You need to put a `ByteArrayOutputStream` under the `ObjectOutputStream`, do the writes, close, get the byte array, and put that to the `MappedByteBuffer`. As you can see there is no advantage to using mapped I/O in this situation: it is in fact slower and wastes memory. – user207421 May 21 '20 at 00:03
  • Could you please elaborate a bit this? How do I put a `ByteArrayOutputStream` under the `ObjectOutputStream`?. The mapped I/O is required as it is used as IPC mechanism (the included code is just a simplified replicable example). – M.E. May 21 '20 at 10:55

0 Answers0