blog banner
 

 

1. What is Multi Tasking?

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)

1) Process-based Multitasking (Multiprocessing)

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

2) Thread-based Multitasking (Multithreading)

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

 

2. What is Thread in JAVA ?

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, which is created by the JVM at the program’s start, when the main() method is invoked with the main thread. In Java, creating a thread is accomplished by implementing an interface and extending a class. Every Java thread is created and controlled by the java.lang.Thread class.

When a thread is created, it is assigned a priority. The thread with higher priority is executed first, followed by lower-priority threads. The JVM stops executing threads under either of the following conditions:
If the exit method has been invoked and authorized by the security manager

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.

All the daemon threads of the program have died
 

3. How To create a Thread ?

Question no. 33 is a proper example of how to create a thread.

There are two ways to create a thread in Java:

1) By extending Thread class.
2) By implementing Runnable interface.

Method 1: Thread creation by extending Thread class

Example:

class MultithreadingDemo extends Thread{

public void run(){

System.out.println("My thread is in running state.");

}

public static void main(String args[]){

MultithreadingDemo obj=new MultithreadingDemo();
obj.start();

}

}

Output:

My thread is in running state.
 

Method 2: Thread creation by implementing Runnable Interface

Example

class MultithreadingDemo implements Runnable{

public void run(){

System.out.println("My thread is in running state.");

}
public static void main(String args[]){

MultithreadingDemo obj=new MultithreadingDemo();
Thread tobj =new Thread(obj);
tobj.start();

}

}

Output:

My thread is in running state.
 

4. What is Thread Priority in JAVA ?

Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.

Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).

Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependent.

Points to remember :

  • Thread priorities are the integers which decide how one thread should be treated with respect to the others.
  • Thread priority decides when to switch from one running thread to another, process is called context switching
  • A thread can voluntarily release control and the highest priority thread that is ready to run is given the CPU.
  • A thread can be preempted by a higher priority thread no matter what the lower priority thread is doing. Whenever a higher priority thread wants to run it does.
  • To set the priority of the thread setPriority() method is used which is a method of the class Thread Class.
  • In place of defining the priority in integers, we can use MIN_PRIORITY, NORM_PRIORITY or MAX_PRIORITY.

 

5. How to set and retrieve thread priorities in JAVA ?

To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.

This is its general form:

final void setPriority(int level)

Here, level specifies the new priority setting for the calling thread. The value of level must be
within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and
10, respectively. To return a thread to default priority, specify NORM_PRIORITY, which is
currently 5. These priorities are defined as static final variables within Thread.
You can obtain the current priority setting by calling the getPriority( ) method of Thread,
shown here:

final int getPriority( )

Example : 

class clicker implements Runnable {

long click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p) {

t = new Thread(this);
t.setPriority(p);

}
public void run() {

while (running) {

click++;

}

}
public void stop() {

running = false;

}
public void start() {

t.start();

}

}
class HiLoPri {

public static void main(String args[]) {

Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {

Thread.sleep(10000);

} catch (InterruptedException e) {

System.out.println("Main thread interrupted.");

}

lo.stop();
hi.stop();
// Wait for child threads to terminate.
try {

hi.t.join();
lo.t.join();

} catch (InterruptedException e) {

System.out.println("InterruptedException caught");

}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);

}

}

The output of this program, shown as follows when run under Windows, indicates that
the threads did context switch, even though neither voluntarily yielded the CPU nor blocked
for I/O. The higher-priority thread got the majority of the CPU time.
Low-priority thread: 4408112
High-priority thread: 589626904
 

6. What is the purpose of isAlive() and Join() in JAVA ?

In all the practical situations main thread should finish last else other threads which have spawned from the main thread will also finish. To know whether the thread has finished we can call isAlive() on the thread which returns true if the thread is not finished. Another way to achieve this by using join() method, this method when called from the parent thread makes parent thread wait till child thread terminates. These methods are defined in the Thread class.

