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.
When methodA is called, a copy of k is passed as argument. The method works only in this copy. Therefore, in this case there's no need to deal with tread-safety issues. [ June 04, 2007: Message edited by: Leandro Melo ]
SCJP 1.4, SCWCD 1.4
Joined: Feb 26, 2005
Hi Leandro Melo, 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.
Joined: Mar 27, 2004
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?
Joined: Feb 26, 2005
Hi Leandro Melo, Thanks for the nice reply with the example.The concept is 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).
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus