O'Reilly logo

Java 9 Cookbook by Nick Samoylov, Mohamed Sanaulla

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

First, we'll check out a problem caused by concurrency. Let's create a Calculator class that has the calculate(): method: 

class Calculator{  private double prop;  public double calculate(int i){    this.prop = 2.0 * i;    DoubleStream.generate(new Random()::nextDouble)                .limit(10);    return Math.sqrt(this.prop);  }}

This method assigns an input value to a property and then calculates its square root. We also inserted code that generates a stream of 10 values. We did this in order to keep the method busy for some time. Otherwise, everything is done so quickly that there will be little chance for any concurrency to occur. Also, we wanted the return value to be obviously the same all the time, so we did not complicate it by having calculations ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required