Professional Documents
Culture Documents
Phant An
Phant An
Session objectives
MultiThreading ◊ Introduction
◊ Creating thread
◊ 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
◊ 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.
3 4
2
3 4
1/9 /2 0 2 3
◊ 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
5 6
3
5 6
1/9 /2 0 2 3
2. Start thread 7 8
4
7 8
1/9 /2 0 2 3
◊ Drawback of Runnable:
Cannot return any type (of run method)
9 10
5
9 10
1/9 /2 0 2 3
◊ 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.
◊ 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
◊ 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.
15 16
8
15 16
1/9 /2 0 2 3
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
19 20
10
19 20
1/9 /2 0 2 3
◊ 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
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
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
27 28
14
27 28
1/9 /2 0 2 3
◊ 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 isTerminated() method returns true if all tasks in the pool are
terminated
29 30
15
29 30
1/9 /2 0 2 3
◊ 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
◊ 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
33 34
17
33 34
1/9 /2 0 2 3
◊ Concurrency mechanism:
Simply tag any operation that should not be interrupted as
synchronized, for example :
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
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
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.
◊ When other threads call lock, they are blocked until the first
thread unlocks the lock object.
23
45 46
1/9 /2 0 2 3
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.
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.
53 54
27
53 54
1/9 /2 0 2 3
◊ The tryLock method tries to acquire a lock and returns true if it was
successful. Otherwise, it immediately returns false.
if (myLock.tryLock(100, TimeUnit.MILLISECONDS)) . . .
55 56
28
55 56
1/9 /2 0 2 3
◊ 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.
◊ 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
◊ 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
61 62
31
61 62
1/9 /2 0 2 3
63 64
32
63 64
1/9 /2 0 2 3
Session objectives
33
65 66
1/9 /2 0 2 3
• 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
34
67 68
1/9 /2 0 2 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).
35
69 70
1/9 /2 0 2 3
• 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.
38
75 76
1/9 /2 0 2 3
JSON Processing - The Object Model API (3) Mapping between JSON and Java entities
39
77 78
1/9 /2 0 2 3
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
43
85 86