• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

IS an Instance variable threadsafe?

 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Expert,

Please explain me with the example.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, instance variable in enum is threadsafe.

public enum BMW{

INSTANCE;

}

INSTANCE - is thread safe.
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:
 
Saloon Keeper
Posts: 28749
211
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic