• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

IS an Instance variable threadsafe?

 
samir vasani
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Expert,

Please explain me with the example.
 
Kuma Phani
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, instance variable in enum is threadsafe.

public enum BMW{

INSTANCE;

}

INSTANCE - is thread safe.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kuma Phani wrote:Yes, instance variable in enum is threadsafe.

Can you answer why that particular type of reference is thread safe?

If the question is if, in general, variables belonging to an instance are thread safe, the answer is no. If the question is if a variable belonging to an instance can be made thread safe, the answer is yes. Here is an example of an instance variable that is not safe:



Here is an example of one that is safe:
 
Tim Holloway
Saloon Keeper
Pie
Posts: 18277
56
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kuma Phani wrote:Yes, instance variable in enum is threadsafe.

public enum BMW{

INSTANCE;

}

INSTANCE - is thread safe.


FALSE

No variable or object in Java is intrinsically threadsafe. If an object is accessible by 2 different threads, they can totally slaughter it.

To be threadsafe, mechanisms must be employed to enforce threadsafe access. The most common mechanism used for this purpose is Java's built-in "synchronized" capabilities. You use the "synchronized" modifier to ensure that critical properties, methods, or even the class instance as a while are only accessed according to proper threading protocols.

Nothing is synchronized by default, however.

For an example of a class whose methods have been made threadsafe, look at the java StringBuffer class. Then contrast it with the newer and non-threadsafe StringBuilder class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic