You are on page 1of 43

1/9 /2 0 2 3

Advanced Java Programming Course

Session objectives
MultiThreading ◊ Introduction

◊ Creating thread

◊ Callables and Futures

◊ Thread class and Thread behaviors

◊ Thread properties

◊ Thread pooling
◊ Thread synchronization

◊ Deadlocks
Faculty of Information Technologies
Industrial University of Ho Chi Minh City ◊ Thread and GUI

1
1 2
1/9 /2 0 2 3

Introduction Introduction

◊ A program may consist of many tasks that can run concurrently.


◊ A thread is the flow of execution, from beginning to end, of a
task.

◊ It provides the mechanism for running a task. (a) Here multiple threads are (b) Here multiple threads
◊ With Java, you can launch multiple threads from a program running on multiple CPUs. share a single CPU.

concurrently. ◊ In single-processor systems, the multiple threads share CPU


◊ These threads can be executed simultaneously in multiprocessor time known as time sharing, and the operating system is
systems responsible for scheduling and allocating resources to them.

3 4

2
3 4
1/9 /2 0 2 3

Java programs execution and Thread Creating Tasks and Threads

◊ Tasks are objects. To create tasks, you have to first define a class
◊ When Java programs execute, there is always one thread
for tasks. A task class must implement the Runnable interface
running and that is the main thread.
◊ You need to implement run method to tell the system how your
 It is this thread from which child threads are created. thread is going to run

 Program is terminated when main thread stops execution.(*)

 Main thread can be controlled through Thread objects.

 Reference of the main thread can be obtained by calling the


currentThread() method of the Thread class.

5 6

3
5 6
1/9 /2 0 2 3

3. Result Thread class


1. create your task
◊ The Thread class contains the constructors for creating
threads for tasks, and the methods for controlling threads.

2. Start thread 7 8

4
7 8
1/9 /2 0 2 3

Another way to create thread Callables and Futures


Introduction
This approach is not recommended, because it mixes the task and the
mechanism of running the task. Separating the task from the thread is ◊ A Runnable encapsulates a task that runs asynchronously; you can

a preferred design. think of it as an asynchronous method with no parameters and no


return value.

◊ Drawback of Runnable:
 Cannot return any type (of run method)

 No parameters (of run method)

 Processing exception locally.

◊ So, we need another mechanic: Callable


◊ The Callable interface is a parameterized type, with a single method
call:

9 10

5
9 10
1/9 /2 0 2 3

Callables and Futures (cont) Callables and Futures


Future object Example

◊ A Future object holds the result of an asynchronous ◊ The FutureTask wrapper is a convenient mechanism for turning a
computation. Callable into both a Future and a Runnable it implements both

◊ You use a Future object so that you can start a computation, interfaces.

give the result to someone, and forget about it.

◊ The owner of the Future object can obtain the result when it is
ready.

11 12

6
11 12
1/9 /2 0 2 3

Thread behaviors – The sleep() method

◊ The sleep(long millis) method puts the thread to sleep for the
specified time in milliseconds to allow other threads to execute.

13 14

7
13 14
1/9 /2 0 2 3

Thread behaviors – The yield() method Thread behaviors – The join() method

◊ the yield() method causes the currently executing thread to ◊ Causes the current thread to wait until the thread on which it is
yield. If there are other runnable threads with a priority at called terminates.
least as high as the priority of this thread, they will be ◊ Allows specifying the maximum amount of time that the program
scheduled next. should wait for the particular thread to terminate.

◊ It throws InterruptedException if another thread interrupts it.

◊ The calling thread waits until the specified thread terminates.

15 16

8
15 16
1/9 /2 0 2 3

Thread with join Interrupting threads

◊ There is no longer a way to force a thread to terminate.


◊ The interrupt() method can be used to request termination of a
thread.

◊ Checking one thread is interrupted:

Thread.currentThread().isInterrupted()
◊ If a thread is blocked, it cannot check the interrupted status.
This is where the InterruptedException comes in.

17 18

9
17 18
1/9 /2 0 2 3

Interrupting threads (cont.) Thread states

public void run() Pattern for interrupting an


