O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

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

A "Simple" Concurrent Programming Problem

Next, we create a thread pool with five threads in it using Java’s ExecutorService, and we submit 10,000 tasks to the service. Each task increments both our normal counter and our atomic counter. The full code snippet follows.

 public​ ​class​ ConcurrencyExamples {
 
 private​ ​static​ ​int​ counter = 0;
 private​ ​static​ AtomicInteger atomicCounter =
 new​ AtomicInteger(0);
 
 public​ ​static​ ​void​ main(String[] args)
 throws​ InterruptedException {
  ExecutorService executors = Executors.newFixedThreadPool(5);
 for​ (​int​ i = 0; i < 10000; i++) {
  executors.execute(​new​ Runnable() {
 public​ ​void​ run() {
  counter++;
  atomicCounter.incrementAndGet();
  }
  });
  }
 
 // Shut ...

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