This content has been marked as final. Show 3 replies
799566 wrote:Yes, each invocation will have its own local variable instances. Concurrent reads will always be safe, as long as no changes are made to object state.
My guess would be that even if the methods of the Set are static, the variables inside the method would still be local the the thread stack and so each thread would have it owns local variables, with no interference. Is that correct?
What you need to worry about is concurrent modifications or even a read and a write happening at the same time. If one thread is reading from the set while another is modifying it (for example adding or removing an entry), the results are "unspecified", but generally bad. Read into synchronization if you want to learn more about how to deal with concurrent access.
Ok great. There are no changes to the state of the set.
Your post doesn't make much sense.
Are methods of a static variable thread safeStatic variables don't have methods. Classes have methods.
Since the Set is static, are the methods of Set also staticNo. Of course not. The methods of Set are unchanged. They are what the Javadoc says they are.
and can two request threads interfere with the results of the contains method?Yes, of course they can, if the Set is being updated concurrently.
I'm concerned about this scenario: one thread passes a value to contains() which is in our Set, then before contains() begins to search for the value, another thread passes a different value to contains() which is not in our Set, then contains searches only for the latter, and would return false for both threads.The read-only case is thread-safe against other read-only cases, but not against the case where there is a concurrent update. The only way you can protect against that is via synchronization or locking; and you have to protect the read-only case against the read-write case, so you have to apply syncrhonization or locking to the read-only case as well as the read-write case.
You should synchronize access to this Set. If you have extreme concurrency requirements you might go as far as using shared read locks and read write locks but I doubt you will ever notice the difference.
My guess would be that even if the methods of the Set are staticThey aren't, and the question has no bearing on whether they are thread safe. These aspects are completely independent.
the variables inside the method would still be localMethod variables are always local regardless of whether it is static or not.
and so each thread would have it owns local variablesAgain that is always true regardless of whether static or not.
with no interferenceWith no interference to local variables in other threads, yes. Thread safety has nothing to do with any of that, or with static either. It has to do with object state.