Example of isAlive method Example of thread with join() method 

public class MyThread extends Thread
{

public void run()
{

System.out.println("r1 ");
try {

Thread.sleep(500);

}
catch(InterruptedException ie) { }
System.out.println("r2 ");

}
public static void main(String[] args)
{

MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();
t2.start();
System.out.println(t1.isAlive());
System.out.println(t2.isAlive());

}

}


 public class MyThread extends Thread
{

public void run()
{

System.out.println("r1 ");
try {

Thread.sleep(500);

}catch(InterruptedException ie){ }
System.out.println("r2 ");

}
public static void main(String[] args)
{

MyThread t1=new MyThread();
MyThread t2=new MyThread();
t1.start();

try{

t1.join(); //Waiting for t1 to finish

}catch(InterruptedException ie){}

t2.start();

}

}


Output :
r1
true
true
r1
r2
r2
 Output :
r1
r2
r1
r2

 

7. Can we set time with Join() ?

yes we can use time. For example take the above program, If we specify time while using join() with t1, then t1 will execute for that time, and then t2 will join it.

t1.join(1500);

Doing so, initially t1 will execute for 1.5 seconds, after which t2 will join it.
 

8. Explain Life Cycle of a thread ?

NEW – A thread that has not yet started is in this state.

RUNNABLE – A thread executing in the Java virtual machine is in this state.

BLOCKED – A thread that is blocked waiting for a monitor lock is in this state.

WAITING – A thread that is waiting indefinitely for another thread to perform a particular action is in this state.

TERMINATED – A thread that has exited is in this state.

A thread can be in only one state at a given point in time.

 

9. What is main thread in JAVA ?

When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins. The main thread is important for two reasons:

  • It is the thread from which other “child” threads will be spawned.
  • Often, it must be the last thread to finish execution because it performs various shutdown actions.

Although the main thread is created automatically when your program is started, it can be controlled through a Thread object. To do so, you must obtain a reference to it by calling the method currentThread( ), which is a public static member of Thread. Its general form is shown here:

static Thread currentThread( )

This method returns a reference to the thread in which it is called. Once you have a reference to the main thread, you can control it just like any other thread.
 

10. What is Multi threading in JAVA ?

Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, 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.

Java Multithreading is mostly used in games, animation etc.
 

11. Write a JAVA code demonstrating multithreading in JAVA ?

// Create multiple threads.
class NewThread implements Runnable {

String name; // name of thread
Thread t;
NewThread(String threadname) {

name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread

}

// This is the entry point for thread.

public void run() {

try {

for(int i = 5; i > 0; i--) {

System.out.println(name + ": " + i);
Thread.sleep(1000);

}

} catch (InterruptedException e) {

System.out.println(name + "Interrupted");

}

System.out.println(name + " exiting.");

}

}

class MultiThreadDemo {

public static void main(String args[]) {

new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");

try {

// wait for other threads to end
Thread.sleep(10000);

} catch (InterruptedException e) {

System.out.println("Main thread Interrupted");

}
System.out.println("Main thread exiting.");

}

}

The output from this program is shown here:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.


As you can see, once started, all three child threads share the CPU. Notice the call to sleep(10000) in main( ). This causes the main thread to sleep for ten seconds and ensures that it will finish last.
 

12. What is the difference between Multitasking , Multithreading , Multiprocessing and parallel processing ?

Multitasking: Ability to execute more than one task at the same time is known as multitasking.

Multithreading: We already discussed about it. It is a process of executing multiple threads simultaneously. Multithreading is also known as Thread-based Multitasking.

Multiprocessing: It is same as multitasking, however in multiprocessing more than one CPUs are involved. On the other hand one CPU is involved in multitasking.

Parallel Processing: It refers to the utilization of multiple CPUs in a single computer system.
 

13. What is synchronization in java ?

