Goroutines in Java

A goroutine is a lightweight thread of execution.

import java.util.concurrent.*;

public class Goroutines {
    public static void main(String[] args) throws InterruptedException {
        // Call function f in the usual way, running it synchronously
        f("direct");
        
        // To invoke this function using an ExecutorService (similar to a goroutine in Go)
        ExecutorService executor = Executors.newCachedThreadPool();
        executor.submit(() -> f("goroutine"));
        
        // Start a thread for an anonymous function call
        executor.submit(() -> System.out.println("going"));

        // Shutdown the executor and wait for currently running tasks to finish
        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.SECONDS);
        
        System.out.println("done");
    }

    // Function f to print messages
    public static void f(String from) {
        for (int i = 0; i < 3; i++) {
            System.out.println(from + " : " + i);
        }
    }
}

Suppose we have a function call f(s). Here’s how we’d call that in the usual way, running it synchronously.

f("direct");

To invoke this function using an ExecutorService (similar to a goroutine in Go), use:

ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(() -> f("goroutine"));

You can also start a thread for an anonymous function call.

executor.submit(() -> System.out.println("going"));

Our two function calls are running asynchronously in separate threads now. Wait for them to finish (for a more robust approach, you might use more advanced synchronization techniques).

executor.shutdown();
executor.awaitTermination(1, TimeUnit.SECONDS);
System.out.println("done");

When we run this program, we see the output of the blocking call first, then the output of the two threads. The threads’ output may be interleaved, because they are being run concurrently by the Java runtime.

$ javac Goroutines.java
$ java Goroutines
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done

Next, we’ll look at a complement to threads in concurrent Java programs: Future and CompletableFuture.