Multithreaded Programming in Java
David [email protected]
Aalborg University
bal1 = a.getBalance();
bal1 = bal1 + 100
a.setBalance(bal1)
bal2 = a .getBalance();
bal2 = bal2 - 50;
a.setBalance(bal2);
System.out.println(a.getBalance());
Starting balance ofaccount, a, is 1000 kr
Fru Jensen withdraws 50 krHr. Jensen deposits 100 kr
What is the final balance?
Sources
• Chapter 14 of The Java Programming Language (Fourth Edition) by Ken Arnold, James Gosling and David Holmes (Addison-Wesley, 2006)
Single-threaded programming
• Single-threaded program – single sequence or thread of
instructions, executed one after the other
– only one instruction being carried out at any given instant in time
– the single thread in a single-threaded program is called the main thread
int bal = a.getBalance();
bal = bal + 10;
a.setBalance(bal)
SingleThreadedProgram.java
Multithreaded programming
• Most of the programs you use every day are multithreaded programs because they have to do two or more things at the same time
• For example– word processor has to listen for user input, update the
screen, save periodic backups, look-up typed words in a dictionary as they are typed, etc.
– web crawler crawls many different web pages simultaneously, creating a record for each one in the search engine’s database
Multithreaded programming• Multithreaded program consists of more than
one independent thread (sequence of instructions), running at the same time or concurrently– hence sometimes called concurrent programming
• Two or more threads can access the same data– this is good in a web crawler where many different
crawling threads can update the same central database
– HOWEVER this can cause problems such as the race condition
Race Condition• Suppose a is the joint bank
account of Hr. and Fru Jensen and it starts off with a balance of 1000kr
• Hr. Jensen goes to the branch near his work and deposits 100 kr
• Fru Jensen goes to the branch near their home and withdraws 50 kr
• The final balance should be 1050 kr...but is it?
• It depends on whether the account is locked while a transaction is taking place
bal1 = a.getBalance();
bal1 = bal1 + 100
a.setBalance(bal1)
bal2 = a .getBalance();
bal2 = bal2 - 50;
a.setBalance(bal2);
System.out.println(a.getBalance());
Starting balance ofaccount, a, is 1000 kr
Fru Jensen withdraws 50 krHr. Jensen deposits 100 kr
What is the final balance?
Creating Threads in Java• Create a new thread of control in Java by
instantiating a Thread object:Thread worker = new Thread();
• Can then set its initial priority, name, etc.:worker.setPriority(worker.getPriority()+1);worker.setName(“myThread”);
• When ready, call the Thread’s start method to set it offworker.start();– This starts a new thread of control based on data in
the Thread object• VM invokes new Thread’s run method which makes the Thread
active• Thread’s run method does nothing, but can override it in a subclass
of Thread
PingPong.java
Creating threads by specializing Thread
• In PingPong, we defined a subclass of Thread called PingPongThread and redefined the run method in this subclass to specify precisely what PingPongThreads should do
• But what if we had wanted PingPongThread to inherit from a class other than Thread?– We couldn’t, because it
has to inherit from Thread• There’s a better way...
PingPongThread
run()
Thread
Using the Runnable interface• A Thread abstracts the concept of a worker
– i.e., something that carries out some task• When you subtype Thread, the task carried out by the
new subtype is defined in its run() method• Instead, can define a new class that implements the
Runnable interface• Runnable interface abstracts the concept of a task• Runnable interface declares a method public void run();
• A class that implements Runnable must implement this run() method
• A Thread (worker) can be assigned a Runnable object (task) to run– The Thread’s run() method calls the run() method of the
Runnable object assigned to it when the Thread is started (with the start() method)
PingPong2.java
Thread runs Runnable objects and implements Runnable itself
PingPongRunnable
run()
«interface»Runnable
run()
Thread
run()
Interference and Critical Regions
• Interference is when interleaved operations from different threads on shared data could corrupt the data
• The code segments that contain the interfering actions are called critical sections or critical regions
bal1 = a.getBalance();
bal1 = bal1 + 100
a.setBalance(bal1)
bal2 = a .getBalance();
bal2 = bal2 - 50;
a.setBalance(bal2);
System.out.println(a.getBalance());
Starting balance ofaccount, a, is 1000 kr
Fr. Jensen withdraws 50 krHr. Jensen deposits 100 kr
What is the final balance?
Synchronization and Locks• Prevent interference by
synchronizing access to critical regions
• A Thread should have to acquire a lock on a shared object before processing it– Here, would have to acquire a
lock on the bank account, a, before changing it
• Thread releases lock on an object when finished with it
• A synchronized method or statement acquires a lock on an object before it executes and releases the lock once it has finished
bal1 = a.getBalance();
bal1 = bal1 + 100
a.setBalance(bal1)
bal2 = a .getBalance();
bal2 = bal2 - 50;
a.setBalance(bal2);
System.out.println(a.getBalance());
Starting balance ofaccount, a, is 1000 kr
Fru Jensen withdraws 50 krHr. Jensen deposits 100 kr
What is the final balance?
Synchronized Methods
HrOgFruJensen.java
Synchronized Statements
HrOgFruJensen2.java