I have a simple question about threads.
int methodA(int k)
Is the above method thread safe?or is it necessary to add synchronized keyword to make itthread safe?I have a small confusion as this method deals with method variables only and not any instance variable.Please clarify.
Thanks for the quick reply.But I have a doubt.Supposing if there are two threads which are accessing the same method at the same time, and one thread passes value 10 for k, and another thread 20 for k, how will the method be thread safe?sorry if my question is too basic,I do not have real time experience in threads.
Thread-safety is associated with the concept of global or somehow shared data. Regarding your question specifically, there's an extra thing to discuss about , which is the fact you're passing a built-in type (an int). Java passes by value. Therefore, when thread1 passes 10 and thread2 passes 20, actually, copies of those values are being incremented. So, unless you assign the return value of the method to the original k, it's not modified. Check out this code:
Therefore, it doesn't make much sense to talk about threa-safety in this situation. Now, suppose methodA doesn't have any parameters. It's just a method that modifies an internal variable (suppose k) of class Test. Then, it might be the case where methodA needs to be synchronized. Because, others threads (or classes) might share the same k in the same instance of class Test.
Another situation would be for example, if methodA received an object as its argument. And this object is an HTTP session object shared by your application (or maybe, a member of a Singleton). Again, this is a typical situation where you would need to synchronize access to this specific object.
Is it clear now?
Originally posted by rajaraman navaneethan:
But I have a doubt.Supposing if there are two threads which are accessing the same method at the same time, and one thread passes value 10 for k, and another thread 20 for k, how will the method be thread safe?
Local variables and method parameters are stored on the stack. Each thread has its own stack, and each method call gets its own space on the stack of the current thread (the latter is why recursion actually works).