0% found this document useful (0 votes)
14 views

Java Thread

Uploaded by

thirtyseven93
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Java Thread

Uploaded by

thirtyseven93
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

JAVA FULL STACK

DEVELOPMENT PROGRAM
Thread
OUTLINE
• Thread & Process

• Thread in Java

• Thread

• Runnable

• Daemon Threads

• Synchronization

• Thread problem
PROCESS
• A process has a self-contained execution environment.

• A process generally has a complete, private set of basic run-time


resources; in particular, each process has its own memory space.

• Processes are often seen as synonymous with programs or applications

• However, what the user sees as a single application may in fact be a set
of cooperating processes

• eg. To facilitate communication between processes, most operating


systems support Inter Process Communication (IPC)
resources, such as pipes and sockets
THREAD
• A thread is a lightweight sub process, a
smallest unit of processing. It is a separate
path of execution

• Threads are independent, if there occurs


exception in one thread, it doesn't affect
other threads. It shares a common memory
area.
THREAD VS PROCESS
THREAD VS PROCESS
WHY THREAD
• To enhance parallel processing

• Massively parallel server monitoring infrastructure, for example u are required to


monitor many servers/routers every 5 seconds

• To reduce response time to the user

• HTTP/JEE servers/frameworks like tomcat, jetty uses multithreads to achieve high


throughput

• To utilize the idle time of the CPU

• jUnit uses threads to run test cases in parallel

• Prioritize your work depending on priority

• Computer games is a good example of multi-threaded processing (Loading maps


when you are working on other things)
THREAD IN JAVA

• Two way to create a new thread

• Extends the Thread class

• Implements the Runnable interface


THREAD CLASS
• In Java, there is a class named as Thread class, which belongs to
java.lang package, declared as

• public class Thread extends Object implements Runnable

• This class encapsulates any thread of execution. Threads are


created as the instance of this class, which contains run()
methods in it. The functionality of the thread can only be achieved
by overriding this run() method

• public void run( ) {


// statement for implementing thread
}
THREAD CLASS
RUNNABLE INTERFACE
• Runnable interface is implemented by Thread class in the package
java.lang. This interface is declared as

• public interface Runnable

• The interface needs to be implemented by any class whose instance


is to be executed by a thread. The implementing class must also
override a void method named as run(), defined as a lone method in
the Runnable interface as

• public void run( ) {


// statement for implementing thread
}
RUNNABLE INTERFACE
START VS RUN
• When a program calls the start() method, a new
thread is created and then the run() method is
executed

• When a program directly call the run() method


then no new thread will be created
and run() method will be executed as a normal
method call on the current calling thread itself
and no multi-threading will take place
START VS RUN
START VS RUN
• Can we start a thread twice?

• eg. call start method on same thread twice

• What if I invoke run() method instead of


start() method

• eg. call run method on same thread twice


START VS RUN
RUNNABLE OR THREAD
• Simply put, we generally encourage the use of Runnable over Thread:

• When extending the Thread class, we're not overriding any of its methods. Instead,
we override the method of Runnable (which Thread happens to implement).
This is a clear violation of IS-A Thread principle

• Creating an implementation of Runnable and passing it to the Thread class


utilizes aggregation/composition and not inheritance – which is more flexible

• After extending the Thread class, we can't extend any other class

• From Java 8 onwards, Runnables can be represented as lambda expressions


MAIN THREAD
• Every Java program has a default thread, main thread.

• When the execution of Java program starts, the JVM


creates the main thread and calls the program's main()
method within that thread.

• Apart from this JVM also creates some invisible threads,


which are important for JVM housekeeping tasks

• Programmers can always take control of the main


thread.
THREAD LIFE CYCLE
• Five states of thread

• new — just created but not started

• runnable — created, started, and able to run

• running — thread is currently running

• blocked — created and started but unable to run because it


is waiting for some event to occur

• dead — thread has finished or been stopped


THREAD LIFE CYCLE
BLOCK THREAD
• Sleep — Thread.sleep causes the current thread to suspend execution for a specified period.
• Join — The join method allows one thread to wait for the completion of another
• If t is a Thread object whose thread is currently executing,
t.join();

• t
causes the current thread to pause execution until 's thread terminates. Overloads of join allow the
programmer to specify a waiting period.