{ thread
try
{
. . .
while (more work to do)
{
do more work
}
}
catch (InterruptedException exception)
{
// thread was interrupted during sleep or wait
}
finally
{
cleanup, if required
}
// exit run method and terminate thread
}

19 20

10
19 20
1/9 /2 0 2 3

Managing threads: Priorities (1) Managing threads: Priorities (2)

◊ In Java, thread scheduler can use the thread priorities in the ◊ When a Java thread is created, it inherits its priority from the thread that
created it.
form of integer value to each of its thread to determine the
◊ At any given time, when multiple threads are ready to be executed, the runtime
execution schedule of threads . system chooses the runnable thread with the highest priority for execution.

◊ Thread gets the ready-to-run state according to their priorities. ◊ In the implementation of threading scheduler usually applies one of the two
following strategies:
The thread scheduler provides the CPU time to thread of  Preemptive scheduling: If the new thread has a higher priority then current running thread
highest priority during ready-to-run state. leaves the runnable state and higher priority thread enter to the runnable state.
 Time-Sliced (Round-Robin) Scheduling: A running thread is allowed to be execute fo
r the
Constant Description fixed time, after completion the time, current thread indicates to the another thread to
enter it in the runnable state.
Thread.MAX_PRIORITY The maximum priority of any thread (10)
Thread.MIN_PRIORITY The minimum priority of any thread (1)
Thread.NORM_PRIORITY The normal priority of any thread (5)
21 22

11
21 22
1/9 /2 0 2 3

Managing threads: Priorities (3) Daemon threads

◊ Two types of threads in Java:


◊ The highest-priority runnable thread keeps running
1. User threads:
until: • Created by the user
2. Daemon threads:
 It yields by calling the yield() method
• Threads that work in the background providing service to other
 It ceases to be runnable (either by dying or by entering the threads (e.g. – the garbage collector thread)

blocked state) ◊ When user thread exits, JVM checks to find out if any other
thread is running.
 A higher-priority thread has become runnable.  If there are, it will schedule the next thread.
 If the only executing threads are daemon threads, it exits.
◊ We can use follow method to set priority of Thread
◊ We can set a thread to be a Daemon if we do not want the main
void setPriority(int newPriority) program to wait until a thread ends.

23 24

12
23 24
1/9 /2 0 2 3

Thread Pools

◊ A thread pool is ideal to manage the number of tasks executing


concurrently.
◊ Java provides the Executor interface for executing tasks in a
thread pool and the ExecutorService interface for managing and
controlling tasks

25 26

13
25 26
1/9 /2 0 2 3

Thread Pools - The Executor interface (1/2) Thread Pools - The Executor interface (2/2)

◊ To create an Executor object, use the static methods in the ◊ The newCachedThreadPool() method creates a new thread if all
Executor sclass. the threads in the pool are not idle and there are tasks waiting

◊ The newFixedThreadPool(int) method creates a fixed number of for execution.


threads in a pool.  A thread in a cached pool will be terminated if it has not been used
 If a thread completes executing a task, it can be reused to execute for 60 seconds.
another task.
 A cached pool is efficient for many short tasks.
 If a thread terminates due to a failure prior to shutdown, a new
thread will be created to replace it
 If all the threads in the pool are not idle and there are tasks waitingfor
execution.

27 28

14
27 28
1/9 /2 0 2 3

Thread Pools – The ExecutorService interface Thread Pools demo

◊ The shutdown() method shuts down the executor, but allows the
tasks in the executor to complete. Once shut down, it cannot accept
new tasks.

◊ The shutdownNow() method shuts down the executor immediately


even though there are unfinished threads in the pool. Returns a list
of unfinished tasks.

◊ The isShutdown() method returns true if the executor has been


shut down.

◊ The isTerminated() method returns true if all tasks in the pool are
terminated

29 30

15
29 30
1/9 /2 0 2 3

Thread Synchronization Thread Synchronization

◊ What happens if two threads have access to the same object ◊ Thread Communication Without Synchronization
and each calls a method that modifies the state of the object? View follow example: UnsynchBankTest.java

