Multithreading

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Multithreading - advantage

1) It doesn't block the user because threads are independent and you can perform multiple operations at same time. 2) You can perform many operations together so it saves time. 3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.

How many process(es) are required for each thread?

At least one process is required for a thread.

Runtime class important methods

1) public static Runtime getRuntime() returns the instance of Runtime class. 2) public void exit(int status) terminates the current virtual machine. 3) public void addShutdownHook(Thread hook) registers new hook thread. 4) public Process exec(String command)throws IOException executes given command in a separate process. 5) public int availableProcessors() returns no. of available processors. 6) public long freeMemory() returns amount of free memory in JVM. 7) public long totalMemory() returns amount of total memory in JVM.

Multiprocessing - Process-based Multitasking

1. Each process has its own address in memory i.e. each process is allocated separate memory in area. 2. Process is heavyweight. 3. Cost of communication between the process is high. 4. Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.

What if we call run() method directly instead start() method?

1. Each thread will start in a separate call stack. 2. Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.

Garbage Collection - advantage

1. It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory. 2. It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

daemon thread - Points to remember for Daemon Thread in Java

1. It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads. 2. Its life depends on user threads. 3. It is a low priority thread.

Garbage Collection

In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.

Runtime freeMemory() and totalMemory() method

In the given program, after creating 10000 instance, free memory will be less than the previous free memory. But after gc() call, you will get more free memory.

Daemon Thread

Daemon thread in java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically. There are many java daemon threads running automatically e.g. gc, finalizer etc.

Inter-thread communication in Java

Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class: 1.wait() 2.notify() 3.notifyAll()

Reentrant Monitor - advantage

It eliminates the possibility of single thread deadlocking

Why wait(), notify() and notifyAll() methods are defined in Object class not Thread class?

It is because they are related to lock and object has a lock.

Java Serialization - advantage

It is mainly used to send object's state on the network (known as marshaling).

Real time usage

It is used in Servlet and JSP where container creates a thread pool to process the request.

Runtime class

Java Runtime class is used to interact with java runtime environment. Java Runtime class provides methods to execute a process, invoke GC, get total and free memory etc. There is only one instance of java.lang.Runtime class is available for one java application. The Runtime.getRuntime() method returns the singleton instance of Runtime class.

Thread Pool

Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times. In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.

Deadlock in java

Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock.

priority - Default priority of thread:

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways: 1. Process-based Multitasking(Multiprocessing) 2.Thread-based Multitasking(Multithreading)

multithreading

Multithreading is a process of executing multiple threads simultaneously.

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java: 1 .by synchronized method 2. by synchronized block 3. by static synchronization

start a thread twice

No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown.

In a process, how many threads can run at a time?

Only one thread at a time can run in a single process.

static synchronization - Problem without static synchronization

Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock.But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock.I want no interference between t1 and t3 or t2 and t4.Static synchronization solves this problem.

Synchronization in Java

Synchronization in java is the capability to control the access of multiple threads to any shared resource. Java Synchronization is better option where we want to allow only one thread to access the shared resource.

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor. Every object has a lock associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them. From Java 5 the package java.util.concurrent.locks contains several lock implementations.

Synchronized block in java

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.

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes. public static void gc(){} Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected.

join - The join() method:

The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task. Syntax: 1. public void join()throws InterruptedException. 2. public void join(long milliseconds)throws InterruptedException. As you can see in the above example,when t1 completes its task then t2 and t3 starts executing.

Thread states are as follows:

The life cycle of the thread in java is controlled by JVM. 1. New. 2. Runnable. 3. Running. 4. Non-Runnable (Blocked). 5. Terminated. (study diagram)

Factory method

The method that returns the instance of a class is known as factory method.

Shutdown Hook

The shutdown hook can be used to perform cleanup resource or save the state when JVM shuts down normally or abruptly. Performing resource cleanup means closing log file, sending some alerts or something else. So if you want to execute some code before JVM shuts down, use shutdown hook.

Sleep method in java

The sleep() method of Thread class is used to stop the execution of a thread temporarily for the specified amount of time. If you sleep a thread for the specified time,the thread shedular picks up another based on factors like priority of a thread, etc. from the pool of ready.

daemon thread - Why JVM terminates the daemon thread if there is no user thread?

The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.

If the start() method of a thread internally calls the run() method, then why don't we directly call the run() method in our code? What are the issues involved in doing so?

The start method makes sure the code runs in a new thread context. If you called run directly, then it would be like an ordinary method call and it would run in the context of the current thread instead of the new one. The start method contains the special code to trigger the new thread; run obviously doesn't have that ability because you didn't include it when you wrote the run method.

Synchronization - why to use it

The synchronization is mainly used to 1. To prevent thread interference. 2. To prevent consistency problem.

new

The thread is in new state if you create an instance of Thread class but before the invocation of start() method.

runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.

running

The thread is in running state if the thread scheduler has selected it.

Thread scheduler - What does the thread scheduler mainly uses to schedule threads?

The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.

unreference an object

