aspose file tools
The moose likes Threads and Synchronization and the fly likes Is there any alternative for synchronization?  Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Is there any alternative for synchronization?  " Watch "Is there any alternative for synchronization?  " New topic
Author

Is there any alternative for synchronization?

Anand Jooshi
Greenhorn

Joined: Jun 15, 2009
Posts: 8
HI friends,

Is there any alternative for synchronization?
If we are not allowed to use synchronization block or method, how we can make the code thread safe.

I faced this question while going through an interview!

Thanks,
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 35252
    
    7
The java.util.concurrent package has a whole range of classes that can be used to make multi-threaded code thread-safe without explicitly using the "synchronized" keyword, if that's what you're asking.

The ThreadLocal class may also help, as may the "volatile" keyword.

And, most fundamentally, multi-threadedness is only a problem if there is shared, mutable state. If you can avoid that, then the code is multithread-safe.


Android appsImageJ pluginsJava web charts
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16695
    
  19

I faced this question while going through an interview!


If only this question ever comes up on any interview that I ever go to....

Synchronization is for a type of locking called "pessimistic locking". It is based on the theory that if you don't protect the code, the threads will step on each other and corrupt the data.

This question is perfect to go into the theory of "optimistic locking" -- how you code with the assumption that the threads won't step on each other. This can lead to how you code something to be done in an atomic fashion, and how you can use the CAS methods of the atomic classes to do so. In other words, you use separate variables to do all the operations without exposing interim data -- then use the CAS to swap the data atomically. A CAS failure is considered a collision which will trigger a rollback (and/or retry).

This question is also perfect for a discussions about transactions -- and commit and rollbacks.

Henry

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Anand Jooshi
Greenhorn

Joined: Jun 15, 2009
Posts: 8
Thanks guys ...!

Both of you put me in the right direction
 
jQuery in Action, 2nd edition
 
subject: Is there any alternative for synchronization?
 
Similar Threads
synchronization in an application server
single raf vs. raf per client
Why we should prefer synchronization?
file parsing and synchronization
advantage of synchronization