Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What will happen when other threads use the following code?

 
azuki ooh
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Multiple objects of MyClass (given below) are used in a program that uses multiple Threads
to create new integer count. What will happen when other threads use the following code?

 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the same instance of the class is used in multiple threads, it is not safe because the yourNumber value is can be accessed/modified by multiple threads in an uncontrolled fashion. Access to the static counter looks safe as long as the counter is only accessed via the method. That can be hard to enforce which is why I would prefer the use of a static final AtomicInteger there. You would neither be able to change the instance of the integer, nor change or get its value without going through atomically safe methods.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic