Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Other way to synchronize method

How to synchronize method in java other than using synchronized keyword?

like image 771
developer Avatar asked Mar 30 '11 07:03

developer


People also ask

What are alternatives to synchronization in Java?

Traditionally, there are two ways in Java to do synchronization: synchronized() blocks and ReadWriteLock . Java 8 provides another alternative called StampedLock .

Can we synchronize the run method?

Yes, we can synchronize a run() method in Java, but it is not required because this method has been executed by a single thread only. Hence synchronization is not needed for the run() method.

What does it mean for a method to be synchronized?

synchronized simple means no two threads can access the block/method simultaneously. When we say any block/method of a class is synchronized it means only one thread can access them at a time.


2 Answers

You could use the java.util.concurrent.locks package, especially Lock interface:

Lock l = ...; 
l.lock();
try {
    // access the resource protected by this lock
} finally {
    l.unlock();
}

See here.

like image 200
trojanfoe Avatar answered Sep 20 '22 13:09

trojanfoe


Depends on you concrete needs.

See Java concurrent package for higher level synchronization abstractions. Note that they may still use synchronized underneath ...

like image 25
Jan Zyka Avatar answered Sep 20 '22 13:09

Jan Zyka