◊ There are some things wrong in this Bank.


◊ In such a case, data may become inconsistent.
◊ The Race Condition Explained:
◊ Situation is often called a race condition.  The prolem is that these are not atomic operations. View folowfigure

◊ To avoid simultaneous access of a shared object by multiple  The real problem is that the work of the transfer method can b
e
interrupted in the middle. If we could ensure that the method runs
threads, you must learn how to synchronize the access.
to completion before the thread loses control, then the state of the
bank account object would not be corrupted.

31 32

16
31 32
1/9 /2 0 2 3

Thread Synchronization Thread Synchronization

◊ Synchronization is based on the concept of monitor.


 A monitor is an object that is used as a mutually exclusive
lock.
◊ Only one thread can enter a monitor:
 When one thread enters the monitor, it means that the
thread has acquired a lock
 All other threads must wait till that thread exits the monitor.
◊ For a thread to enter the monitor of an object:
 The programmer may invoke a method created using the
synchronized keyword (implicit synchronize).
 Or using explicit lock objects.

33 34

17
33 34
1/9 /2 0 2 3

Thread Synchronization – 1st approach Comparison of unsynchronized and synchronized


threads

◊ Concurrency mechanism:
 Simply tag any operation that should not be interrupted as
synchronized, for example :

public synchronized void transfer(int from, int to,int amount)

 When one thread calls a synchronized method, it is guaranteed


that the method will finish before another thread can
execute any synchronized method on the same object.

35 36

18
35 36
1/9 /2 0 2 3

Thread Synchronization – 1st approach (cont.) Thread Synchronization – 1st approach (cont.)
how it work? The ‘wait - notify’ mechanism

◊ When a thread calls a synchronized method, the object becomes "locked."  This mechanism ensures that there is a smooth
transition of a particular resource between two
◊ Periodically, the thread scheduler activates the threads that are waiting for
competitive threads.
the lock to open.
 It also oversees the condition in a program where one
◊ Other threads are still free to call unsynchronized methods on a locked thread is:
object. • Allowed to wait for the lock.
◊ When a thread leaves a synchronized method by throwing an exception, it • Notified to end its waiting state and get the lock
still relinquishes the object lock.
 When a thread executes a call to wait, it surrenders the
◊ If a thread owns the lock of an object and it calls another synchronized object lock and enters a wait list for that object.
method of the same object, then that method is automatically granted
 To remove a thread from the wait list, some other
access. The thread only relinquishes the lock when it exits the last thread must make a call to notifyAll or notify, on the
synchronized method. same object.

37 38

19
37 38
1/9 /2 0 2 3

Thread Synchronization – 1st approach (cont.)


The ‘wait - notify’ mechanism (cont.) Thread Synchronization – 1st approach (cont.)
The ‘wait - notify’ mechanism example

notify() First thread

notify()
wakes up or
notifies the
first thread.

notifyAll() Thread 2
notifyAll()
wakes up or Thread 1
notifies all the
Thread 3
threads that
called wait( ) on
the same object.
39 An incorrect implementation of a producer and consumer 40

20
39 40
1/9 /2 0 2 3

Thread Synchronization – 1st approach (cont.) Thread Synchronization – 1st approach (cont.)
The ‘wait - notify’ mechanism example Synchronized Blocks

 Syntax : synchronized (object){


//do your work
}
 Example :
1. public void run()
2. {
3. //. . .
4. synchronized (bank) // lock the bank object
5. {
6. if (bank.getBalance(from) >= amount)
7.bank.transfer(from, to, amount); 8.}
9. //. . .
10.}

41 42

21
41 42
1/9 /2 0 2 3

Thread Synchronization – 1st approach (cont.) Thread Synchronization – 2nd approach (cont.)
Synchronized static method Lock Objects

 If one thread calls a synchronized static method of a class, all ◊ The basic outline for protecting a code block with a
synchronized static methods of the class are blocked until the ReentrantLock is:
first call returns.

 Example :
public static synchronized Singleton getInstance()

43 44

22
43 44
1/9 /2 0 2 3

