From 4d3db99283199ffd8d5fdbe84933444d25b980f4 Mon Sep 17 00:00:00 2001 From: pjulien Date: Sat, 31 Jan 2015 11:14:59 -0500 Subject: [PATCH] Issue #136 The satellite data of the ``ByteBuffer`` cannot be modified in any way and stay thread safe in the presence of concurrent readers. This implementation is simple and does introduce an allocation, however without it multiple readers will quickly and continuously encounter ``IndexOutOfBoundsException`` exceptions. An alternative, but possibly more controversial, implementation would be to use ``Unsafe``. Using ``Unsafe``, it's possible to do an array copy with a provided buffer index. Change-Id: I851d4034e753b3be2931ee2249ec2c82dde43135 --- java/com/google/flatbuffers/Table.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/java/com/google/flatbuffers/Table.java b/java/com/google/flatbuffers/Table.java index c42638944..3ed99ad81 100644 --- a/java/com/google/flatbuffers/Table.java +++ b/java/com/google/flatbuffers/Table.java @@ -18,6 +18,7 @@ package com.google.flatbuffers; import static com.google.flatbuffers.Constants.*; import java.nio.ByteBuffer; +import java.nio.ByteOrder; // All tables in the generated code derive from this class, and add their own accessors. public class Table { @@ -46,13 +47,13 @@ public class Table { if (bb.hasArray()) { return new String(bb.array(), offset + SIZEOF_INT, bb.getInt(offset), FlatBufferBuilder.utf8charset); } else { - // We can't access .array(), since the ByteBuffer is read-only. + // We can't access .array(), since the ByteBuffer is read-only, + // off-heap or a memory map + ByteBuffer bb = this.bb.duplicate().order(ByteOrder.LITTLE_ENDIAN); // We're forced to make an extra copy: byte[] copy = new byte[bb.getInt(offset)]; - int old_pos = bb.position(); bb.position(offset + SIZEOF_INT); bb.get(copy); - bb.position(old_pos); return new String(copy, 0, copy.length, FlatBufferBuilder.utf8charset); } } @@ -77,12 +78,11 @@ public class Table { protected ByteBuffer __vector_as_bytebuffer(int vector_offset, int elem_size) { int o = __offset(vector_offset); if (o == 0) return null; - int old_pos = bb.position(); - bb.position(__vector(o)); - ByteBuffer nbb = bb.slice(); - bb.position(old_pos); - nbb.limit(__vector_len(o) * elem_size); - return nbb; + ByteBuffer bb = this.bb.duplicate().order(ByteOrder.LITTLE_ENDIAN); + int vectorstart = __vector(o); + bb.position(vectorstart); + bb.limit(vectorstart + __vector_len(o) * elem_size); + return bb; } // Initialize any Table-derived type to point to the union at the given offset.