Question

I have some serialized classes which have several members that are classes that initiate some life-long threads.(while(true){doSth();sleep(100)}). Now I wonder which is a good practice to handle them. Wether I should create those objects by implementing read/writeObject methods or I should divide the factories for creating those objects and take out all transient object creations in a different create method and run the both factory methods when I want to create them from scratch and use only the transient factory method for the case I read them from a serialized stream?

Was it helpful?

Solution

Wether I should create those objects by implementing read/writeObject methods

First off, to have entities that you are serializing manage their own threads is the first red flag. Entities that are serialized should most likely be data passing objects only. Business logic and certainly thread tasks should live elsewhere. Having the readObject() method magically fork threads just gives me the willies even thinking about it.

I would have the class that is reading these deserialize them and then register them with some sort of entity/task manager. Then the manager would manage the thread pools (think ExecutorService) that run the tasks the entities need to operate appropriately. Entities, especially serialized ones, should not do that on their own.

run the both factory methods when I want to create them from scratch and use only the transient factory method for the case I read them from a serialized stream?

If you need to precisely manage these objects then you could have the entity manager do the actual construction and task forking I guess. Or just have a register() method there so whenever someone constructs one or deserializes one of these, they register it.

OTHER TIPS

This is a poor architecture for a number of reasons. Threads with a while (true) { sleep } structure are a big red flag on that front, it's incredibly rare that they are actually the best way to do something.

In this case use a ScheduledExecutorService with a thread pool to handle all the tasks, and then register the objects with that service. I'd be a bit wary of having the objects register themselves too (in fact if they do it in their constructor it's actively broken from a thread safety point of view). Really a factory or manager class should be handling that too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top