I have use case where we have to handle millions of messages. I have a class which will handle these messages. I dont want to create an instance of the class for every message as we keep getting millions of messages. So I just want to maintain a single instance but the problem is i get different of messages so based on the type of messages the value to my arguments keep changing. So the question is should I create different instance for each message and cache them or just create a single instance(cache it) and then based on the message type change the value of the arguments.
Asked
Active
Viewed 63 times
-1
-
1Sounds like you should have one instance per message type... – Jon Skeet Oct 27 '16 at 16:54
-
What would be the problem if I just maintain a single instance instead of one instance per message type. – Vaishu13 Oct 27 '16 at 16:56
-
Well you'd need to mutate it, which means it would immediately lose any hope of being thread-safe, for one thing. We don't really know what your object does, but if it's reasonable to make it immutable, that sounds like a good idea to me... and if there are only a limited number of types, then one instance per type should be fine. – Jon Skeet Oct 27 '16 at 16:59
-
In case if it is single threaded application then in that case one instance would be okay. What I am really trying to understand is if maintaining one instance and changing the value of arguments based on the message type will have any down sides. – Vaishu13 Oct 27 '16 at 17:03
-
It would *work*, but mutable types are generally harder to maintain and reason about. If that's the *only* thing that needs to change in your handler, that seems like a bad idea. But your question really doesn't give much context... – Jon Skeet Oct 27 '16 at 17:04
-
Since they are mutable it is better to different instances instead of single instance. – Vaishu13 Oct 27 '16 at 17:14
-
We can't tell for sure, because your requirements are very unclear. The more information you can provide, the more helpful we can be. – Jon Skeet Oct 27 '16 at 17:20
2 Answers
1
You should use single instance per message. That should be the way to go as John mentioned.
If you use only instance for all message types it will be difficult for you to keep track of the instances
What you can do is have an ArrayList
where you can keep adding these message instances.

Pritam Banerjee
- 17,953
- 10
- 93
- 108
1
Take a look into static factory methods. This will give you the ability to create (or more importantly, not create) objects as you need them, while handling the logic of whether or not to create them or use an existing object. Creating multiple static factories should give you what you need without creating millions of unnecesary objects.

Community
- 1
- 1

Trevor Bye
- 686
- 1
- 6
- 26