Is protobuf in java thread-safe?
java, protocol-buffers, thread-safety
Solution
You should be fine if you synchronize both your read and writes:
synchronized (countsBuilder) {
// modify countsBuilder
}
But remember that you also need to make sure that there aren't any race conditions when building the message; the writer thread is not allowed to make any writes after the message has been built.
Problem
I have the following protobuf msg defined: ``` message Counts { repeated int32 counts = 1; } ``` which is shared between threads `R` and `W` as a builder: ``` private final Counts.Builder countsBuilder; ``` Thread `R` will only read from `countsBuilder` and `W` will only write to `countsBuilder`. The shared builder will be read, written-to and (at some point) built & sent over the network. AFAIK, concurrent reads to messages are fine, but anything else must be synchronized at a higher level by the developer? So, I can't actually write and read to the shared builder at the same time? If this is not inherently thread-safe, I'm thinking of using some kind of thread-safe `Collection<Integer>` which I'll use for reading/writing and will (at some point) create a brand new message right before sending it over the network. Or am I missing something? Thanks! EDIT 1: I'm using protobuf 2.4.1 and java 6 EDIT 2: Some terminology and spelling fixes.