views:

521

answers:

4

Is there any alternative to synchronize class or method without using 'synchronized' keyword in java ?

Thanks, Mallikarjun Kokatanur

A: 

You could use a "lockable" resource, such as a file.

You can also look at java.util.concurrent.locks which has more sophisticated locking.

Why don't you want to use synchronized?

djna
+2  A: 

You may want to look at the changes introduced with the concurrency package, to JDK 5.

http://java.sun.com/developer/technicalArticles/J2SE/concurrency/

Here are some of what is in the article:

  • Semaphore: A classic concurrency tool
  • CyclicBarrier: A resettable multiway synchronization point (useful for parallel programming)
  • CountDownLatch: A utility for blocking until a given number of signals, events, or conditions hold
  • Exchanger: Allows two threads to exchange objects at a rendezvous point, and can be useful in pipeline designs
James Black
A: 

It would help if you could elaborate on why you want to synchronize without using the synchronized keyword. That is what it's for, after all.

You could do something like

void foo() {
   if(x) { // or whatever
      synchronize(this){
         // do things
      }
   }
}
iWerner
A: 

check out Lock classes from java.util.concurrent.locks package, which can be more flexible than sychronized methods

catwalk