Thread Synchronization – 2nd approach (cont.) Thread Synchronization – 2nd approach (cont.)
Lock Objects (cont.) Lock Objects (cont.)

◊ This construct guarantees that only one thread at a time can ◊ Imagine we have a very simple case where we need to
enter the critical section. synchronize access to a pair of variables. One is a simple value

◊ As soon as one thread locks the lock object, no other thread can and another is derived based on some lengthy calculation.

get past the lock statement.

◊ When other threads call lock, they are blocked until the first
thread unlocks the lock object.

Simple, but if we have a lot of


contention or if we perform a lot
of reads and few writes?
45 46

23
45 46
1/9 /2 0 2 3

Thread Synchronization – 2nd approach (cont.)


Condition Objects

◊ See code below:


if (bank.getBalance(from) >= amount)
bank.transfer(from, to, amount);
◊ It is entirely possible that the current thread will be deactivated
between the successful outcome of the test and the call to
transfer:
if (bank.getBalance(from) >= amount)
// thread might be deactivated at this point
bank.transfer(from, to, amount);
◊ By the time the thread is running again, the account balance may
have fallen below the withdrawal amount.

Using of ReadWriteLock 48

24
47 48
1/9 /2 0 2 3

Thread Synchronization – 2nd approach (cont.) Thread Synchronization – 2nd approach (cont.)
Condition Objects (cont.) Condition Objects (cont.)

◊ You must make sure that the thread cannot be interrupted ◊ What do we do when there is not enough money in the account?

between the test and the insertion: ◊ We wait until some other thread has added funds. But this
thread has just gained exclusive access to the bankLock, so no
other thread has a chance to make a deposit.

◊ The solution is : condition objects

 A lock object can have one or more associated condition objects.

49 50

25
49 50
1/9 /2 0 2 3

Thread Synchronization – 2nd approach (cont.) Thread Synchronization – 2nd approach (cont.)
Condition Objects (cont.) Condition Objects (cont.)

◊ If the Transfer method finds that sufficient funds are not ◊ There is an essential difference between a thread that is waiting to acquire
a lock and a thread that has called await.
available, it calls
◊ Once a thread calls the await method, it enters a wait set for that
sufficientFunds.await(); condition.

=>The current thread is now blocked and gives up the lock. This ◊ Thread is not unblocked when the lock is available.
◊ Instead, it stays blocked until another thread has called the signalAll
lets in another thread that can, we hope, increase the account
method on the same condition.
balance
◊ The signalAll method call unblocks all threads that are waiting for the
condition.

◊ When the threads are removed from the wait set, they are again runnable
and the scheduler will eventually activate them again.

51 52

26
51 52
1/9 /2 0 2 3

Thread Synchronization – 2nd approach (cont.) Thread Synchronization – 2nd approach (cont.)
Condition Objects (cont.) Fainess

◊ A fair lock favors the thread that has been waiting for the
longest time.

◊ By default, locks are not required to be fair.

◊ You can specify that you want a fair locking policy:

Lock fairLock = new ReentrantLock(true);

◊ Fair locks are a lot slower than regular locks.


◊ You should only enable fair locking if you have a specific reason
why fairness is essential for your problem.

53 54

27
53 54
1/9 /2 0 2 3

Thread Synchronization – 2nd approach (cont.) Deadlocks


Lock Testing and Timeouts Analyzing following situation

◊ The tryLock method tries to acquire a lock and returns true if it was
successful. Otherwise, it immediately returns false.

◊ You can call tryLock with a timeout parameter, like this:

if (myLock.tryLock(100, TimeUnit.MILLISECONDS)) . . .

◊ TimeUnit is an enumeration with values SECONDS, MILLISECONDS,


MICROSECONDS, and NANOSECONDS.

55 56

28
55 56
1/9 /2 0 2 3

Deadlocks(cont.) GUI Event Dispatch Thread

◊ If all threads in an application are blocked. The system has ◊ GUI event handling and painting code executes on a special
deadlocked. thread called the event dispatch thread.

◊ Most of Swing methods are not thread-safe. Invoking them from


◊ Unfortunately, there is nothing in the Java programming language to
avoid or break these deadlocks. multiple threads may cause conflicts.

