This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Calling thread unsafe methods from thread safe method  RSS feed

 
Dag Frode Olsen
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

Having done most of my development work in a bean environment where I don't really have to worry too much about threads I now find myself doing some real thread work...

So you don't have to worry about multi-threaded access to local variables, because local variables reside on the Java stack and each thread has it's own Java stack...

Does this mean that if you have the following code:



is thread safe, even though UnsafeClass is not thread safe, because UnsafeClass is now part of the thread's 'safe' stack?

Cheers! And thanks!
 
Vinod K Singh
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it is thread safe because 'UnsafeClass unsafeClass' is scoped to 'aMethod' only. So no other thread can see and change variables of this instance.
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well yes and no!
It depends alot on how the methods method1 and method2 are defined.
It may so happen that method1 and method2 touch a static variable in a non-thread-safe way.(as you said UnsafeClass is not threadsafe)
In such a case even though unsafeClass is a local variable, the invocation of method1 and method2 may wreck havoc.

Also, if i change your code to:



then, the local variable unsafeClass "escapes" from the method and can be used in a non-thread-safe way.

What i am trying to say is that, making blanket statements like
is thread safe, even though UnsafeClass is not thread safe, because UnsafeClass is now part of the thread's 'safe' stack?

have to made with care and *(conditions apply )

It is correct that local variables are on the method stack which is not shared among threads but the objects are always created on the heap.
So, if it may so happens that someone can get hold of this object (eg: if the reference escapes from the method) then no longer is the thread safety guaranteed.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!