0
class RequestMessage{

public byte[] getMsgAsBytes() throws UnsupportedEncodingException{
        ByteBuffer reqBuffer = ByteBuffer.allocate(PAYLOAD_SZ);
        reqBuffer.put(xxx);
        reqBuffer.putInt(xxx);
        reqBuffer.put(xxx);
        reqBuffer.position(0);
        return reqBuffer.array();
    }
}

The RequestMessage class is then used by a singleton in the following manner(read-only).The singleton would be accessed multiple threads in tandem.

private void sendRequest(...) throws Exception {
        RequestMessage reqMessage = new RequestMessage( );
        gateway.sendAsyncMessage(...., reqMessage.getMsgAsBytes());

}

Is this usage of bytebuffer thread-safe?
We do see occasional corruption of the array contents ,and need to ascertain the casue for that.

IUnknown
  • 9,301
  • 15
  • 50
  • 76
  • 2
    It depends on what the `xxx`-values are. Can they be mutated? Where do they come from? – Hulk Jan 04 '19 at 08:13
  • 1
    If the bytebuffer is allocated as shown (within the `getMsgAsBytes()` method) then each thread will have it's own bytebuffer, so it will never be shared between threads. – Thomas Kläger Jan 04 '19 at 08:23
  • 2
    As Thomas said, the things you showed us here are not problematic. What you did not show us is where the `xxx` values come from - if they come from some shared source, that might be a problem. – Hulk Jan 04 '19 at 08:30

2 Answers2

0

if the xxxes are instance fields of the RequestMessage, it is thread safe: as both the RequestMessage and the ByteBuffer are local variables, they cannot be altered by another thread.

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
0

What does the observed corruption consist of ?

If those xxx are instance fields of RequestMessage AND THEY ARE IMMUTABLE (meaning no setters and their value is set and fixed at constructor invocation time) and the state of any objects constituting the xxx is itself also immutable then things should be incorruptible.

Otherwise there is no avoiding occasional corruption, because there is no way to avoid objects from being passed to other threads, if that is what some other portion of the system thinks it should do. And there is no way to avoid state being mutated in unpredictable manners and/or sequencings exactly while you're reading that state.

Erwin Smout
  • 18,113
  • 4
  • 33
  • 52