Golang vs Java concurrency a comparative study

Damitha Dayananda
2 min readDec 29, 2018

--

First of all what is concurrency. Simply say concurrency is dealing with many tasks at same time. How ever concurrency and parallelism are somewhat close concepts and its important to understand difference between both two concepts. So parallelism is about leveraging the simultaneous execution of work to perform a bunch of things at once while concurrency is about the composition of work to manage a bunch of things at once.

With the arrival of multi-core machine Many programming languages implements this concepts in their own ways like threads, green threads, process, goroutines.

When looking at both languages comparatively. Java uses OS thread to perform parallel execution of work through green threads(threads managed by language runtime). Golang uses OS thread through goroutines. So in the parallelism there can’t be significant difference between both implementations. But in concurrency there is huge difference. In java JVM map its green threads to OS threads while Golang brings mapping goroutines to OS threads into deep abstraction level through go scheduler.

Goroutines are not either system thread or thread managed by OS runtime (green thread).The idea behind the goroutine is multiplexing independently execution functions(coroutines) into set of threads. So when a coroutine block runtime move other set of coroutines into different green thread. Go scheduler maps m green threads to n OS threads and scheduler distributes go routines in between available green threads.

However both languages use almost similar concepts to maintain their own concurrent model. For example.

Starting asynchronous process

Java

  • Extending Thread class
  • Implementing runnable interface

Golang

  • Start gorountine

Synchronously using of resource

Java

  • Synchronized block
  • Using Lock.ReentrantLock that comes in utils.concurrent package

Golang

With the “concept of do not communicate with sharing memory instead share memory by communicating” go has concept called channel to achieve this use case. How ever it offer locking resource ability also

  • Using Sync.Mutex package to lock and unlock resources

Inter process communication

Java

  • Using object.wait(), object.Notify() or object.NotifyAll() method
  • Sharing BlockingQueue amoung threads
  • Using PipeReader and PipeWriter methods

Golang

  • Using channel

Simple programme demonstrate usage of channel to communicate between two goroutines. following go code calculate first 100 prime numbers using Sieve of Eratosthenes algorithm.

Example demonstrate concurrent programme in java

preferences

--

--

Damitha Dayananda

Electrical Engineer interesting in web development, power electronic design and android application development — — — — damithadayananda@gmail.com — — — -