How to synchronize method in java other than using synchronized keyword?
Traditionally, there are two ways in Java to do synchronization: synchronized() blocks and ReadWriteLock . Java 8 provides another alternative called StampedLock .
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.
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.
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.
Depends on you concrete needs.
See Java concurrent package for higher level synchronization abstractions. Note that they may still use synchronized
underneath ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With