O'Reilly logo

Java 11 Cookbook by Mohamed Sanaulla, Nick Samoylov

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 reproduce a problem caused by the concurrent modification of the same value. Let's create a Calculator class that has the calculate() method: 

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

This method assigns an input value to a property and then calculates its square root. We also inserted two lines of code that generate streams of 50 and 100 values. We did this 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. Our adding the ...

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