When two or more threads need access to a shared resource, they need some way to ensure
that the resource will be used by only one thread at a time. The process by which this is
achieved is called synchronization. As you will see, Java provides unique, language-level
support for it.

Key to synchronization is the concept of the monitor (also called a semaphore). A monitor
is an object that is used as a mutually exclusive lock, or mutex. Only one thread can own a
monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor.
All other threads attempting to enter the locked monitor will be suspended until the first
thread exits the monitor. These other threads are said to be waiting for the monitor. A thread
that owns a monitor can reenter the same monitor if it so desires

In Summary, Java synchronized Keyword provides following functionality essential for concurrent programming:

1) The synchronized keyword in Java provides locking, which ensures mutually exclusive access to the shared resource and prevents data race.

2) synchronized keyword also prevent reordering of code statement by the compiler which can cause a subtle concurrent issue if we don't use synchronized or volatile keyword.

3) synchronized keyword involve locking and unlocking. before entering into synchronized method or block thread needs to acquire the lock, at this point it reads data from main memory than cache and when it release the lock, it flushes write operation into main memory which eliminates memory inconsistency errors.

Example:

Public synchronized void increment()
{

X++;

}
 

14. Why We need Synchronization in JAVA ?

Java supports multiple threads to be executed. This may cause two or more threads to access the same fields or objects. Synchronization is a process which keeps all concurrent threads in execution to be in synch. Synchronization avoids memory consistence errors caused due to inconsistent view of shared memory. When a method is declared as synchronized; the thread holds the monitor for that method's object If another thread is executing the synchronized method, your thread is blocked until that thread releases the monitor.

The synchronization is mainly used to

  • To prevent thread interference.
  • To prevent consistency problem.

 

15. What is Mutual Exclusive threads in JAVA ?

Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by using synchronized code.
 

16. What is a Lock in JAVA? Or, What is monitor in JAVA?

Synchronization is built around an internal entity known as the lock or monitor. Every object has an 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.
 

17. In How many ways we can implement synchronization in JAVA with an example programme ?

We can synchronize our code in either of two ways. Both involve the use of the synchronized keyword.

  1. Using Synchronized Methods
  2. using Synchronized Statement / Synchronized block

 

18. How can we Synchronize our code using synchronized methods ?

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.

In Other words, To enter an object’s monitor, just call a method that has been modified with the synchronized keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on the same instance have to wait. To exit the monitor and relinquish control of the object to the next waiting thread, the owner of the monitor simply returns from the synchronized method.

Example : 

The following program has three simple classes. The first one, Callme, has a single method named call( ). The call( ) method takes a String parameter called msg. This method tries to print the msg string inside of square brackets. The interesting thing to notice is that after call( ) prints the opening bracket and the msg string, it calls Thread .sleep(1000), which pauses the current thread for one second.

The constructor of the next class, Caller, takes a reference to an instance of the Callme class and a String, which are stored in target and msg, respectively. The constructor also creates a new thread that will call this object’s run( ) method. The thread is started immediately. The run( ) method of Caller calls the call( ) method on the target instance of Callme, passing in the msg string. Finally, the Synch class starts by creating a single instance of Callme, and three instances of Caller, each with a unique message string. The same instance of Callme is passed to each Caller.

Program without method synchronization Program with method synchronization

class Callme {

void call(String msg) {

System.out.print("[" + msg);
try {

Thread.sleep(1000);

} catch(InterruptedException e) {

System.out.println("Interrupted");

}
System.out.println("]");

}

}
class Caller implements Runnable {

String msg;
Callme target;
Thread t;

public Caller(Callme targ, String s) {

target = targ;
msg = s;
t = new Thread(this);
t.start();

}
public void run() {

target.call(msg);

}

}
class Synch {

public static void main(String args[]) {

Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {

ob1.t.join();
ob2.t.join();
ob3.t.join();

} catch(InterruptedException e) {

System.out.println("Interrupted");

}

}

}


