I'm implementing a library for a network protocol that involves sending data at a constant rate of 50Hz. The actual transmission of data will be done on a separate thread. As part of the library, there will be a class that represents all the data that needs to be sent, and the library will take care of serializing it and transmitting it.
My issue is that I'm not sure how to design this data class. The options I was thinking of were:
- Single mutable object. The sending thread will lock the object, serialize it, then unlock it so the client can modify it again. I think this is probably the worst option.
- Mutable object, that is cloned by the library when passed as an argument. This way the calling method can modify the existing object while not interfering with the send thread.
- Immutable object, so a new one will have to be created each time by the calling method, and repopulated with the data.
I was not sure about going the cloning route since a new object will have to be created and populated 50 times per second.
For the cloning options, I was also wondering what the best way to clone an object like this would be. Should I take advantage of Object.clone(), which I have heard mixed things about, or implement a custom copy method/constructor? If I make something custom, what would be the most robust way of implementing it? Basically, I'll have to write in the code to copy every field of the source object one by one, and I was hoping there would be some easier way of doing it.