There are many ways: 1. By nulling the reference 2. By assigning a reference to another 3. By annonymous object etc.

Synchronization - types

There are two types of synchronization 1. Process Synchronization 2. Thread Synchronization

Synchronization - thread synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication. 1. Mutual Exclusive Synchronized method. Synchronized block. static synchronization. 2. Cooperation (Inter-thread communication in java)

create thread

There are two ways to create a thread: 1. By extending Thread class. 2. By implementing Runnable interface.

Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

Who makes your class object as thread object?

Thread class constructor allocates a new thread object.When you create object of Multi class,your class constructor is invoked(provided by Compiler) fromwhere Thread class constructor is invoked(by super() as first statement).So your Multi class object is thread object now.

Thread class

Thread class provide constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.

thread

Thread is a lightweight sub-process, a smallest unit of processing.

Thread Scheduler

Thread scheduler in java is the part of the JVM that decides which thread should run. There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.

currently running thread - How to get the id and name of the?

Thread.currentThread().getId(); Thread.currentThread().getName(); Both these methods should be in the run method.

light-weight - thread considered light-weight?

Threads are considered lightweight because they use far less resources than processes.

The point to point explanation of the above diagram is as follows:

Threads enter to acquire lock. Lock is acquired by on thread. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state). Now thread is available to acquire lock. After completion of the task, thread releases the lock and exits the monitor state of the object.

It's important to note that a thread can do anything a process can do.

True

Note: Neither finalization nor garbage collection is guaranteed.

True

Note: The shutdown sequence can be stopped by invoking the halt(int) method of Runtime class.

True

Threads have independent call stack

True

daemon thread - Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException.

True

garbage collector - Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).

True

Difference between preemptive scheduling and time slicing

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states . Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

notify() method

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax: public final void notify()

notifyAll() method

Wakes up all threads that are waiting on this object's monitor. Syntax: public final void notifyAll()

jconsole

You can see all the detail by typing the jconsole in the command prompt. The jconsole tool provides information about the loaded classes, memory usage, running threads etc.

currentThread() method syntax

public static Thread currentThread(): returns the reference of currently running thread.

The 3 methods provided by the Thread class for interrupting a thread

public void interrupt() public static boolean interrupted() public boolean isInterrupted()

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following tasks: 1. A new thread starts(with new callstack). 2. The thread moves from New state to the Runnable state. 3. When the thread gets a chance to execute, its target run() method will run.

Difference between wait and sleep?

wait() sleep() 1. wait() method releases the lock, but sleep() method doesn't release the lock. 2. wait method is the method of Object class, but sleep method is the method of Thread class 3. wait method is the non-static method, but sleep method is the static method 4. wait method should be notified by notify() or notifyAll() methods, sleep method after the specified amount of time, sleep is completed.

public final void wait(long timeout)throws InterruptedException

waits for the specified amount of time.

public final void wait()throws InterruptedException

waits until object is notified

How to perform multiple tasks by multiple threads (multitasking in multithreading)?

If you have to perform multiple tasks by multiple threads,have multiple run() methods.For example: Program of performing two tasks by two threads

Difference between a process and a thread?

1. Process is a running instance of an application. Thread is a light weight sub process, it is the smallest unit of processing. 2. Another difference between a thread and a process is that threads within the same process share the same address space, whereas different processes do not. This allows threads to read from and write to the same data structures and variables, and also facilitates communication between threads. Threads also share any other resources within that process. This means that it's very easy to share data amongst threads, but it's also easy for the threads to step on each other, which can lead to bad things. 3. Communication between processes - also known as IPC, or inter-process communication - is quite difficult and resource-intensive. 4. Also, context switching between threads is generally less expensive than in processes. And finally, the overhead (the cost of communication) between threads is very low relative to processes

Points to remember for Synchronized block

