SlideShare une entreprise Scribd logo
1  sur  61
Télécharger pour lire hors ligne
Java ConcurrencyGanesh Samarthyam
ganesh@codeops.tech
Do you think you always
write correct concurrent
programs?
Simple Program: Is it Okay?
class MyThread extends Thread {
public void run() {
System.out.println("In run method; thread name is: "
+ Thread.currentThread().getName());
}
public static void main(String args[]) {
Thread myThread = new MyThread();
myThread.run();
System.out.println("In main method; thread name is: "
+ Thread.currentThread().getName());
}
}
Prints:
In run method; thread name is: main
In main method; thread name is: main
Simple Time Bomb
class TimeBomb extends Thread {
String [] timeStr = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine" };
public void run() {
for(int i = 9; i >= 0; i--) {
System.out.println(timeStr[i]);
}
}
public static void main(String []s) {
TimeBomb timer = new TimeBomb();
System.out.println("Starting 10 second count down... ");
timer.start();
System.out.println("Boom!!!");
}
}
Does it print “Boom!!!” after counting
down from Nine to Zero? If not, how
will you make it happen?
Getting Thread State
class BasicThreadStates extends Thread {
public static void main(String []s) throws Exception {
Thread t = new Thread(new BasicThreadStates());
System.out.println("Just after creating thread; n" +
" The thread state is: " + t.getState());
t.start();
System.out.println("Just after calling t.start(); n" +
" The thread state is: " + t.getState());
t.join();
System.out.println("Just after main calling t.join(); n" +
" The thread state is: " + t.getState());
}
}
In rare cases, it prints:
Just after creating thread;
The thread state is: NEW
Just after calling t.start();
The thread state is: TERMINATED
Just after main calling t.join();
The thread state is: TERMINATED
Race Condition / Data Race
class Counter {
public static long count = 0;
}
class UseCounter implements Runnable {
public static void increment() {
Counter.count++;
System.out.print(Counter.count + " ");
}
public void run() {
increment();
increment();
increment();
}
}
public class DataRace {
public static void main(String args[]) {
UseCounter c = new UseCounter();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
Thread t3 = new Thread(c);
t1.start();
t2.start();
t3.start();
}
}
This program suffers from race
condition / data race problem
$ java DataRace
3 4 5 3 6 3 7 8 9
$ java DataRace
2 4 5 3 6 7 2 8 9
$ java DataRace
1 2 3 4 5 6 7 8 9
$
race conditions
Dealing with bugs in parallel
programs is very difficult!
Dead Lock
// Balls class has a globally accessible data member to hold the number of balls thrown
class Balls {
public static long balls = 0;
}
// Runs class has a globally accessible data member to hold the number of runs scored
class Runs {
public static long runs = 0;
}
public class DeadLock {
public static void main(String args[]) throws InterruptedException {
Counter c = new Counter();
// create two threads and start them at the same time
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
System.out.println("Waiting for threads to complete execution…");
t1.join();
t2.join();
System.out.println("Done.");
}
}
Dead Lock
// Counter class has two methods – IncrementBallAfterRun and IncrementRunAfterBall.
// For demonstrating deadlock, we call these two methods in the run method, so that
// locking can be requested in opposite order in these two methods
class Counter implements Runnable {
// this method increments runs variable first and then increments the balls variable
// since these variables are accessible from other threads,
// we need to acquire a lock before processing them
public void IncrementBallAfterRun() {
// since we’re updating runs variable first, first lock the Runs.class
synchronized(Runs.class) {
// lock on Balls.class before updating balls variable
synchronized(Balls.class) {
Runs.runs++;
Balls.balls++;
}
}
}
public void IncrementRunAfterBall() {
// since we’re updating balls variable first; so first lock Balls.class
synchronized(Balls.class) {
// acquire lock on Runs.class before updating runs variable
synchronized(Runs.class) {
Balls.balls++;
Runs.runs++;
}
}
}
public void run() {
// call these two methods which acquire locks in different order
// depending on thread scheduling and the order of lock acquision,
// a deadlock may or may not arise
IncrementBallAfterRun();
IncrementRunAfterBall();
}
}
deadlocks
deadlocks
Too many locks!
java.util.concurrent package
Using AtomicInteger
import java.util.concurrent.atomic.*;
// Class to demonstrate how incrementing "normal" (i.e., thread unsafe) integers and incrementing
// "atomic" (i.e., thread safe) integers are different: Incrementing a shared Integer object without locks can result
// in a data race; however, incrementing a shared AtomicInteger will not result in a data race.
class AtomicVariableTest {
// Create two integer objects – one normal and another atomic – with same initial value
private static Integer integer = new Integer(0);
private static AtomicInteger atomicInteger = new AtomicInteger(0);
static class IntegerIncrementer extends Thread {
public void run() {
++integer;
}
}
static class AtomicIntegerIncrementer extends Thread {
public void run() {
atomicInteger.incrementAndGet();
}
}
public static void main(String []args) {
// create three threads each for incrementing atomic and "normal" integers
for(int i = 0; i < 10; i++) {
new IntegerIncrementer().start();
new AtomicIntegerIncrementer().start();
}
System.out.printf("final int value = %d and final AtomicInteger value = %d",
integer, atomicInteger.intValue());
}
}
Atomic Variables
❖ AtomicBoolean: Atomically updatable Boolean value.
❖ AtomicInteger: Atomically updatable int value; inherits from the N umber class.
❖ AtomicIntegerArray: An int array in which elements can be updated atomically.
❖ AtomicLong: Atomically updatable long value; inherits from N umber class.
❖ AtomicLongArray: A long array in which elements can be updated atomically.
❖ AtomicReference<V>: An atomically updatable object reference of type V.
❖ AtomicReferenceArray<E>: An atomically updatable array that can hold object
references of type E (E refers to be base type of elements).
Locks
How to simulate only one
thread using an ATM and
others wait for their turn?
Locks
import java.util.concurrent.locks.*;
// This class simulates a situation where only one ATM machine is available and
// and five people are waiting to access the machine. Since only one person can
// access an ATM machine at a given time, others wait for their turn
class ATMMachine {
public static void main(String []args) {
// A person can use a machine again, and hence using a "reentrant lock"
Lock machine = new ReentrantLock();
// list of people waiting to access the machine
new Person(machine, "Mickey");
new Person(machine, "Donald");
new Person(machine, "Tom");
new Person(machine, "Jerry");
new Person(machine, "Casper");
}
}
Locks
// Each Person is an independent thread; their access to the common resource
// (the ATM machine in this case) needs to be synchronized using a lock
class Person extends Thread {
private Lock machine;
public Person(Lock machine, String name) {
this.machine = machine;
this.setName(name);
this.start();
}
public void run() {
try {
System.out.println(getName() + " waiting to access an ATM machine");
machine.lock();
System.out.println(getName() + " is accessing an ATM machine");
Thread.sleep(1000); // simulate the time required for withdrawing amount
} catch(InterruptedException ie) {
System.err.println(ie);
}
finally {
System.out.println(getName() + " is done using the ATM machine");
machine.unlock();
}
}
}
Locks
$ java ATMMachine
Donald waiting to access an ATM machine
Donald is accessing an ATM machine
Jerry waiting to access an ATM machine
Mickey waiting to access an ATM machine
Tom waiting to access an ATM machine
Casper waiting to access an ATM machine
Donald is done using the ATM machine
Jerry is accessing an ATM machine
Jerry is done using the ATM machine
Mickey is accessing an ATM machine
Mickey is done using the ATM machine
Tom is accessing an ATM machine
Tom is done using the ATM machine
Casper is accessing an ATM machine
Casper is done using the ATM machine
Assume that only two
people can be in an ATM
room at a time
Semaphore
import java.util.concurrent.Semaphore;
// This class simulates a situation where an ATM room has only two ATM machines
// and five people are waiting to access the machine. Since only one person can access
// an ATM machine at a given time, others wait for their turn
class ATMRoom {
public static void main(String []args) {
// assume that only two ATM machines are available in the ATM room
Semaphore machines = new Semaphore(2);
// list of people waiting to access the machine
new Person(machines, "Mickey");
new Person(machines, "Donald");
new Person(machines, "Tom");
new Person(machines, "Jerry");
new Person(machines, "Casper");
}
}
Semaphore
import java.util.concurrent.Semaphore;
// Each Person is an independent thread; but their access to the common resource
// (two ATM machines in the ATM machine room in this case) needs to be synchronized.
class Person extends Thread {
private Semaphore machines;
public Person(Semaphore machines, String name) {
this.machines = machines;
this.setName(name);
this.start();
}
public void run() {
try {
System.out.println(getName() + " waiting to access an ATM machine");
machines.acquire();
System.out.println(getName() + " is accessing an ATM machine");
Thread.sleep(1000); // simulate the time required for withdrawing amount
System.out.println(getName() + " is done using the ATM machine");
machines.release();
} catch(InterruptedException ie) {
System.err.println(ie);
}
}
}
Semaphore
Mickey waiting to access an ATM machine
Mickey is accessing an ATM machine
Jerry waiting to access an ATM machine
Jerry is accessing an ATM machine
Tom waiting to access an ATM machine
Donald waiting to access an ATM machine
Casper waiting to access an ATM machine
Mickey is done using the ATM machine
Jerry is done using the ATM machine
Tom is accessing an ATM machine
Donald is accessing an ATM machine
Tom is done using the ATM machine
Donald is done using the ATM machine
Casper is accessing an ATM machine
Casper is done using the ATM machine
How can you simulate a running
race with a count down? Once
“Start” => All threads should run
CountDownLatch
import java.util.concurrent.*;
// this class simulates the start of a running race by counting down from 5. It holds
// three runner threads to be ready to start in the start line of the race and once the count down
// reaches zero, all the three runners start running...
class RunningRaceStarter {
public static void main(String []args) throws InterruptedException {
CountDownLatch counter = new CountDownLatch(5);
// count from 5 to 0 and then start the race
// instantiate three runner threads
new Runner(counter, "Carl");
new Runner(counter, "Joe");
new Runner(counter, "Jack");
System.out.println("Starting the countdown ");
long countVal = counter.getCount();
while(countVal > 0) {
Thread.sleep(1000); // 1000 milliseconds = 1 second
System.out.println(countVal);
if(countVal == 1) {
// once counter.countDown(); in the next statement is called,
// Count down will reach zero; so shout "Start"
System.out.println("Start");
}
counter.countDown(); // count down by 1 for each second
countVal = counter.getCount();
}
}
}
CountDownLatch
// this Runner class simulates a track runner in a 100-meter dash race. The runner waits till the
// count down timer gets to zero and then starts running
class Runner extends Thread {
private CountDownLatch timer;
public Runner(CountDownLatch cdl, String name) {
timer = cdl;
this.setName(name);
System.out.println(this.getName() + " ready and waiting for the count down to start");
start();
}
public void run() {
try {
// wait for the timer count down to reach 0
timer.await();
} catch (InterruptedException ie) {
System.err.println("interrupted -- can't start running the race");
}
System.out.println(this.getName() + " started running");
}
}
CountDownLatch
Carl ready and waiting for the count down to start
Joe ready and waiting for the count down to start
Jack ready and waiting for the count down to start
Starting the countdown
5
4
3
2
1
Start
Carl started running
Jack started running
Joe started running
How to exchange data (or
synchronise communication)
between two threads?
Exchanger
class CoffeeShopThread extends Thread {
private Exchanger<String> sillyTalk;
public CoffeeShopThread(Exchanger<String> args) {
sillyTalk = args;
}
public void run() {
String reply = null;
try {
// exchange the first messages
reply = sillyTalk.exchange("Who's there?");
// print what Duke said
System.out.println("Duke: " + reply);
// exchange second message
reply = sillyTalk.exchange("Duke who?");
// print what Duke said
System.out.println("Duke: " + reply);
// there is no message to send, but to get a message from Duke thread,
// both ends should send a message; so send a "dummy" string
reply = sillyTalk.exchange("");
System.out.println("Duke: " + reply);
} catch(InterruptedException ie) {
System.err.println("Got interrupted during my silly talk");
}
}
}
Exchanger
import java.util.concurrent.Exchanger;
// The DukeThread class runs as an independent thread. It talks to the CoffeeShopThread that
// also runs independently. The chat is achieved by exchanging messages through a common
// Exchanger<String> object that synchronizes the chat between them.
// Note that the message printed are the "responses" received from CoffeeShopThread
class DukeThread extends Thread {
private Exchanger<String> sillyTalk;
public DukeThread(Exchanger<String> args) {
sillyTalk = args;
}
public void run() {
String reply = null;
try {
// start the conversation with CoffeeShopThread
reply = sillyTalk.exchange("Knock knock!");
// Now, print the response received from CoffeeShopThread
System.out.println("CoffeeShop: " + reply);
// exchange another set of messages
reply = sillyTalk.exchange("Duke");
// Now, print the response received from CoffeeShopThread
System.out.println("CoffeeShop: " + reply);
// an exchange could happen only when both send and receive happens
// since this is the last sentence to speak, we close the chat by
// ignoring the "dummy" reply
reply = sillyTalk.exchange("The one who was born in this coffee shop!");
// talk over, so ignore the reply!
} catch(InterruptedException ie) {
System.err.println("Got interrupted during my silly talk");
}
}
}
Exchanger
// Co-ordinate the silly talk between Duke and CoffeeShop by instantiating the Exchanger object
// and the CoffeeShop and Duke threads
class KnockKnock {
public static void main(String []args) {
Exchanger<String> sillyTalk = new Exchanger<String>();
new CoffeeShopThread(sillyTalk).start();
new DukeThread(sillyTalk).start();
}
}
Exchanger
CoffeeShop: Who's there?
Duke: Knock knock!
Duke: Duke
CoffeeShop: Duke who?
Duke: The one who was born in this coffee shop!
Useful Concurrency Utilities
❖ Semaphore: Controls access to one or more shared
resources
❖ CountDownLatch: Allows threads to wait for a countdown
to complete
❖ Exchanger: Supports exchanging data between two threads
❖ CyclicBarrier: Enables threads to wait at a predefined
execution point
❖ Phaser: Supports a synchronization barrier
Concurrent Collections
Priority Queue Doesn’t “Block”
import java.util.*;
// Simple PriorityQueue example. Here, we create two threads in which one thread inserts an element,
// and another thread removes an element from the priority queue.
class PriorityQueueExample {
public static void main(String []args) {
final PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
// spawn a thread that removes an element from the priority queue
new Thread() {
public void run() {
// Use remove() method in PriorityQueue to remove the element if available
System.out.println("The removed element is: " + priorityQueue.remove());
}
}.start();
// spawn a thread that inserts an element into the priority queue
new Thread() {
public void run() {
// insert Integer value 10 as an entry into the priority queue
priorityQueue.add(10);
System.out.println("Successfully added an element to the queue ");
}
}.start();
}
}
Priority Queue Doesn’t “Block”
java PriorityQueueExample
Exception in thread "Thread-0"
java.util.NoSuchElementException
at java.util.AbstractQueue.remove(AbstractQueue.java:117)
at PriorityQueueExample$1.run(PriorityQueueExample.java:12)
Successfully added an element to the queue
Using PriorityBlockingQueue
// Illustrates the use of PriorityBlockingQueue. In this case, if there is no element available in the priority queue
// the thread calling take() method will block (i.e., wait) till another thread inserts an element
import java.util.concurrent.*;
class PriorityBlockingQueueExample {
public static void main(String []args) {
final PriorityBlockingQueue<Integer> priorityBlockingQueue = new PriorityBlockingQueue<>();
new Thread() {
public void run() {
try {
// use take() instead of remove()
// note that take() blocks, whereas remove() doesn’t block
System.out.println("The removed element is: " + priorityBlockingQueue.take());
} catch(InterruptedException ie) {
// its safe to ignore this exception
ie.printStackTrace();
}
}
}.start();
new Thread() {
public void run() {
// add an element with value 10 to the priority queue
priorityBlockingQueue.add(10);
System.out.println("Successfully added an element to the que);
}
}
Using PriorityBlockingQueue
$ java PriorityBlockingQueueExample
Successfully added an element to the queue
The removed element is: 10
Modifying a List Concurrently
import java.util.*;
public class ModifyingList {
public static void main(String []args) {
List<String> aList = new ArrayList<>();
aList.add("one");
aList.add("two");
aList.add("three");
Iterator listIter = aList.iterator();
while(listIter.hasNext()) {
System.out.println(listIter.next());
aList.add("four");
}
}
}
$ java ModifyingList
one
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at ModifyingList.main(ModifyingList.java:14)
CopyOnWriteArrayList
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class COWList {
public static void main(String []args) {
List<String> aList = new CopyOnWriteArrayList<>();
aList.add("one");
aList.add("two");
aList.add("three");
Iterator listIter = aList.iterator();
while(listIter.hasNext()) {
System.out.println(listIter.next());
aList.add("four");
}
}
}
$ java COWList
one
two
three
Parallel Streams
I really really hate
concurrency problems
Parallel code
Serial code
Sometimes, dreams do come
true even at 86 :-)
So, keep dreaming till you
become 86!
Parallel Streams
import java.util.stream.LongStream;
class PrimeNumbers {
private static boolean isPrime(long val) {
for(long i = 2; i <= val/2; i++) {
if((val % i) == 0) {
return false;
}
}
return true;
}
public static void main(String []args) {
long numOfPrimes = LongStream.rangeClosed(2, 50_000)
.parallel()
.filter(PrimeNumbers::isPrime)
.count();
System.out.println(numOfPrimes);
}
}
long numOfPrimes = LongStream.rangeClosed(2, 100_000)
.filter(PrimeNumbers::isPrime)
.count();
System.out.println(numOfPrimes);
Prints 9592
2.510 seconds
Parallel code
Serial code
Let’s flip the switch by
calling parallel() function
long numOfPrimes = LongStream.rangeClosed(2, 100_000)
.parallel()
.filter(PrimeNumbers::isPrime)
.count();
System.out.println(numOfPrimes);
Prints 9592
1.235 seconds
Wow! That’s an awesome flip
switch!
Internally, parallel streams make
use of fork-join framework
import java.util.Arrays;
class StringConcatenator {
public static String result = "";
public static void concatStr(String str) {
result = result + " " + str;
}
}
class StringSplitAndConcatenate {
public static void main(String []args) {
String words[] = "the quick brown fox jumps over the lazy dog".split(" ");
Arrays.stream(words).forEach(StringConcatenator::concatStr);
System.out.println(StringConcatenator.result);
}
}
Gives wrong results with
with parallel() call
Meetups
h"p://www.meetup.com/JavaScript-Meetup-Bangalore/	
h"p://www.meetup.com/Container-Developers-Meetup-Bangalore/		
h"p://www.meetup.com/So>ware-Cra>smanship-Bangalore-Meetup/	
h"p://www.meetup.com/Core-Java-Meetup-Bangalore/	
h"p://www.meetup.com/Technical-Writers-Meetup-Bangalore/	
h"p://www.meetup.com/CloudOps-Meetup-Bangalore/	
h"p://www.meetup.com/Bangalore-SDN-IoT-NetworkVirtualizaHon-Enthusiasts/	
h"p://www.meetup.com/So>wareArchitectsBangalore/
Upcoming Bootcamps
https://www.townscript.com/e/solidprinciples (27th August)
https://www.townscript.com/e/azure (27th August)
https://www.townscript.com/e/modernarchitecture (10th Sept)
Apply
coupon code
“FLAT500”
to get Rs. 500
discount
ganesh@codeops.tech @GSamarthyam
www.codeops.tech slideshare.net/sgganesh
+91 98801 64463 bit.ly/ganeshsg
Image Credits
❖ https://bonexpose.com/wp-content/uploads/2015/07/Wildlife-Photography-by-Tim-
Flach-1a.jpg
❖ http://worldofdtcmarketing.com/wp-content/uploads/2016/02/innovation-
image1111111.jpg
❖ https://d.ibtimes.co.uk/en/full/1392314/traffic-light-tree.jpg
❖ http://s3-media1.fl.yelpcdn.com/bphoto/BKYrqfRerQFqM1wQWtYphw/o.jpg
❖ http://popsych.org/wp-content/uploads/2013/03/starting-line.jpeg
❖ https://cdn.boldomatic.com/content/post/
419493-05f182bf5bb701ed8ac64c963395eade77b07a674117a0dadba2a5f1404eca5f/Knock-
knock-Who-s-there-Opportunity-Don-t-be-silly?size=800
❖ http://www.locksmith-in-huddersfield.com/commercial_locks.png
❖ https://www.discoveryindochina.com/fr/wp-content/uploads/454.jpg

Contenu connexe

Tendances

Tendances (20)

MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 
Java threads
Java threadsJava threads
Java threads
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Java Garbage Collection - How it works
Java Garbage Collection - How it worksJava Garbage Collection - How it works
Java Garbage Collection - How it works
 
Servlets
ServletsServlets
Servlets
 
Introduction to Basic Java Versions and their features
Introduction to Basic Java Versions and their featuresIntroduction to Basic Java Versions and their features
Introduction to Basic Java Versions and their features
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Java I/O
Java I/OJava I/O
Java I/O
 
Files in java
Files in javaFiles in java
Files in java
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In Java
 

En vedette

En vedette (20)

Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkRefactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech Talk
 
Choosing Between Cross Platform of Native Development
Choosing	Between Cross Platform of Native DevelopmentChoosing	Between Cross Platform of Native Development
Choosing Between Cross Platform of Native Development
 
DevOps Fundamentals: A perspective on DevOps Culture
DevOps Fundamentals: A perspective on DevOps Culture DevOps Fundamentals: A perspective on DevOps Culture
DevOps Fundamentals: A perspective on DevOps Culture
 
7 best quotes on dev ops
7 best quotes on dev ops7 best quotes on dev ops
7 best quotes on dev ops
 
Better java with design
Better java with designBetter java with design
Better java with design
 
DevOps - A Gentle Introduction
DevOps - A Gentle IntroductionDevOps - A Gentle Introduction
DevOps - A Gentle Introduction
 
Introduction to chef
Introduction to chefIntroduction to chef
Introduction to chef
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Solid Principles Of Design (Design Series 01)
Solid Principles Of Design (Design Series 01)Solid Principles Of Design (Design Series 01)
Solid Principles Of Design (Design Series 01)
 
Zero downtime release through DevOps Continuous Delivery
Zero downtime release through DevOps Continuous DeliveryZero downtime release through DevOps Continuous Delivery
Zero downtime release through DevOps Continuous Delivery
 
DevOps Toolchain v1.0
DevOps Toolchain v1.0DevOps Toolchain v1.0
DevOps Toolchain v1.0
 
DevOps game marshmallow challenge
DevOps game marshmallow challengeDevOps game marshmallow challenge
DevOps game marshmallow challenge
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java 8 concurrency abstractions
Java 8 concurrency abstractionsJava 8 concurrency abstractions
Java 8 concurrency abstractions
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
 
Software Architecture - Principles Patterns and Practices - OSI Days Workshop...
Software Architecture - Principles Patterns and Practices - OSI Days Workshop...Software Architecture - Principles Patterns and Practices - OSI Days Workshop...
Software Architecture - Principles Patterns and Practices - OSI Days Workshop...
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
 

Similaire à Java Concurrency by Example

Multithreading
MultithreadingMultithreading
Multithreading
backdoor
 
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerKOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
Aiman Hud
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
Sonam Sharma
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
myrajendra
 

Similaire à Java Concurrency by Example (20)

unit-3java.pptx
unit-3java.pptxunit-3java.pptx
unit-3java.pptx
 
Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptx
 
04 threads
04 threads04 threads
04 threads
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
 
Thread 1
Thread 1Thread 1
Thread 1
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
 
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian KomputerKOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
JAVA Question : Programming Assignment
JAVA Question : Programming AssignmentJAVA Question : Programming Assignment
JAVA Question : Programming Assignment
 
JAVA THREADS.pdf
JAVA THREADS.pdfJAVA THREADS.pdf
JAVA THREADS.pdf
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 

Plus de CodeOps Technologies LLP

Plus de CodeOps Technologies LLP (20)

AWS Serverless Event-driven Architecture - in lastminute.com meetup
AWS Serverless Event-driven Architecture - in lastminute.com meetupAWS Serverless Event-driven Architecture - in lastminute.com meetup
AWS Serverless Event-driven Architecture - in lastminute.com meetup
 
Understanding azure batch service
Understanding azure batch serviceUnderstanding azure batch service
Understanding azure batch service
 
DEVOPS AND MACHINE LEARNING
DEVOPS AND MACHINE LEARNINGDEVOPS AND MACHINE LEARNING
DEVOPS AND MACHINE LEARNING
 
SERVERLESS MIDDLEWARE IN AZURE FUNCTIONS
SERVERLESS MIDDLEWARE IN AZURE FUNCTIONSSERVERLESS MIDDLEWARE IN AZURE FUNCTIONS
SERVERLESS MIDDLEWARE IN AZURE FUNCTIONS
 
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONSBUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS
BUILDING SERVERLESS SOLUTIONS WITH AZURE FUNCTIONS
 
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICESAPPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES
APPLYING DEVOPS STRATEGIES ON SCALE USING AZURE DEVOPS SERVICES
 
BUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPS
BUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPSBUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPS
BUILD, TEST & DEPLOY .NET CORE APPS IN AZURE DEVOPS
 
CREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNER
CREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNERCREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNER
CREATE RELIABLE AND LOW-CODE APPLICATION IN SERVERLESS MANNER
 
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
CREATING REAL TIME DASHBOARD WITH BLAZOR, AZURE FUNCTION COSMOS DB AN AZURE S...
 
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESSWRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
WRITE SCALABLE COMMUNICATION APPLICATION WITH POWER OF SERVERLESS
 
Training And Serving ML Model Using Kubeflow by Jayesh Sharma
Training And Serving ML Model Using Kubeflow by Jayesh SharmaTraining And Serving ML Model Using Kubeflow by Jayesh Sharma
Training And Serving ML Model Using Kubeflow by Jayesh Sharma
 
Deploy Microservices To Kubernetes Without Secrets by Reenu Saluja
Deploy Microservices To Kubernetes Without Secrets by Reenu SalujaDeploy Microservices To Kubernetes Without Secrets by Reenu Saluja
Deploy Microservices To Kubernetes Without Secrets by Reenu Saluja
 
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
Leverage Azure Tech stack for any Kubernetes cluster via Azure Arc by Saiyam ...
 
YAML Tips For Kubernetes by Neependra Khare
YAML Tips For Kubernetes by Neependra KhareYAML Tips For Kubernetes by Neependra Khare
YAML Tips For Kubernetes by Neependra Khare
 
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...
Must Know Azure Kubernetes Best Practices And Features For Better Resiliency ...
 
Monitor Azure Kubernetes Cluster With Prometheus by Mamta Jha
Monitor Azure Kubernetes Cluster With Prometheus by Mamta JhaMonitor Azure Kubernetes Cluster With Prometheus by Mamta Jha
Monitor Azure Kubernetes Cluster With Prometheus by Mamta Jha
 
Jet brains space intro presentation
Jet brains space intro presentationJet brains space intro presentation
Jet brains space intro presentation
 
Functional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and StreamsFunctional Programming in Java 8 - Lambdas and Streams
Functional Programming in Java 8 - Lambdas and Streams
 
Distributed Tracing: New DevOps Foundation
Distributed Tracing: New DevOps FoundationDistributed Tracing: New DevOps Foundation
Distributed Tracing: New DevOps Foundation
 
"Distributed Tracing: New DevOps Foundation" by Jayesh Ahire
"Distributed Tracing: New DevOps Foundation" by Jayesh Ahire  "Distributed Tracing: New DevOps Foundation" by Jayesh Ahire
"Distributed Tracing: New DevOps Foundation" by Jayesh Ahire
 

Dernier

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Dernier (20)

%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 

Java Concurrency by Example

  • 2. Do you think you always write correct concurrent programs?
  • 3. Simple Program: Is it Okay? class MyThread extends Thread { public void run() { System.out.println("In run method; thread name is: " + Thread.currentThread().getName()); } public static void main(String args[]) { Thread myThread = new MyThread(); myThread.run(); System.out.println("In main method; thread name is: " + Thread.currentThread().getName()); } } Prints: In run method; thread name is: main In main method; thread name is: main
  • 4. Simple Time Bomb class TimeBomb extends Thread { String [] timeStr = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }; public void run() { for(int i = 9; i >= 0; i--) { System.out.println(timeStr[i]); } } public static void main(String []s) { TimeBomb timer = new TimeBomb(); System.out.println("Starting 10 second count down... "); timer.start(); System.out.println("Boom!!!"); } } Does it print “Boom!!!” after counting down from Nine to Zero? If not, how will you make it happen?
  • 5. Getting Thread State class BasicThreadStates extends Thread { public static void main(String []s) throws Exception { Thread t = new Thread(new BasicThreadStates()); System.out.println("Just after creating thread; n" + " The thread state is: " + t.getState()); t.start(); System.out.println("Just after calling t.start(); n" + " The thread state is: " + t.getState()); t.join(); System.out.println("Just after main calling t.join(); n" + " The thread state is: " + t.getState()); } } In rare cases, it prints: Just after creating thread; The thread state is: NEW Just after calling t.start(); The thread state is: TERMINATED Just after main calling t.join(); The thread state is: TERMINATED
  • 6. Race Condition / Data Race class Counter { public static long count = 0; } class UseCounter implements Runnable { public static void increment() { Counter.count++; System.out.print(Counter.count + " "); } public void run() { increment(); increment(); increment(); } } public class DataRace { public static void main(String args[]) { UseCounter c = new UseCounter(); Thread t1 = new Thread(c); Thread t2 = new Thread(c); Thread t3 = new Thread(c); t1.start(); t2.start(); t3.start(); } } This program suffers from race condition / data race problem $ java DataRace 3 4 5 3 6 3 7 8 9 $ java DataRace 2 4 5 3 6 7 2 8 9 $ java DataRace 1 2 3 4 5 6 7 8 9 $
  • 8. Dealing with bugs in parallel programs is very difficult!
  • 9.
  • 10. Dead Lock // Balls class has a globally accessible data member to hold the number of balls thrown class Balls { public static long balls = 0; } // Runs class has a globally accessible data member to hold the number of runs scored class Runs { public static long runs = 0; } public class DeadLock { public static void main(String args[]) throws InterruptedException { Counter c = new Counter(); // create two threads and start them at the same time Thread t1 = new Thread(c); Thread t2 = new Thread(c); t1.start(); t2.start(); System.out.println("Waiting for threads to complete execution…"); t1.join(); t2.join(); System.out.println("Done."); } }
  • 11. Dead Lock // Counter class has two methods – IncrementBallAfterRun and IncrementRunAfterBall. // For demonstrating deadlock, we call these two methods in the run method, so that // locking can be requested in opposite order in these two methods class Counter implements Runnable { // this method increments runs variable first and then increments the balls variable // since these variables are accessible from other threads, // we need to acquire a lock before processing them public void IncrementBallAfterRun() { // since we’re updating runs variable first, first lock the Runs.class synchronized(Runs.class) { // lock on Balls.class before updating balls variable synchronized(Balls.class) { Runs.runs++; Balls.balls++; } } } public void IncrementRunAfterBall() { // since we’re updating balls variable first; so first lock Balls.class synchronized(Balls.class) { // acquire lock on Runs.class before updating runs variable synchronized(Runs.class) { Balls.balls++; Runs.runs++; } } } public void run() { // call these two methods which acquire locks in different order // depending on thread scheduling and the order of lock acquision, // a deadlock may or may not arise IncrementBallAfterRun(); IncrementRunAfterBall(); } }
  • 16. Using AtomicInteger import java.util.concurrent.atomic.*; // Class to demonstrate how incrementing "normal" (i.e., thread unsafe) integers and incrementing // "atomic" (i.e., thread safe) integers are different: Incrementing a shared Integer object without locks can result // in a data race; however, incrementing a shared AtomicInteger will not result in a data race. class AtomicVariableTest { // Create two integer objects – one normal and another atomic – with same initial value private static Integer integer = new Integer(0); private static AtomicInteger atomicInteger = new AtomicInteger(0); static class IntegerIncrementer extends Thread { public void run() { ++integer; } } static class AtomicIntegerIncrementer extends Thread { public void run() { atomicInteger.incrementAndGet(); } } public static void main(String []args) { // create three threads each for incrementing atomic and "normal" integers for(int i = 0; i < 10; i++) { new IntegerIncrementer().start(); new AtomicIntegerIncrementer().start(); } System.out.printf("final int value = %d and final AtomicInteger value = %d", integer, atomicInteger.intValue()); } }
  • 17. Atomic Variables ❖ AtomicBoolean: Atomically updatable Boolean value. ❖ AtomicInteger: Atomically updatable int value; inherits from the N umber class. ❖ AtomicIntegerArray: An int array in which elements can be updated atomically. ❖ AtomicLong: Atomically updatable long value; inherits from N umber class. ❖ AtomicLongArray: A long array in which elements can be updated atomically. ❖ AtomicReference<V>: An atomically updatable object reference of type V. ❖ AtomicReferenceArray<E>: An atomically updatable array that can hold object references of type E (E refers to be base type of elements).
  • 18. Locks
  • 19. How to simulate only one thread using an ATM and others wait for their turn?
  • 20. Locks import java.util.concurrent.locks.*; // This class simulates a situation where only one ATM machine is available and // and five people are waiting to access the machine. Since only one person can // access an ATM machine at a given time, others wait for their turn class ATMMachine { public static void main(String []args) { // A person can use a machine again, and hence using a "reentrant lock" Lock machine = new ReentrantLock(); // list of people waiting to access the machine new Person(machine, "Mickey"); new Person(machine, "Donald"); new Person(machine, "Tom"); new Person(machine, "Jerry"); new Person(machine, "Casper"); } }
  • 21. Locks // Each Person is an independent thread; their access to the common resource // (the ATM machine in this case) needs to be synchronized using a lock class Person extends Thread { private Lock machine; public Person(Lock machine, String name) { this.machine = machine; this.setName(name); this.start(); } public void run() { try { System.out.println(getName() + " waiting to access an ATM machine"); machine.lock(); System.out.println(getName() + " is accessing an ATM machine"); Thread.sleep(1000); // simulate the time required for withdrawing amount } catch(InterruptedException ie) { System.err.println(ie); } finally { System.out.println(getName() + " is done using the ATM machine"); machine.unlock(); } } }
  • 22. Locks $ java ATMMachine Donald waiting to access an ATM machine Donald is accessing an ATM machine Jerry waiting to access an ATM machine Mickey waiting to access an ATM machine Tom waiting to access an ATM machine Casper waiting to access an ATM machine Donald is done using the ATM machine Jerry is accessing an ATM machine Jerry is done using the ATM machine Mickey is accessing an ATM machine Mickey is done using the ATM machine Tom is accessing an ATM machine Tom is done using the ATM machine Casper is accessing an ATM machine Casper is done using the ATM machine
  • 23. Assume that only two people can be in an ATM room at a time
  • 24. Semaphore import java.util.concurrent.Semaphore; // This class simulates a situation where an ATM room has only two ATM machines // and five people are waiting to access the machine. Since only one person can access // an ATM machine at a given time, others wait for their turn class ATMRoom { public static void main(String []args) { // assume that only two ATM machines are available in the ATM room Semaphore machines = new Semaphore(2); // list of people waiting to access the machine new Person(machines, "Mickey"); new Person(machines, "Donald"); new Person(machines, "Tom"); new Person(machines, "Jerry"); new Person(machines, "Casper"); } }
  • 25. Semaphore import java.util.concurrent.Semaphore; // Each Person is an independent thread; but their access to the common resource // (two ATM machines in the ATM machine room in this case) needs to be synchronized. class Person extends Thread { private Semaphore machines; public Person(Semaphore machines, String name) { this.machines = machines; this.setName(name); this.start(); } public void run() { try { System.out.println(getName() + " waiting to access an ATM machine"); machines.acquire(); System.out.println(getName() + " is accessing an ATM machine"); Thread.sleep(1000); // simulate the time required for withdrawing amount System.out.println(getName() + " is done using the ATM machine"); machines.release(); } catch(InterruptedException ie) { System.err.println(ie); } } }
  • 26. Semaphore Mickey waiting to access an ATM machine Mickey is accessing an ATM machine Jerry waiting to access an ATM machine Jerry is accessing an ATM machine Tom waiting to access an ATM machine Donald waiting to access an ATM machine Casper waiting to access an ATM machine Mickey is done using the ATM machine Jerry is done using the ATM machine Tom is accessing an ATM machine Donald is accessing an ATM machine Tom is done using the ATM machine Donald is done using the ATM machine Casper is accessing an ATM machine Casper is done using the ATM machine
  • 27. How can you simulate a running race with a count down? Once “Start” => All threads should run
  • 28. CountDownLatch import java.util.concurrent.*; // this class simulates the start of a running race by counting down from 5. It holds // three runner threads to be ready to start in the start line of the race and once the count down // reaches zero, all the three runners start running... class RunningRaceStarter { public static void main(String []args) throws InterruptedException { CountDownLatch counter = new CountDownLatch(5); // count from 5 to 0 and then start the race // instantiate three runner threads new Runner(counter, "Carl"); new Runner(counter, "Joe"); new Runner(counter, "Jack"); System.out.println("Starting the countdown "); long countVal = counter.getCount(); while(countVal > 0) { Thread.sleep(1000); // 1000 milliseconds = 1 second System.out.println(countVal); if(countVal == 1) { // once counter.countDown(); in the next statement is called, // Count down will reach zero; so shout "Start" System.out.println("Start"); } counter.countDown(); // count down by 1 for each second countVal = counter.getCount(); } } }
  • 29. CountDownLatch // this Runner class simulates a track runner in a 100-meter dash race. The runner waits till the // count down timer gets to zero and then starts running class Runner extends Thread { private CountDownLatch timer; public Runner(CountDownLatch cdl, String name) { timer = cdl; this.setName(name); System.out.println(this.getName() + " ready and waiting for the count down to start"); start(); } public void run() { try { // wait for the timer count down to reach 0 timer.await(); } catch (InterruptedException ie) { System.err.println("interrupted -- can't start running the race"); } System.out.println(this.getName() + " started running"); } }
  • 30. CountDownLatch Carl ready and waiting for the count down to start Joe ready and waiting for the count down to start Jack ready and waiting for the count down to start Starting the countdown 5 4 3 2 1 Start Carl started running Jack started running Joe started running
  • 31. How to exchange data (or synchronise communication) between two threads?
  • 32. Exchanger class CoffeeShopThread extends Thread { private Exchanger<String> sillyTalk; public CoffeeShopThread(Exchanger<String> args) { sillyTalk = args; } public void run() { String reply = null; try { // exchange the first messages reply = sillyTalk.exchange("Who's there?"); // print what Duke said System.out.println("Duke: " + reply); // exchange second message reply = sillyTalk.exchange("Duke who?"); // print what Duke said System.out.println("Duke: " + reply); // there is no message to send, but to get a message from Duke thread, // both ends should send a message; so send a "dummy" string reply = sillyTalk.exchange(""); System.out.println("Duke: " + reply); } catch(InterruptedException ie) { System.err.println("Got interrupted during my silly talk"); } } }
  • 33. Exchanger import java.util.concurrent.Exchanger; // The DukeThread class runs as an independent thread. It talks to the CoffeeShopThread that // also runs independently. The chat is achieved by exchanging messages through a common // Exchanger<String> object that synchronizes the chat between them. // Note that the message printed are the "responses" received from CoffeeShopThread class DukeThread extends Thread { private Exchanger<String> sillyTalk; public DukeThread(Exchanger<String> args) { sillyTalk = args; } public void run() { String reply = null; try { // start the conversation with CoffeeShopThread reply = sillyTalk.exchange("Knock knock!"); // Now, print the response received from CoffeeShopThread System.out.println("CoffeeShop: " + reply); // exchange another set of messages reply = sillyTalk.exchange("Duke"); // Now, print the response received from CoffeeShopThread System.out.println("CoffeeShop: " + reply); // an exchange could happen only when both send and receive happens // since this is the last sentence to speak, we close the chat by // ignoring the "dummy" reply reply = sillyTalk.exchange("The one who was born in this coffee shop!"); // talk over, so ignore the reply! } catch(InterruptedException ie) { System.err.println("Got interrupted during my silly talk"); } } }
  • 34. Exchanger // Co-ordinate the silly talk between Duke and CoffeeShop by instantiating the Exchanger object // and the CoffeeShop and Duke threads class KnockKnock { public static void main(String []args) { Exchanger<String> sillyTalk = new Exchanger<String>(); new CoffeeShopThread(sillyTalk).start(); new DukeThread(sillyTalk).start(); } }
  • 35. Exchanger CoffeeShop: Who's there? Duke: Knock knock! Duke: Duke CoffeeShop: Duke who? Duke: The one who was born in this coffee shop!
  • 36. Useful Concurrency Utilities ❖ Semaphore: Controls access to one or more shared resources ❖ CountDownLatch: Allows threads to wait for a countdown to complete ❖ Exchanger: Supports exchanging data between two threads ❖ CyclicBarrier: Enables threads to wait at a predefined execution point ❖ Phaser: Supports a synchronization barrier
  • 38.
  • 39. Priority Queue Doesn’t “Block” import java.util.*; // Simple PriorityQueue example. Here, we create two threads in which one thread inserts an element, // and another thread removes an element from the priority queue. class PriorityQueueExample { public static void main(String []args) { final PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(); // spawn a thread that removes an element from the priority queue new Thread() { public void run() { // Use remove() method in PriorityQueue to remove the element if available System.out.println("The removed element is: " + priorityQueue.remove()); } }.start(); // spawn a thread that inserts an element into the priority queue new Thread() { public void run() { // insert Integer value 10 as an entry into the priority queue priorityQueue.add(10); System.out.println("Successfully added an element to the queue "); } }.start(); } }
  • 40. Priority Queue Doesn’t “Block” java PriorityQueueExample Exception in thread "Thread-0" java.util.NoSuchElementException at java.util.AbstractQueue.remove(AbstractQueue.java:117) at PriorityQueueExample$1.run(PriorityQueueExample.java:12) Successfully added an element to the queue
  • 41. Using PriorityBlockingQueue // Illustrates the use of PriorityBlockingQueue. In this case, if there is no element available in the priority queue // the thread calling take() method will block (i.e., wait) till another thread inserts an element import java.util.concurrent.*; class PriorityBlockingQueueExample { public static void main(String []args) { final PriorityBlockingQueue<Integer> priorityBlockingQueue = new PriorityBlockingQueue<>(); new Thread() { public void run() { try { // use take() instead of remove() // note that take() blocks, whereas remove() doesn’t block System.out.println("The removed element is: " + priorityBlockingQueue.take()); } catch(InterruptedException ie) { // its safe to ignore this exception ie.printStackTrace(); } } }.start(); new Thread() { public void run() { // add an element with value 10 to the priority queue priorityBlockingQueue.add(10); System.out.println("Successfully added an element to the que); } }
  • 42. Using PriorityBlockingQueue $ java PriorityBlockingQueueExample Successfully added an element to the queue The removed element is: 10
  • 43. Modifying a List Concurrently import java.util.*; public class ModifyingList { public static void main(String []args) { List<String> aList = new ArrayList<>(); aList.add("one"); aList.add("two"); aList.add("three"); Iterator listIter = aList.iterator(); while(listIter.hasNext()) { System.out.println(listIter.next()); aList.add("four"); } } } $ java ModifyingList one Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) at java.util.ArrayList$Itr.next(ArrayList.java:851) at ModifyingList.main(ModifyingList.java:14)
  • 44. CopyOnWriteArrayList import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; public class COWList { public static void main(String []args) { List<String> aList = new CopyOnWriteArrayList<>(); aList.add("one"); aList.add("two"); aList.add("three"); Iterator listIter = aList.iterator(); while(listIter.hasNext()) { System.out.println(listIter.next()); aList.add("four"); } } } $ java COWList one two three
  • 46. I really really hate concurrency problems
  • 48. Sometimes, dreams do come true even at 86 :-)
  • 49. So, keep dreaming till you become 86!
  • 50. Parallel Streams import java.util.stream.LongStream; class PrimeNumbers { private static boolean isPrime(long val) { for(long i = 2; i <= val/2; i++) { if((val % i) == 0) { return false; } } return true; } public static void main(String []args) { long numOfPrimes = LongStream.rangeClosed(2, 50_000) .parallel() .filter(PrimeNumbers::isPrime) .count(); System.out.println(numOfPrimes); } }
  • 51. long numOfPrimes = LongStream.rangeClosed(2, 100_000) .filter(PrimeNumbers::isPrime) .count(); System.out.println(numOfPrimes); Prints 9592 2.510 seconds
  • 52. Parallel code Serial code Let’s flip the switch by calling parallel() function
  • 53. long numOfPrimes = LongStream.rangeClosed(2, 100_000) .parallel() .filter(PrimeNumbers::isPrime) .count(); System.out.println(numOfPrimes); Prints 9592 1.235 seconds
  • 54. Wow! That’s an awesome flip switch!
  • 55. Internally, parallel streams make use of fork-join framework
  • 56.
  • 57. import java.util.Arrays; class StringConcatenator { public static String result = ""; public static void concatStr(String str) { result = result + " " + str; } } class StringSplitAndConcatenate { public static void main(String []args) { String words[] = "the quick brown fox jumps over the lazy dog".split(" "); Arrays.stream(words).forEach(StringConcatenator::concatStr); System.out.println(StringConcatenator.result); } } Gives wrong results with with parallel() call
  • 59. Upcoming Bootcamps https://www.townscript.com/e/solidprinciples (27th August) https://www.townscript.com/e/azure (27th August) https://www.townscript.com/e/modernarchitecture (10th Sept) Apply coupon code “FLAT500” to get Rs. 500 discount
  • 61. Image Credits ❖ https://bonexpose.com/wp-content/uploads/2015/07/Wildlife-Photography-by-Tim- Flach-1a.jpg ❖ http://worldofdtcmarketing.com/wp-content/uploads/2016/02/innovation- image1111111.jpg ❖ https://d.ibtimes.co.uk/en/full/1392314/traffic-light-tree.jpg ❖ http://s3-media1.fl.yelpcdn.com/bphoto/BKYrqfRerQFqM1wQWtYphw/o.jpg ❖ http://popsych.org/wp-content/uploads/2013/03/starting-line.jpeg ❖ https://cdn.boldomatic.com/content/post/ 419493-05f182bf5bb701ed8ac64c963395eade77b07a674117a0dadba2a5f1404eca5f/Knock- knock-Who-s-there-Opportunity-Don-t-be-silly?size=800 ❖ http://www.locksmith-in-huddersfield.com/commercial_locks.png ❖ https://www.discoveryindochina.com/fr/wp-content/uploads/454.jpg