So let’s say I have a class X with a method m. Method m is NOT synchronized and it doesn’t need to be since it doesn’t really change the state of the object x of type X.
In some threads I call the method like this: x.m(). All these threads use the same object x.
By how many threads can be this method (method m) called on object x simultaneously?
Can be the fact that the method is called by, let’s say, 100 threads a bottleneck for my application?
thanks.
Other’s have answered your direct question.
I’d like to clear up something that is could be a misconception on your part … and if it is, it is a dangerous one.
That is not a sufficient condition. Methods that don’t change state typically need to be synchronized too.
Suppose that you have a class Test with a simple getter and setter:
Is the getter thread-safe?
Why? Because unless the threads that call
getFooandsetFoosynchronize properly, a call togetFoo()after a call tosetFoo(...)may see a stale value forfoo.This is one of those nasty cases where you will get away with it nearly all of the time. But very occasionally, the timing of the two calls will be such that the bug bites you. This kind of bug is likely to slip through the cracks of your testing, and be very difficult to reproduce when it occurs in production.
The only case where it absolutely safe to access an object’s state from multiple threads without synchronizing is when the state is declared as
final, AND the constructor doesn’t publish the object.