How to implement CustomMessage?Do we need to do some copy job when implementing CustomMessageCodec?

451 views
Skip to first unread message

whitew...@gmail.com

unread,
May 29, 2017, 7:42:51 AM5/29/17
to vert.x
Hi there:

Is there any examples about CustomMessage & CustomMessageCodec?
I just saw this example:
and got confused since in the source code e.g. StringMessageCodec:
the transform method is implemented as following and there is a comment
@Override
public String transform(String s) {
// Strings are immutable so just return it
return s;
}
and for other message codecs e.g. json object message codec:
@Override
public JsonObject transform(JsonObject jsonObject) {
return jsonObject.copy();
}
and byte array message codec:
@Override
public byte[] transform(byte[] bytes) {
byte[] copied = new byte[bytes.length];
System.arraycopy(bytes, 0, copied, 0, bytes.length);
return copied;
}
as we can see here, if the message object is not immutable, then in the transform method, we should copy the original obj.
but in the vertx-example custom message codec transform method
it does not copy the original object:

@Override
public CustomMessage transform(CustomMessage customMessage) {
// If a message is sent *locally* across the event bus.
// This example sends message just as is
return customMessage;
}

thus my guess here is the example is wrong, but I am not sure about this
any suggestions?

Thanks

Paulo Lopes

unread,
May 29, 2017, 7:55:51 AM5/29/17
to vert.x

whitew...@gmail.com

unread,
May 29, 2017, 8:26:53 AM5/29/17
to vert.x
Hi Paulo:

Thanks for the reply
Any explanation about why using non-copy transform method?
since all non-immutable objs get copied in the original default message codecs
Besides, in the Message Codec interface there is a bold message "Instances of this class must be thread-safe as they may be used concurrently by different threads."
but when checking the examples, those implemented message codecs seems like not thread-safe, since there is no synchronized, lock, juc etc.
so my question is do we need to follow the instruction which tells us to make the message instances thread-safe or  the vert.x will handle these for users?

Tim Fox

unread,
May 29, 2017, 9:33:39 AM5/29/17
to vert.x
The CustomMessage class is immutable - it has all final fields, therefore does not need to be copied.

The CustomMessageCodec is indeed thread safe, it does not locks etc as it stores no state. In general MessageCodec classes should never store state so don't need any locking.

whitew...@gmail.com

unread,
May 29, 2017, 10:20:13 AM5/29/17
to vert.x
Thanks Tim, this post is really helpful, make sense every thing

Cheers
Reply all
Reply to author
Forward
0 new messages