GeeCON Prague 2014*
The moose likes Threads and Synchronization and the fly likes What will happen when other threads use the following code? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "What will happen when other threads use the following code?" Watch "What will happen when other threads use the following code?" New topic
Author

What will happen when other threads use the following code?

azuki ooh
Greenhorn

Joined: Nov 07, 2008
Posts: 20
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

Joined: Jan 28, 2003
Posts: 4181
    
  21

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.


Steve
 
GeeCON Prague 2014
 
subject: What will happen when other threads use the following code?