1. Synchronized block is used to lock an object for any shared resource. 2. Scope of synchronized block is smaller than the method. Syntax to use synchronized block synchronized (object reference expression) { //code block }

Multithreading - Thread-based Multitasking

1. Threads share the same address space. 2. Thread is lightweight. 3. Cost of communication between the thread is low.

3 constants defined in Thread class:

1. public static int MIN_PRIORITY 2. public static int NORM_PRIORITY 3. public static int MAX_PRIORITY

daemon thread - Methods for Java Daemon thread by Thread class

1. public void setDaemon(boolean status) - is used to mark the current thread as daemon thread or user thread. Once you start a thread you cannot set it as a daemon thread. 2. public boolean isDaemon() - is used to check that current is daemon.

Constructors of Thread class:

1.Thread(). 2.Thread(String name). 3.Thread(Runnable r). 4.Thread(Runnable r,String name).

Methods of Thread class:

1.public void run(): is used to perform action for a thread. 2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread. 3.public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. 4.public void join(): waits for a thread to die. 5.public void join(long miliseconds): waits for a thread to die for the specified miliseconds. 6.public int getPriority(): returns the priority of the thread. 7.public int setPriority(int priority): changes the priority of the thread. 8.public String getName(): returns the name of the thread. 9.public void setName(String name): changes the name of the thread. 10.public Thread currentThread(): returns the reference of currently executing thread. 11.public int getId(): returns the id of the thread. 12.public Thread.State getState(): returns the state of the thread. 13.public boolean isAlive(): tests if the thread is alive. 14.public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute. 15.public void suspend(): is used to suspend the thread(depricated). 16.public void resume(): is used to resume the suspended thread(depricated). 17.public void stop(): is used to stop the thread(depricated). 18.public boolean isDaemon(): tests if the thread is a daemon thread. 19.public void setDaemon(boolean b): marks the thread as daemon or user thread. 20.public void interrupt(): interrupts the thread. 21.public boolean isInterrupted(): tests if the thread has been interrupted. 22.public static boolean interrupted(): tests if the current thread has been interrupted.

Example of multi-threading.

A common example of the advantage of multithreading is the fact that you can have a word processor that prints a document using a background thread, but at the same time another thread is running that accepts user input, so that you can type up a new document. If we were dealing with an application that uses only one thread, then the application would only be able to do one thing at a time - so printing and responding to user input at the same time would not be possible in a single threaded application.

Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state. But for better understanding the threads, we are explaining it in the 5 states.

Terminated

A thread is in terminated or dead state when its run() method exits.

How to perform single task by multiple threads?

If you have to perform single task by many threads, have only one run() method.For example: Note: Each thread run in a separate callstack.

Reentrant Monitor in Java

According to Sun Microsystems, Java monitors are reentrant means java thread can reuse the same monitor for different synchronized methods if method is called from the method.

Static synchronization

If you make any static method as synchronized, the lock will be on the class not on object.

thread pool - Advantage of Java Thread Pool

Better performance. It saves time because there is no need to create new thread.

Multiprocessing and multithreading - used

Both are used to achieve multitasking. But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

wait() method

Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception.

Priority of a Thread (Thread Priority):

Each thread has a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.

Interrupting a Thread:

If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. If the thread is not in the sleeping or waiting state, calling the interrupt() method performs normal behaviour and doesn't interrupt the thread but sets the interrupt flag to true. Let's first see the methods provided by the Thread class for thread interruption.

By implementing the Runnable interface

If you are not extending the Thread class,your class object would not be treated as a thread object.So you need to explicitly create Thread class object.We are passing the object of your class that implements Runnable so that your class run() method may execute.

Java synchronized method

If you declare any method as synchronized, it is known as synchronized method. Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.

Dependency

Processes are independent of each other. Threads, since they share the same address space are interdependent, so caution must be taken so that different threads don't step on each other.

Critical section.

Sections of code that modify data structures shared by multiple threads are called critical sections. When a critical section is running in one thread it's extremely important that no other thread be allowed into that critical section. This is called synchronization. But, the point is that multithreading requires careful programming.

java.io.Serializable interface

Serializable is a marker interface (has no body). It is just used to "mark" java classes which support a certain capability. It must be implemented by the class whose object you want to persist. Let's see the example given below:

Serialization in Java

Serialization in java is a mechanism of writing the state of an object into a byte stream. It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies. The reverse operation of serialization is called deserialization. The String class and all the wrapper classes implements java.io.Serializable interface by default.

process is considered heavyweight?

Since a process can consist of multiple threads, a thread could be considered a 'lightweight' process. Thus, the essential difference between a thread and a process is the work that each one is used to accomplish. Threads are used for small tasks, whereas processes are used for more 'heavyweight' tasks - basically the execution of applications.

When does the JVM shut down?

The JVM shuts down when: 1. user presses ctrl+c on the command prompt 2. System.exit(int) method is invoked 3. user logoff 4. user shutdown etc.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run(). public void run(): is used to perform action for a thread.

Naming a thread:

The Thread class provides methods to change and get the name of a thread. 1. public String getName(): is used to return the name of a thread. 2. public void setName(String name): is used to change the name of a thread.

sleep() method - syntax

The Thread class provides two methods for sleeping a thread: 1. public static void sleep(long miliseconds) throws InterruptedException. 2. public static void sleep(long miliseconds, int nanos) throws InterruptedException.

addShutdownHook(Runnable r) method

The addShutdownHook() method of Runtime class is used to register the thread with the Virtual Machine. Syntax: public void addShutdownHook(Runnable r){} The object of Runtime class can be obtained by calling the static factory method getRuntime(). For example: Runtime r = Runtime.getRuntime();

Synchronized block on a class lock:

The block synchronizes on the lock of the object denoted by the reference .class name .class. A static synchronized method printTable(int n) in class Table is equivalent to the following declaration:

currentThread() method:

The currentThread() method returns a reference to the currently executing thread object.

finalize() method

The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as: protected void finalize(){}


Ensembles d'études connexes

FIN Ch. 14, Working capital and current assets management

View Set

Head and Spine Injuries Ch.29 Hw

View Set

NCLEX-PN Maternal and Women's Health Nursing EAQ questions and answers

View Set

Truman Doctrine and Marshall Plan

View Set

Human Biology Chapter 20 (Cancer)

View Set