Skip to main content
GameDev.net gamedev.net
🔒 Locked

java Threads questions

Started by makingroulette Nov 19, 2005 at 8:24 AM 1 replies 750+ views
Original Post
makingroulette
makingroulette
If two or more threads share access to an object instance, and that object instance has methods that are not synchronized, My question is, are local variables declared in a method/function that is not declared as synchronized at risk of the race condition? i think they are, but im not entirely certain, because im thinking that each function call has its own set of variables. so if two threads call the same function on the same object, each function call will have its own set of local variables. when i say local variabls, i am refering to variables declared in the function. I am not referring to object instance variables my other question is, is it correct that when a synchronized static method is called on a call, the thread acquires the lock on the class object of the class, and this prevents any other Thread from calling static methods on that object. It does not prevent access to not static synchronized methods. Many thanks for your feedback
cmptrgear
cmptrgear
I am not 100% sure of this (actually I am just covering my butt if I am wrong) but local variables are local to the thread only.

If you have a lock in a static method that lock only affects threads which call the method.

So if thread 1 aquires a lock in foo()
Thread 2 can happily perform calculations in bar() regardless of what Thread 1 does assuming that bar() does not have the same lock as foo()
"Pfft, Facts! Facts can be used to prove anything!" -- Homer J. Simpson
shmoove
shmoove
Local variables are allocated on the call stack and every thread will have it's own, so they are not shared.

As for the static synchronized method, you have it backwards, other threads are able to access regular methods, but not other static synchronized methods in that class or any other code block sharing that monitor.

In other words: what cmptrgear said.

shmoove

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.