◊ You need to run the code in the event dispatch thread to avoid
◊ You must design your threads to ensure that a deadlock situation possible conflicts.
cannot occur.
◊ You can use the static methods, invokeLater and invokeAndWait
in the javax.swing.SwingUtilities class to run the code in the
◊ Notify/notifyAll method can unblock thread(s).
event dispatch thread.

57 58

29
57 58
1/9 /2 0 2 3

GUI Event Dispatch Thread– code template Thread and Swing - SwingWorker

◊ All Swing GUI events are processed in a single event dispatch


thread.

◊ If an event requires a long time to process, the thread cannot


attend to other tasks in the queue.

◊ To solve this problem, you should run the time-consuming task


for processing the event in a separate thread.

◊ You can define a task class that extends SwingWorker, run the
time-consuming task and update the GUI using the results
produced from the task.

59 60

30
59 60
1/9 /2 0 2 3

Thread and Swing - SwingWorker

Thread and Swing - SwingWorker

61 62

31
61 62
1/9 /2 0 2 3

Thread and Swing - SwingWorker That’s all for this session!

◊ Thread is a special and interesting property of Java


◊ Since the task is run on a separate thread, you can continue to
 For building a single program to perform more than one task at th
e
use the GUI.
same time (multithreading program)
◊ If the task is executed on the event dispatch thread, the GUI is
 Thread synchronization
frozen

◊ Other advanced technique to use multithreading is Callable


 The best technique to handling multithreading.

Thank you all for your attention and patient !

63 64

32
63 64
1/9 /2 0 2 3

Java Programming Course

Session objectives

JSON Processing with Java JSON Introduction


JSON structure

Java API for JSON Processing

Faculty of Information Technologies


Industrial University of Ho Chi Minh City

33
65 66
1/9 /2 0 2 3

JSON structure (1)


JSON Introduction http://www.json.org/

• JSON (JavaScript Object Notation) is a lightweight data-interchange • JSON is built on two structures:
format. o A collection of name/value pairs. In various languages, this is realized as
It is easy for humans to read and write.
an object, record, struct, dictionary, hash table, keyed list, or
o

o It is easy for machines to parse and generate.


associative array.
o It is based on a subset of the JavaScript Programming Language, Standard
ECMA-262 3rd Edition - December 1999. o An ordered list of values. In most languages, this is realized as an array,
o JSON is a text format that is completely language independent but uses vector, list, or sequence.
conventions that are familiar to programmers of the C-family of languages,
including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These
properties make JSON an ideal data-interchange language.
• JSON is often used in Ajax applications, configurations, databases,
and RESTful web services. All popular websites offer JSON as the
data exchange format with their RESTful web services.

34
67 68
1/9 /2 0 2 3

JSON structure (2) JSON structure (3)

• In JSON, they take on these forms: • A value can be a string in double quotes, or a number, or true or
o An object is an unordered set of name/value pairs. An object begins false or null, or an object or an array. These structures can be
with { (left brace) and ends with } (right brace). Each name is followed nested.
by : (colon) and the name/value pairs are separated by , (comma).

o An array is an ordered collection of values. An array begins with [ (left


bracket) and ends with ] (right bracket). Values are separated by
, (comma).

35
69 70
1/9 /2 0 2 3

JSON structure (4) JSON structure (5)

• A string is a sequence of zero or more Unicode characters, • A number is very much like a C or Java number, except that the
wrapped in double quotes, using backslash escapes. A character is octal and hexadecimal formats are not used.
represented as a single character string. A string is very much like
a C or Java string.

36
71 72
1/9 /2 0 2 3

Sample json document & rule Java API for JSON Processing

• The Java API for JSON Processing (JSR 353) provides portable
APIs to parse, generate, transform, and query JSON using object
model and streaming APIs.
• It produces and consumes JSON text in a streaming fashion
(similar to StAX API for XML) and allows to build a Java object
model for JSON text using API classes (similar to DOM API for
XML).

37
73 74
1/9 /2 0 2 3

JSON Processing - The Object Model API (1) JSON Processing - The Object Model API (2)

