Futures in Golang

Berk Gökden
Berk Gökden’s adventures
2 min readNov 10, 2019

--

I have been programming in Java and Scala for a long time. It is very common to use Futures for concurrency. Some people are obsessed with it.

This Sunday morning had some time to create a simple library which is somewhat similar to Java Future.

For starters, here is the link for Java Future and here is the link for the Scala Future.

Go has Goroutine and channels to build basic concurrent programming. So I wanted to build a function that runs the given function inside goroutine and returns the result in a channel.

I feel guilty for creating a channel for only one call but this is more of a utility for beginners, prototyping or low load services. For the advanced use cases, I still recommend creating your channels, goroutines and wait groups.

I wanted to have a wrapper to start a function in a goroutine and get the result from a channel and allow it to set a timeout. I have been doing this in other projects but mostly manually.

future := gofuture.FutureFunc(func() int {
return 5
})
// do something else here
// get result when needed
result := future.Get()

Also set timeout if needed:

result := future.GetWithTimeout(3 * time.Second)

I run into a problem that golang still doesn’t support generics so Future struct returns an interface and type casting should be handled by the user.

Future struct:

type Future struct {
Success bool
Done bool
Result interface{}
InterfaceChannel <-chan interface{}
}

Future struct currently allows checking if the result is ready and successful.

Channel kept open after get call, so the user can call GetWithTimeout multiple times. It is ok to leave a channel open, although it is not recommended. To handle this, it is recommended to allow the Future struct to be garbage collected. When all references to a channel are removed channel will be closed and garbage collected. Source: https://stackoverflow.com/a/36613932/927783

Future of Future:

I would like to use this Future implementation with a Golang Stream library like Automi or a similar library to create easy to write parallel calls.

Here is the link to the github repo:

--

--