Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the golang equivalent of a Java synchronized() block?

Tags:

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.)

like image 574
Brad Peabody Avatar asked Sep 18 '13 19:09

Brad Peabody


People also ask

What is sync in Golang?

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.

What is Java synchronization block?

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.

What are alternatives to synchronization in Java?

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.

Which is better synchronized method or block?

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.


1 Answers

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() 
like image 57
Salah Eddine Taouririt Avatar answered Oct 10 '22 19:10

Salah Eddine Taouririt