class Callme {

synchronized void call(String msg) {

System.out.print("[" + msg);
try {

Thread.sleep(1000);

} catch(InterruptedException e) {

System.out.println("Interrupted");

}
System.out.println("]");

}

}
class Caller implements Runnable {

String msg;
Callme target;
Thread t;

public Caller(Callme targ, String s) {

target = targ;
msg = s;
t = new Thread(this);
t.start();

}
public void run() {

target.call(msg);

}

}
class Synch {

public static void main(String args[]) {

Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {

ob1.t.join();
ob2.t.join();
ob3.t.join();

} catch(InterruptedException e) {

System.out.println("Interrupted");

}

}

}


Here is the output produced by this program:
Hello[Synchronized[World]
]
]

Here is the output produced by this program:
[Hello]
[Synchronized]
[World]

In the above programme, by calling sleep( ), the call( ) method allows execution to switch to another
thread. This results in the mixed-up output of the three message strings. In this program,
nothing exists to stop all three threads from calling the same method, on the same object, at
the same time. This is known as a race condition, because the three threads are racing each
other to complete the method. This example used sleep( ) to make the effects repeatable and
obvious. In most situations, a race condition is more subtle and less predictable, because
you can’t be sure when the context switch will occur. This can cause a program to run right
one time and wrong the next.

To fix the preceding program, you must serialize access to call( ). That is, you must restrict its
access to only one thread at a time. To do this, you simply need to precede call( )’s definition
with the keyword synchronized, as shown in the programme on righ side.

19. How can we Synchronize our code using synchronized statements / Synchronized Block ?

Using synchronized block in java is also similar to using synchronized keyword in methods. Only important thing to note here is that object is used to lock synchronized block of code

Properties

  • Synchronized block is used to lock an object for any shared resource.
  • Scope of synchronized block is smaller than the method.

Syntax :

You simply put calls to the methods defined by this class inside a synchronized block.

synchronized(object) {

// statements to be synchronized

}

Here, object is a reference to the object being synchronized. A synchronized block ensures
that a call to a method that is a member of object occurs only after the current thread has
successfully entered object’s monitor

Example :

void foo() {

synchronized (this) {

// statements to be synchronized

}

}
 

20. What is the difference between Sychronized Method and Synchronized Block ?  

synchronized method acquires a method on the whole object. This means no other thread can use any synchronized method in the whole object while the method is being run by one thread.

synchronized blocks acquires a lock in the object between parentheses after the synchronized keyword. Meaning no other thread can acquire a lock on the locked object until the synchronized block exits.

The difference is in which lock is being acquired:

1) One significant difference between synchronized method and block is that, Synchronized block generally reduce scope of lock. As scope of lock is inversely proportional to performance, its always better to lock only critical section of code. One of the best example of using synchronized block is double checked locking in Singleton pattern where instead of locking whole getInstance() method we only lock critical section of code which is used to create Singleton instance. This improves performance drastically because locking is only required one or two times.

2) Synchronized block provide granular control over lock, as you can use arbitrary any lock to provide mutual exclusion to critical section code. On the other hand synchronized method always lock either on current object represented by this keyword or class level lock, if its static synchronized method.

3) Synchronized block can throw throw java.lang.NullPointerException if expression provided to block as parameter evaluates to null, which is not the case with synchronized methods.

4) In case of synchronized method, lock is acquired by thread when it enter method and released when it leaves method, either normally or by throwing Exception. On the other hand in case of synchronized block, thread acquires lock when they enter synchronized block and release when they leave synchronized block.

5) For synchronized methods, the lock will be held throughout the method scope, while in the synchronized block, the lock is held only during that block scope (otherwise known as critical section). In practice, the JVM is permitted to optimize by removing some operations out of the synchronized block execution if it can prove that it can be done safely.
 

21. Which one among Sychronized Method and Synchronized Block is more efficient while synchronizing ?Or, Why we need Synchronized Block when we have Synchronized Method ? Explain with an example.

