Reputation: 221
Say I am running a multithreaded program, a server, and this handles incoming requests in different threads (one per request). I have a RequestHandler object that can handle a single request with a method,
void handleRequest(Request r);
Say there are no concurrency issues in terms of reusing a single RequestHandler object between threads. Would there ever be any performance benefit in creating one RequestHandler per thread? Or is it better to reuse a single RequestHandler between threads (each maintaining a reference to the same RequestHandler)?
Edit: In reponse to Jack's answer- yes, we are assuming that the handleRequest method is completely thread safe and does not contain any synchronization block or object.
Upvotes: 0
Views: 829
Reputation: 133577
If the implementation of handleRequest(Request r)
is completely thread safe and it doesn't contain any synchronization block or object then I don't see any benefit/disadvantage in having a single shared object compared to separated objects.
This implies that the object which implements handleRequest
doesn't have any mutable state of course.
Every thread can enter the method independently by following its code path, this would be the same with multiple objects but you would have different this
references (unless the method is static
). Now if the code is thread safe then almost nothing is done through the implicit this
reference unless calling other thread safe methods so it's equivalent.
Upvotes: 4