Java provides a very convenient idiom for synchronizing critical portions of code:
synchronized(someObject) { // do something really important all by myself with nobody bothering me }
Or
public synchronized void doSomething() { // ... }
What is the go equivalent?
(A quick search reveals: golang.org/pkg/sync/ - which seems (maybe I'm wrong) a bit too low level for general use.)
(Example of why I care about this: I need to send a message to multiple listeners via channels. Channels provide a good conduit for the data without having to synchronize anything, but when channels are added or removed I need to modify the list of channels, which might happen at any time must be able to deal with concurrency.)
We can make use of channels if we want to synchronize goroutines. By synchronizing, we want to make the goroutines work in a defined manner, for example, not starting the next goroutine until the previous one has finished its execution.
A Synchronized block is a piece of code that can be used to perform synchronization on any specific resource of the method. A Synchronized block is used to lock an object for any shared resource and the scope of a synchronized block is smaller than the synchronized method.
Synchronized keyword limitations concurrent. locks package from Java 1.5 introduces a Lock interface defined as an alternative to the synchronized keyword : Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements.
A Java synchronized block doesn't allow more than one JVM, to provide access control to a shared resource. The system performance may degrade because of the slower working of synchronized keyword. Java synchronized block is more efficient than Java synchronized method.
sync.Mutex is a mutual exclusion lock, it can provide a similar functionality to the synchronized
java key-word (except that locks in java provide reentrant
mutual exclusion) :
synchronized(someObject) { // }
Is equivalent to :
var l sync.Mutex l.Lock() // l.Unlock()
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