Golang working with goroutines and channels -4
We will continue with the last part of golang reading. In our previous examples, we worked with main method which runs on only one processor and all tasks executed sequentially. But what if we need multi task environment which be scheduled by golang get results from these tasks and use them.
How about Java Future. Sounds familiar ? Most of the Java developers uses Future interface in order to handle asynchronous processes.
https://www.baeldung.com/java-future
Here is the following a task executor which makes simple math calculation.
public class SquareCalculator { private ExecutorService executor = Executors.newSingleThreadExecutor(); public Future<Integer> calculate(Integer input) { return executor.submit(() -> { Thread.sleep(1000); return input * input; }); } }
What about execution ? It is so easy to implement. After creating an instance of executor we trigger "calculate" method and after we expect the result from "get" method of Future interface. Very cool.
Future<Integer> future = new SquareCalculator().calculate(10); while(!future.isDone()) { System.out.println("Calculating..."); Thread.sleep(300); } Integer result = future.get();
Comparing to Java, In Golang "goroutine" has executor role and "channel" has a Future role. So lets have a look at an example of goroutine and channel.
Have a good work.
Yorumlar
Yorum Gönder