Is protobuf in java thread safe?

I have the following protobuf msg:

message Counts {
    repeated int32 counts = 1;
}

which is shared between threads Rand Was a builder:

private final Counts.Builder countsBuilder;

The topic Rwill only read from countsBuilder, and Wwill only be written to countsBuilder. The common creator will be read, written, and (at some point) created and transmitted over the network.

AFAIK, simultaneous reading of messages is fine, but something else needs to be synchronized by the developer at a higher level? So, I can’t write and read the shared builder at the same time?

If this is not essentially thread-safe, I’m thinking of using some kind of thread-safe Collection<Integer>, which I will use to read / write and (at some point) create a completely new message right before sending it over the network. Or am I missing something?

Thank!

EDIT 1: I am using protobuf 2.4.1 and java 6

EDIT 2: Some terms and spelling corrections.

+3
source share
1 answer

You should be fine if you synchronize both reading and writing:

synchronized (countsBuilder) {
   // modify countsBuilder
}

But remember that you also need to make sure that when building a message there are no race conditions; Writer thread is not allowed to be written after the creation of the message.

+1
source

All Articles