While creating synchronized methods within classes that you create is an easy and effective means of achieving synchronization, it will not work in all cases. To understand why, consider the following. Imagine that you want to synchronize access to objects of a class that was not designed for multithreaded access. That is, the class does not use synchronized methods. Further, this class was not created by you, but by a third party, and you do not have access to the source code. Thus, you can’t add synchronized to the appropriate methods within the class. How can access to an object of this class be synchronized? Fortunately, the solution to this problem is quite easy: You simply put calls to the methods defined by this class inside a synchronized block.

class Callme {

void call(String msg) {

System.out.print("[" + msg);
try {

Thread.sleep(1000);

} catch (InterruptedException e) {

System.out.println("Interrupted");

}
System.out.println("]");

}

}
class Caller implements Runnable {

String msg;

Callme target;
Thread t;
public Caller(Callme targ, String s) {

target = targ;
msg = s;
t = new Thread(this);
t.start();

}
// synchronize calls to call()
public void run() {

synchronized(target) { // synchronized block

target.call(msg);

}

}

}
class Synch1 {

public static void main(String args[]) {

Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {

ob1.t.join();
ob2.t.join();
ob3.t.join();

} catch(InterruptedException e) {

System.out.println("Interrupted");

}

}

}

Here, the call( ) method is not modified by synchronized. Instead, the synchronized statement is used inside Caller’s run( ) method. This causes the same correct output as the preceding example, because each thread waits for the prior one to finish before proceeding. The output produced by this program:

[Hello]
[Synchronized]
[World]

 

22. What is polling in java ? Is it Good for programming Condition ?

Polling is usually implemented by a loop that is used to check some condition repeatedly. Once the condition is true, appropriate action is taken. This wastes CPU time.

For example, consider the classic queuing problem, where one thread is producing some data and another is consuming it. To make the problem more interesting, suppose that the producer has to wait until the consumer is finished before it generates more data. In a polling system, the consumer would waste many CPU cycles while it waited for the producer to produce. Once the producer was finished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, and so on. Clearly, this situation is undesirable

 

23. Why we need inter thread communication in JAVA ? Or, Explain the methods wait( ), notify( ), and notifyAll( ) of JAVA ?

To avoid polling, Java includes an elegant interprocess communication mechanism via the wait( ), notify( ), and notifyAll( ) methods. These methods are implemented as final methods in java.lang.Object, so all classes have them. All three methods can be called only from within a synchronized context. Although conceptually advanced from a computer science perspective, the rules for using these methods are actually quite simple:

• wait( ) : It 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.

• notify( ) wakes up a thread that called wait( ) on the same object.SoiIt 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.

• notifyAll( ) wakes up all the threads that called wait( ) on the same object's monitor. One of the threads will be granted access.

These methods are declared within Object, as shown here:

final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
 

24. What is spurious wakeup in JAVA ?

Although wait( ) normally waits until notify( ) or notifyAll( ) is called, there is a possibility that in very rare cases the waiting thread could be awakened due to a spurious wakeup. In this case, a waiting thread resumes without notify( ) or notifyAll( ) having been called.
 

25. What are the differences between wait() and sleep()?

wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
It is the method of Object class It is the method of Thread class
It is a non-static method It is a static method
It should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is completed.
It is called from synchronised block no such requirement

 

26. What is the producer-consumer problem in JAVA ? Or, Explain interthread communication with an example ?

producer-consumer problem is a classic example of multithreading and interthread communication.

producer-consumer problem:

  • Producer(s) produce items.
  • Consumer(s) consume the items produced by the producer(s).
  • Producer(s) finish production and let the consumers know that they are done.
  • There can be multiple producer.
  • There will be multiple consumers.
  • Once the production of new items is done the producer(s) will let the consumers know so that the consumer will exit after the last item is consumed and processed.