• The Object Model API • The main classes and interfaces in the object model API
o The object model API creates a random-access, tree-like structure that Class or Interface Description
represents the JSON data in memory. The tree can then be navigated and Contains static methods to create JSON readers, writers,
Json
queried. builders, and their factory objects.
JsonGenerator Writes JSON data to a stream one value at a time.
o This programming model is the most flexible and enables processing that
Reads JSON data from a stream and creates an object
requires random access to the complete contents of the tree. However, it is JsonReader
model in memory.
often not as efficient as the streaming model and requires more memory. JsonObjectBuilder Create an object model or an array model in memory by
o The object model API is similar to the Document Object Model (DOM) API JsonArrayBuilder adding values from application code.

for XML. JsonWriter Writes an object model from memory to a stream.


JsonValue
o It is a high-level API that provides immutable object models for JSON
JsonObject
object and array structures. These JSON structures are represented as JsonArray Represent data types for values in JSON data.
object models using the Java types JsonObject and JsonArray. JsonString
JsonNumber

38
75 76
1/9 /2 0 2 3

JSON Processing - The Object Model API (3) Mapping between JSON and Java entities

• JsonObject, JsonArray, JsonString, and JsonNumber are subtypes of


JsonValue. These are constants defined in the API for null, true, and false
JSON values.
• The object model API uses builder patterns to create these object models
from scratch. Application code can use the interface JsonObjectBuilder to
create models that represent JSON objects. The resulting model is of type
JsonObject. Application code can use the interface JsonArrayBuilder to
create models that represent JSON arrays. The resulting model is of type
JsonArray.
• These object models can also be created from an input source (such as
InputStream or Reader) using the interface JsonReader. Similarly, these On decoding:
object models can be written to an output source (such as OutputStream or The default concrete class of java.util.List is org.json.simple.JSONArray
Writer) using the class JsonWriter. The default concrete class of java.util.Map is org.json.simple.JSONObject.

39
77 78
1/9 /2 0 2 3

Encoding JSON in Java Decoding JSON in Java

40
79 80
1/9 /2 0 2 3

JSON Processing - The Streaming API (1) JSON Processing - The Streaming API (2)

• The Streaming API • The streaming API is similar to the Streaming API for XML
o The streaming API provides a way to parse and generate JSON in a (StAX) and consists of the interfaces JsonParser and
streaming fashion. JsonGenerator.
o It hands over parsing and generation control to the programmer. • JsonParser contains methods to parse JSON data using the
o The streaming API provides an event-based parser and allows an
streaming model.
application developer to ask for the next event rather than handling the
• JsonGenerator contains methods to write JSON data to an output
event in a callback. This gives a developer more procedural control over
the JSON processing. Application code can process or discard the
source. Table 2 lists the main classes and interfaces in the

parser event and ask for the next event (pull the event). streaming API.

41
81 82
1/9 /2 0 2 3

JSON Processing - The Streaming API (3) JSON Processing - The Streaming API (3)

• The main classes and interfaces in the streaming API • JsonParser provides forward, read-only access to JSON data using
the pull parsing programming model. In this model, the application code
Class or Interface Description
controls the thread and calls methods in the parser interface to move
Contains static methods to create JSON parsers,
Json
generators, and their factory objects. the parser forward or to obtain JSON data from the current state of
Represents an event-based parser that can read JSON data the parser.
JsonParser
from a stream.
• JsonGenerator provides methods to write JSON data to a stream. The
JsonGenerator Writes JSON data to a stream one value at a time
generator can be used to write name/value pairs in JSON objects and
values in JSON arrays.
• The streaming API is a low-level API designed to process large
amounts of JSON data efficiently. Other JSON frameworks (such as
JSON binding) can be implemented using this API.

42
83 84
1/9 /2 0 2 3

Decoding JSON in Java – Stream API Conclusion

• The Java API for JSON Processing provides the following


capabilities:
o Parsing input streams into immutable objects or event streams
o Writing event streams or immutable objects to output streams
o Programmatically navigating immutable objects
o Programmatically building immutable objects with builders

43
85 86

You might also like