I kept on reading local objects are thread safe in Java if it's not been passed to another thread. can someone explain why it's thread safe because objects are not maintain ed in stack? also an example/pattern how someone can pass local object to another thread?
-
Start reading [here](http://docs.oracle.com/javase/tutorial/essential/concurrency/) – Boris the Spider Aug 24 '14 at 12:54
-
Let's say you rent a room. Every time you rent the room to someone, you have to be careful that you haven't already rented the room to someone else. Now if you dedicate the room to a single person, and this person is thus the only one who can rent the room, you don't have to do any checks before renting it anymore. The room isn't shared, so there is no room (no pun intended) for conflicts. thread-safety is all about shared state. No shared state, no problem. – JB Nizet Aug 24 '14 at 13:03
-
As Marko says, if an object can only be accessed from a single thread it is, for all practical purposes, "thread safe". A "local variable" is only accessible within the method that declares it, so any objects referenced from local variables are only accessible locally, unless you somehow "pass" the object reference out to another thread. – Hot Licks Aug 24 '14 at 13:04
-
"Why is it thread safe if it's not been passed to another thread?" Well, it's because it's not been passed to another thread. If only one thread can use the object, there's zero chance that two threads will try to use it at once. – user253751 Aug 24 '14 at 13:11
-
possible duplicate of [In Java, do methods that dont use static or class variables need to be synchronized?](http://stackoverflow.com/questions/4766179/in-java-do-methods-that-dont-use-static-or-class-variables-need-to-be-synchroni) – Basilevs Aug 24 '14 at 14:58
-
1"...if it's not been passed to another thread..." If thread A creates an object O, and it does not store a reference to O where any other thread can see it, then it should be pretty obvious that no other thread will be able to use object O. – Solomon Slow Aug 24 '14 at 16:20
2 Answers
If you use each object from a single thread, then it is very hard to create a program which would fail to be thread-safe. To "achieve" non-thread-safety in that case, the object would have to internally make use of some globally shared non-thread-safe state, so different objects would access the same from different threads.
The above explains why the general wisdom is that local object are thread-safe to use.

- 195,646
- 29
- 319
- 436
A local object is thread safe because it can only be accessed by one thread.
If you pass it to another thread eg via a Queue it is no longer local unless only one thread accesses it. Eg if the sending thread no longer accesses it and the queue is thread safe your object can be treated as thread safe if only one thread has a reference to it.

- 525,659
- 79
- 751
- 1,130