class Q {

int n;
boolean valueSet = false;
synchronized int get() {

while(!valueSet)
try {

wait();

} catch(InterruptedException e) {

System.out.println("InterruptedException caught");

}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;

}
synchronized void put(int n) {

while(valueSet){

try {

wait();

} catch(InterruptedException e) {

System.out.println("InterruptedException caught");

}

}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();

}

}

class Producer implements Runnable {

Q q;

Producer(Q q) {

this.q = q;
new Thread(this, "Producer").start();

}
public void run() {

int i = 0;
while(true) {

q.put(i++);

}

}

}

class Consumer implements Runnable {

Q q;
Consumer(Q q) {

this.q = q;
new Thread(this, "Consumer").start();

}
public void run() {

while(true) {

q.get();

}

}

}

class PCFixed {

public static void main(String args[]) {

Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");

}

}

Inside get( ), wait( ) is called. This causes its execution to suspend until the Producer notifies you that some data is ready. When this happens, execution inside get( ) resumes. After the data has been obtained, get( ) calls notify( ). This tells Producer that it is okay to put more data in the queue. Inside put( ), wait( ) suspends execution until the Consumer has removed the item from the queue. When execution resumes, the next item of data is put in the queue, and notify( ) is called. This tells the Consumer that it should now remove it.
Here is some output from this program, which shows the clean synchronous behavior:

Put: 1
Got: 1
Put: 2
Got: 2
Put: 3

Got: 3
Put: 4
Got: 4
Put: 5
Got: 5
 

27. What are the levels of concurrency in JAVA ?

There are three levels for concurrency:

1. Class
2. Method
3. Variable

1. Class level concurrency is commonly built via extending classes such as Thread or by implementing interfaces such as Runnable, Callable.

2. Method level concurrency is commonly built via synchronized keyword. Also one can use lock, semaphore(classes).

3. Variable level concurrency can be built by making variable of type Atomic. It takes care of race condition.
 

28. What is critical section in java ?

In concurrent programming, a critical section or critical region is a part of a multi-threaded program that may not be concurrently executed by more than one of the program's processes. In other words, it is a piece of a program that requires mutual exclusion of access. Typically, the critical section accesses a shared resource, such as a data structure, a peripheral device, or a network connection, that does not allow multiple concurrent accesses.

A critical section may consist of multiple discontiguous parts of the program's code. For example, one part of a program might read from a file that another part wishes to modify. These parts together form a single critical section, since simultaneous readings and modifications may interfere with each other.

A critical section will usually terminate in finite time,and a thread, task, or process will have to wait for a fixed time to enter it (aka bounded waiting). Some synchronization mechanism is required at the entry and exit of the critical section to ensure exclusive use, for example a semaphore.
 

29. What is Race condition in JAVA ?

A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.

A race condition is a special condition that may occur inside a critical section. A critical section is a section of code that is executed by multiple threads and where the sequence of execution for the threads makes a difference in the result of the concurrent execution of the critical section.

When the result of multiple threads executing a critical section may differ depending on the sequence in which the threads execute, the critical section is said to contain a race condition. The term race condition stems from the metaphor that the threads are racing through the critical section, and that the result of that race impacts the result of executing the critical section.
 

30. How to prevent Race condition and critical section in java ?

To handle these situations we either must not use shared resource or should use some locking mechanism. This can be done by synchronization.

To prevent race conditions from occurring you must make sure that the critical section is executed as an atomic instruction. That means that once a single thread is executing it, no other threads can execute it until the first thread has left the critical section.

Race conditions can be avoided by proper thread synchronization in critical sections. Thread synchronization can be achieved using a synchronized block / synchronized method of Java code.
 

31. What is Deadlock scenario in multithreading of JAVA ? What is the disadvantahe of synchronization in JAVA? Explain with an example.

A special type of error of multitasking is deadlock, which occurs when two threads have a circular dependency on a pair of synchronized objects. For example, suppose one thread enters the monitor on object X and another thread enters the monitor on object Y. If the thread in X tries to call any synchronized method on Y, it will block as expected. However, if the thread in Y, in turn, tries to call any synchronized method on X, the thread waits forever, because to access X, it would have to release its own lock on Y so that the first thread could complete.

