0

I'm willing to use a ByteBuffer to inter thread communication of JNI and C++. I couldn't find in the documentation whether ByteBuffer's getInt() is blocking or not. So, do I need to do something like:

if(byteBuffer.asIntBuffer().hasRemaining())
    byteBuffer.getInt();
Thread.sleep(1000);

or

byteBuffer.getInt();

will block so sleep is unnecessary?

Iswanto San
  • 18,263
  • 13
  • 58
  • 79
quimnuss
  • 1,503
  • 2
  • 17
  • 37
  • 1
    It's not a stream, it doesn't wait for any input, it just reads a fixed memory location. – ZhongYu Apr 04 '13 at 16:05
  • `ByteBuffer`s have no synchronization at all; they're not thread safe. – Louis Wasserman Apr 04 '13 at 16:11
  • @Louis They're not atomic? What do you mean? – quimnuss Apr 04 '13 at 16:13
  • 1
    @quimnuss: No, they're not atomic. `ByteBuffer` has no thread safety whatsoever. If it's not documented, it's not there. – Louis Wasserman Apr 04 '13 at 16:14
  • @zhong they're two threads, not two processes. – quimnuss Apr 04 '13 at 16:16
  • I think you have confused Buffers with Channels. Buffers are just some memory (that may be optimized for moving data to certain channels, like either native malloc'ed memory or memory mapped from some device or file). Channels are used to copy data to/from buffers, and they can indeed be blocking or non-blocking (and in the latter case signal a Selector when done). – mihi Apr 04 '13 at 16:18
  • there's no guarantee that putInt/getInt are atomic like read/write normal `int`. – ZhongYu Apr 04 '13 at 16:20
  • What event would it block on? Not a real question. – user207421 Apr 14 '13 at 01:12

1 Answers1

3

According to the documentation, if there aren't at least four bytes in the buffer, it will throw BufferUnderflowException. That suggests it doesn't block (as does the fact that the word "block" doesn't appear on its documentation page at all).

But note that your sleep solution won't work, because you're doing the sleep call after calling getInt, which will have already thrown an exception if there isn't enough data there yet. You need to ensure the buffer has at least four bytes in it before you call getInt.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875