• However, as with sleep, join is dependent on the OS for timing, so you should not assume
that join will wait exactly as long as you specify.
THREAD EXAMPLE
• SimpleThreads

• Several things to notice

• Thread.currentThread().getName() is returning the thread name in the


context of thread

• sleep() and join() both throw the InterruptedException which needs to be


handled properly

• what happens if we removed t.join(1000)?

• what happens if we removed t.join()?


DAEMON THREAD
• It provides services to user threads for background
supporting tasks. It has no role in life than to serve
user threads

• Its life depend on the mercy of user threads i.e. when


all the user threads dies, JVM terminates this thread
automatically.

• It is a low priority thread

• eg. garbage collection thread


DAEMON THREAD
• How to create Daemon thread

• public void setDaemon(boolean status) --


is used to mark the current thread as
daemon thread or user thread

• public boolean isDaemon() -- is used to


check that current is daemon
DAEMON THREAD
• Why Daemon thread?

• Create a daemon thread for functionalities that are not critical to system

• logging thread or monitoring thread to capture the system resource details


and their state

• Take another example:

• Imagine you're writing a simple game where your main method loops until
you decide to quit. And imagine that at the start of the game, you start a
thread that will endlessly poll some website to trigger alerts. You would like
the JVM to exit when you decide to end the game. You don't want the
endless polling to prevent the game from ending. So you make this polling
thread a daemon thread.
THREAD INTERFERENCE
• Consider a situation where
two thread is operating on the
same object at the same
time.
• Interference happens when
two operations, running in
different threads, but acting
on the same
data, interleave. This means
that the two operations
consist of multiple steps, and
the sequences of steps
overlap.
THREAD INTERFERENCE
• Virtual Machines like JVM will
decompose the “c++” statement
into following steps

• Retrieve the current value of c.

• Increment the retrieved value by


1.

• Store the incremented value back


in c.

• What if thread A is calling


increment and thread B is calling
decrement? (What will be the
result?)
MEMORY CONSISTENCY
ERRORS
• Memory consistency errors occur when
different threads have inconsistent views of
what should be the same data

• Eg. Same Counter class as before — Thread


A increases the counter by 1, and thread B
tries to print the value of counter. Now the
value can either be 1 or 0
SYNCHRONIZATION
• Threads communicate primarily by sharing access to fields and the objects
reference fields refer to

• This form of communication is extremely efficient, but makes two kinds of


errors possible: thread
interference and memory
consistency errors.

• The tool needed to prevent these errors is synchronization.

• Synchronization can be achieved in two ways

• By using synchronized keyword with method definition

• By using synchronized keyword with any block of code


SYNCHRONIZED METHOD
• It is not possible for two invocations of
synchronized methods on the same
object to interleave. When one thread
is executing a synchronized
method for an object, all other
threads that invoke synchronized
methods for the same object
block (suspend execution) until the
first thread is done with the object.
• When a synchronized method exits, it
automatically establishes a happens-
before relationship with any
subsequent invocation of a
synchronized method for the same
object. This guarantees that changes
to the state of the object are visible to
all threads.
SYNCHRONIZED BLOCK
• Synchronized block can be used to perform synchronization on
any specific resource of the method

• Suppose you have 50 lines of code in your method, but you


want to synchronize only 5 lines, you can use synchronized
block

• If you put all the codes of the method in the synchronized


block, it will work same as the synchronized method

• It is not required to understand the Synchronized Block, but it is


required to know how to write Synchronized Block in code.
THREAD PROBLEM

• Deadlock

• Starvation (Optional)

• Livelock (Optional)
DEADLOCK
• Deadlock describes a situation where two or more threads
are blocked forever, waiting for each other
STARVATION
• A situation where a thread is unable to gain regular
access to shared resources and is unable to make
progress

• eg. suppose an object provides a synchronized


method that often takes a long time to return. If one
thread invokes this method frequently, other threads
that also need frequent synchronized access to the
same object will often be blocked.

• A software design problem


LIVELOCK
• A situation where both threads are too busy
responding to each other

• A moves to his left to let G pass, while G


moves to his right to let A pass. Seeing
that they are still blocking each other, A
moves to his right, while G moves to his
left. They're still blocking each other…
ANY QUESTIONS?

You might also like