Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Marking a variable static final is thread safe  RSS feed

 
Mintoo kumar
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Folks,

I have a bit confusion that if i mark a variable "static final ", is it threadsafe?

like: public satic final MyObject myObj;

_____________________________
Mintoo
SCJP 1.4
_____________________________
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, not generally.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would say that the variable itself is threadsafe, but if it's a reference variable and the object it refers to is mutable, then that object may not be threadsafe. Unless it's designed to be threadsafe.

More generally, this is true for any final variable, not just static variables. If they're final and primitive, or final and referring to an immutable class, then they're thread-safe. Otherwise they're probably not thread-safe (unless you determine otherwise through more detailed analysis).
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jim, good point.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!