A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object.

class A {

synchronized void foo(B b) {

String name = Thread.currentThread().getName();
System.out.println(name + " entered A.foo");
try {

Thread.sleep(1000);

} catch(Exception e) {

System.out.println("A Interrupted");

}
System.out.println(name + " trying to call B.last()");
b.last();

}
synchronized void last() {

System.out.println("Inside A.last");

}

}
class B {

synchronized void bar(A a) {

String name = Thread.currentThread().getName();
System.out.println(name + " entered B.bar");
try {

Thread.sleep(1000);

} catch(Exception e) {

System.out.println("B Interrupted");

}
System.out.println(name + " trying to call A.last()");
a.last();

}
synchronized void last() {

System.out.println("Inside A.last");

}

}
class Deadlock implements Runnable {

A a = new A();
B b = new B();
Deadlock() {

Thread.currentThread().setName("MainThread");
Thread t = new Thread(this, "RacingThread");
t.start();
a.foo(b); // get lock on a in this thread.
System.out.println("Back in main thread");

}

public void run() {

b.bar(a); // get lock on b in other thread.
System.out.println("Back in other thread");

}

public static void main(String args[]) {

new Deadlock();

}

}

When you run this program, you will see the output shown here:

MainThread entered A.foo
RacingThread entered B.bar
MainThread trying to call B.last()
RacingThread trying to call A.last()

Because the program has deadlocked, you need to press CTRL-C to end the program. You can see a full thread and monitor cache dump by pressing CTRL-BREAK on a PC . You will see that RacingThread owns the monitor on b, while it is waiting for the monitor on a. At the same time, MainThread owns a and is waiting to get b. This program will never complete. As this example illustrates, if your multithreaded program locks up occasionally, deadlock is one of the first conditions that you should check for.

 

32. How to avoid deadlock in java ?

One of the best ways to prevent the potential for deadlock is to avoid acquiring more than one lock at a time.
 

33. Explain start() and run() method while creating a thread in java ?

The start() method causes this thread to begin execution, the Java Virtual Machine calls the run method of this thread.The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

The run() method is called if this thread was constructed using a separate Runnable run object, else this method does nothing and returns. To implement Runnable, a class need only implement a single method called run( ), which is declared like this:

public void run( )

Inside run( ), you will define the code that constitutes the new thread. It is important to understand that run( ) can call other methods, use other classes, and declare variables, just like the main thread can. The only difference is that run( ) establishes the entry point for another, concurrent thread of execution within your program. This thread will end when run( ) returns.

After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. In essence, start( ) executes a call to run( ). 

// Create a second thread.
class NewThread implements Runnable {

Thread t;
NewThread() {

// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread

}
// This is the entry point for the second thread.
public void run() {

try {

for(int i = 5; i > 0; i--) {

System.out.println("Child Thread: " + i);
Thread.sleep(500);

}

} catch (InterruptedException e) {

System.out.println("Child interrupted.");

}
System.out.println("Exiting child thread.");

}

}

class ThreadDemo {

public static void main(String args[]) {

new NewThread(); // create a new thread
try {

for(int i = 5; i > 0; i--) {

System.out.println("Main Thread: " + i);
Thread.sleep(1000);

}

} catch (InterruptedException e) {

System.out.println("Main thread interrupted.");

}
System.out.println("Main thread exiting.");

}

}
 

Questions On Multithreading will be continued in part#7

Admin Team


0 Respond



Written
Exam Questions
BLOG Posts
For study materials
Job Walk-In
Updates across India
Interview round
Questions
Interview or procedure
Experiences
Files
For study materials
Please LIKE our page to Get regular JOB WALK-IN UPDATES across India and STUDY MATERIALS on facebook news feed.