Professional Documents
Culture Documents
Thread Priorities
Thread Priorities
What is a thread?
1//A thread is a lightweight sub-process, the smallest unit of processing. Or in
more general terms a thread of execution is the smallest sequence of programmed
instructions that can be managed independently by a scheduler
2//A thread, in the context of Java, is the path followed when executing a
program.All Java programs have at least one thread, known as the main
thread.
3//Each thread has a priority and that helps the thread scheduler to decide
which thread should start first. Whenever we create a thread, it automatically inherits
the priority from the parent thread.
1
starvation. 9//For this reason, use priority only to affect scheduling policy for
efficiency purposes. We shouldn’t rely on thread priority for algorithm correctness.
2
Thread priority in multithreading(5+6)
8. To understand thread priority in multithreading more easily let us look at an
example. Let us take a java application whose job is to perform database
operations, and that this is a multithreaded application. If we have one thread for
monitoring the database connection and for opening and closing that connection,
and another thread for performing all the crud operations like insert, update, etc.
But in the multithreading environment the JVM controls the thread priority, so we do
not have any control over the order of execution.
3
that each of them has a chance to make progress. But it is at least theoretically
possible that on some platforms a thread scheduler picks a random thread or keeps
picking the first available thread. This is actually a weakness of the Java
programming language, and it is difficult to write multithreaded programs that are
guaranteed to work identically on all virtual machines.
9//I also remember there are some get and set methods
in thread priority
10//Yes, there are actually two methods for that purpose:
4
2//Priority inversion
Priority inversion is an operating system scenario in which a higher priority process
is preempted by a lower priority process. This implies the inversion of the priorities
of the two processes.
- A system malfunction may occur if a high priority process is not provided the
required resources.
- 4//Priority inversion may also lead to implementation of corrective measures.
These may include the resetting of the entire system.
- 4//The performance of the system can be reduced due to priority inversion.
This may happen because it is imperative for higher priority tasks to execute
promptly.
- 5//System responsiveness decreases as high priority tasks may have strict time
constraints or real-time response guarantees.
5//However, sometimes there is no harm caused by priority inversion as the late
execution of the high priority process is not noticed by the system.
6//Are there any solutions that can solve the issue of
priority inversion?
5. Some solutions of priority inversion are as follows:
- Priority Ceiling: All the resources are assigned a priority that is equal to the
highest priority of any task that may attempt to claim them. This helps in
avoiding priority inversion.
- Priority inheritance: This solution temporarily escalates the priority of the low
priority task that is executing to the highest priority task that needs the
5
resource. This means that medium priority tasks cannot intervene and lead to
priority inversion.
Is it possible to prevent the low priority task from blocking the high
priority task?(9+10)
5. Yes, priority inversion can be avoided by avoiding blocking as the low priority task
blocks the high priority task.
- Priority boosting: The priority of the ready tasks can be randomly boosted
until they exit the critical section.
- boolean isDaemon():This method is used to check that current is daemon. It
returns true if the thread is Daemon else it returns false.
6
What are some of the applications and benefits of using
this daemon thread?(7+8)
Daemon threads are useful for background supporting tasks such as garbage
collection, releasing memory of unused objects and removing unwanted entries
from the cache. Most JVM threads are daemon threads . Their sole purpose is that
they provide services to user thread for background supporting task. If there is no
user thread, there is no need for the JVM keep running this thread. That is why JVM
terminates the daemon thread if there is no user thread.
Thread group(3+4)
Java provides a convenient way to group multiple threads in a single object.
Java.lang.ThreadGroup class in Java offers a convenient way to manage groups of
7
threads as a unit. The thread group form a tree in which every group except the
initial thread group has a parent.
A thread is allowed to access information about its thread group but does not
have access to information about its parent group or any other thread group.
- Thread group (string name) : It creates a thread group with a given name.
- Thread group (thread group parent, string name) - It creates a thread group
with given parent group and name.
1//Shutdown hook
1//The shutdown hook can be used to perform cleanup resource or save the
state when JVM shuts down normally or abruptly. Performing clean resource
means closing log file, sending some alerts or something else.
2// So if you want to execute some code before JVM shuts down, use the
shutdown hook.
The addShutdownHook() method of Runtime class is used to register the thread
with the Virtual Machine.
8
3//On the surface, using a shutdown hook is downright straightforward. All we
have to do is simply write a class which extends the java.lang.Thread class, and
provide the logic that we want to perform when the VM is shutting down, inside the
public void run() method. 4//Then we register an instance of this class as a shutdown
hook to the VM by calling Runtime.getRuntime().addShutdownHook(Thread)
method.
- 5//The important features of java virtual machine are shutdown hooks
because they provide the capacity to do the cleanup of resources or store the
state of the application when the java virtual machine is shutting down
- 4//The shutdown hooks can be executed at runtime when the java virtual
machine is shutting down normally or abruptly.
- 6//More than one shutdown hooks can be registered at any time during the
running of a java virtual machine through a runtime application programming
interface
9//Java synchronisation
9//Multi -Threaded programs may often have a situation where multiple threads try
to access the same resources and finally produce erroneous and unforeseen results.
So there needs to be some synchronisation method that only one thread can
access the resource at a given point of time.
10//Java provides a way of creating threads and synchronising their task by
using synchronised blocks. Synchronised blocks in Java are marked with the
synchronised keyword. Such a block is synchronised on some object.
9
1//All synchronised blocks synchronised on the same object can only have one
thread executing inside them at a time. All other threads attempting to enter this
block are blocked until the thread inside the synchronised block exits the block.
10
threads such that only one thread accesses the synchronised resource and other
threads wait for the resource to become free.
1//Java provides a way of creating threads and synchronising their task by using
synchronised blocks. These blocks are marked with the synchronised keyword. When
we use such a block, internally Java uses a monitor also known as monitor lock or
intrinsic lock, to provide synchronisation.
2//Yes in fact, all such blocks synchronised on the same object can only have
one thread executing inside them at a time. All other threads attempting to enter
the synchronised block are blocked until the thread inside the block exits it.
- 5// As scope of lock is inversely proportional to performance, it is always
better to lock only critical section of code.
- 4//One of the best example of using a block is double checked locking in
Singleton pattern where instead of locking whole getInstance() method we
only lock the critical section of code which is used to create Singleton
instance. This improves performance drastically because locking is only
required a few times.
- 5//Synchronised block can throw throw java.lang.NullPointerException if
expression provided to block as parameter evaluates to null, which is not the
case with synchronised methods.
9.
- 6//These blocks also provide granular control over lock, as you can use
arbitrary lock to provide mutual exclusion to critical section code. On the
other hand, synchronised methods always lock either on the current object
represented by this keyword or class level lock, if it is the static synchronised
method.
- 7//In the case of synchronised method, lock is acquired by thread when it
enters method and released when it leaves method, either normally or by
throwing Exception. On the other hand in case of synchronised block, thread
acquires lock when they enter synchronised block and release when they
leave synchronised block.
11
- 8// So if we want to lock the whole object, we should use a synchronised
method. If we want to keep other parts of the object accessible to other
threads, then the synchronised blocks are the ones we should opt for.
9 //If we choose the locked object carefully, synchronised blocks will lead to less
contention because the whole object/class is not blocked.
10//Applications
10.// Practically, all server applications require some sort of synchronisation between
multiple threads. Most of the synchronisation work is done for us at the framework
level, such as by our web server, database client or messaging framework.
1//The synchronised keyword in Java is used to provide mutually exclusive
access to a shared resource with multiple threads in Java. Synchronisation in Java
guarantees that no two threads can execute a synchronised method which requires
the same lock simultaneously or concurrently.
2//Synchronisation in java comes into play when you have multiple threads
doing certain job, and you want them to be able to work in correspondence to each
other when some dependent task is involved.
3// Yes, I’d like to talk about a real life application of this
Consider this:
There is a voting process going on. You have two teams whose voters can vote
for - A and B. Now, the voting process will happen in various localities, and each
locality has its voters and a collector who counts the votes. After the collector has
collected the votes, they take it to a central location to add with the existing votes in
the central box.
4//In this example the voting process in each locality is like a thread. Each can
occur independently without interfering with any of the others.
But when the collector comes to add the votes at the central location, they need
to synchronise with other collectors who have also come to deposit their count.
5//This is where synchronisation comes in. Both are not allowed to access the
box simultaneously, one has to wait for the other to finish so that he/she could work
with the updated value.
12
6//Do any of the GUI toolkits like Swing,
Javafx, etc. use threads to keep track of
various events generated by the different
widgets in the GUI?
7// In most configurations, there is only one CPU. Thus threads must share the CPU
with other threads. The execution of multiple threads on a single CPU, in some
order, is called scheduling.
6//The Java runtime supports a simple, deterministic scheduling algorithm known as
fixed priority scheduling.
8//Each Java thread is given a numeric priority, between MINPRIORITY and
MAXPRIORITY (constants defined in class Thread). At any given time, when multiple
threads are ready to be executed, the thread with the highest priority will be chosen
for execution. 9//Only when that thread stops, or is suspended for some reason, will
a lower priority thread start executing. Scheduling of the CPU is preemptive in
nature. If a thread with a higher priority than the currently executing thread needs to
execute, the higher priority thread is immediately scheduled.
10// The Java runtime will not preempt the currently running thread for another
thread of the same priority. In other words, the Java runtime does not time-slice.
However, the system implementation of threads underlying the Java Thread class
may support time-slicing. Do not write code that relies on time-slicing.
1// If the currently running thread yields the CPU (i.e. allows another thread to
execute by calling the yield()), then the scheduler implements a simple
non-preemptive round-robin scheduling order.
2// In addition, a given thread may, at any time, give up its right to execute by
calling the yield() method.
3//Threads can only yield the CPU to other threads of the same
priority--attempts to yield to a lower priority thread are ignored.
Conclusion
4//I believe we’ve discussed a great deal about everything. So, Thread priority is an
essential concept since the scheduler picks up the threads for execution based on
the priority.
5//However, thread priorities cannot guarantee that a higher priority thread will
always be executed first than the lower priority thread. With that note I’d like to
conclude our discussion.
13