Daemon thread

Threads which are running in background to provide support to “main” thread are called Daemon thread.

Daemon thread example: Garbage collector, signal dispatcher etc.

When main thread runs with low memory problem then JVM runs Garbage collector to destroy useless objects. So that memory get improve and main thread can continue.

 

How to check thread is Daemon or not?

Below method is use to check current thread is Daemon or not.

isDaemon() method returns boolean value. IF current thread is not Daemon then it will return false.

Output:

As current working thread is “main” which is always non-daemon. That’s why false is answer.

 

How to set a thread as Daemon

We can change nature of thread using below method.

We can set non-Daemon thread to daemon and daemon to non daemon. But changing nature of a thread is possible before starting of a thread only.

Output:

If we try to change nature of a thread after starting we will get Runtime Exception: IllegalThreadStateException.
We can not change nature of “main” thread because it is already started by JVM.

Output:

Default nature of Thread

By default main thread is always non-daemon and all remaining threads nature will inherited from parent to child. That means if parent is daemon, child thread will also be daemon.

Output:

Whenever last non-Daemon thread terminates automatically all daemon thread will terminate irrespective of there position.

Help others by sharing the content!

Inter Thread communication

Two threads can communicate with each other by using following three methods. These methods are present in Object class but not in Thread class.

  • wait()
  • notify()
  • notifyAll()

wait(): The thread which is expecting a update is responsible to call wait() method. Then immediately the thread enter into waiting state.

notify(): The thread which will perform update is responsible to call notify() method. Then waiting thread will get notification and can continue with updated items.

notifyAll(): This method is used to give notification to all waiting threads.
 
Important points to remember

  • All these 3 methods wait(), notify(), notifyAll() are present in Object class but not in Thread class.
  • To call these methods on any object Thread should be owner of that object i.e thread should have lock of that object i.e thread should be in synchronized area. Otherwise will get Runtime exception: IllegalMonitorException.
  • If a thread call wait() method it immediately releases lock of that object and enter into waiting state.
  • If a thread call notify() method on any object it may not releases lock of that object immediately.
  • Except wait(), notify(), notifyAll() there is no other method where thread releases a lock.

 

Difference between notify() and notifyAll()

notify() will give notification to only one waiting thread. If multiple threads are waiting then only one thread will be notify and the remaining threads will have to wait until further notification.

notifyAll() is use to give notification to all waiting threads of a particular object. Even tho multiple threads get notification only one thread can operate on object at a time.

 

What is Deadlock

If two thread are waiting for each other forever such type of infinite waiting is called Deadlock.
Long waiting of thread where waiting will not end.

 

What is starvation

Long waiting of thread where waiting may end is call starvation.
Example: If there are 100 thread. One thread out of 100 have priority-1 other 99 has priority-10. Then thread with priority-1 has to wait to complete execution of all 99 thread. This waiting is going to long but will end.

Help others by sharing the content!

Synchronization

What is Synchronized keyword

If a multiple threads want to operate on a same object simultaneously, there may be problem of data inconsistency. To overcome this problem we can use synchronized keyword.

Synchronized keyword is only applicable to methods & blocks and not to variables & class.

 

Advantage and disadvantage of synchronized keyword / synchronization

Advantage: Using Synchronized keyword it reduces problem of data inconsistency.

Disadvantage: It increase waiting time of thread. At a time only one thread can operate on object so other threads have to wait. So it creates performance problem.

 

What is Race condition

If a multiple threads want to operate on a same object simultaneously. There may be problem of data inconsistency. This condition is called Race condition.

 

How synchronization is implemented? / Synchronized method

Internally synchronization is implemented by using lock. In java every object has a unique lock.

If a thread wants to operate any synchronization method on object then it first has to take lock of that object. Once thread got a lock then it is allowed to perform any synchronization method on that object.

Once thread completes execution it releases lock. The process of locking and releasing lock is internally take care by JVM.

lock concept is implemented based on object and not on methods.

 

Difference between class level lock and object level lock

What is class level lock

If a thread wants to execute a static synchronized method then first thread require class level lock. Once thread got class level lock then thread can perform any static synchronized method of that class.

 

What is object level lock

If a thread wants to execute a instance synchronized method then first thread require object level lock.

 

Synchronized block

If a very few line of code require a synchronization then it is not useful/ recommended to synchronization method.We should use synchronization block.

Synchronization block reduces waiting time of thread and increase performance as compare to synchronized method.

 

How to implement Synchronized block

We can implement Synchronized block by using following:

  • to get lock of current object – eg: synchronized(this)
  • to get lock of particular object
  • to get lock of class level object – eg: synchronized(Test.class) // Test is class name
Help others by sharing the content!

Thread Priorities

Every thread in java has some priority. It may be default priority generated by JVM or customize priority provided by programmer.

Thread priority range from 1 to 10. 1 is minimum priority where 10 is highest.

Thread class defines following constants to represent some standard priorities.

  • Thread.MIN_PRIORITY
  • Thread.NORM_PRIORITY
  • Thread.MAX_PRIORITY

Thread who has highest priority get first chance. If two threads having same priority then can’t expect exact which thread will get a chance, it’s depend on Thread Scheduler.

Methods to get and set priority of thread

Thread class contain following methods to get and set priority of a thread.

To get priority of current thread “Thread.currentThread.getPriority()”.
To set priority of current thread “Thread.currentThread.setPriority(2)”. It will set 2 as priority to current thread.

If we give priority other than 1 to 10 then we will get compile time exception saying “IllegalArgumentException”
Example:

Output:

Default priority only for “main” thread is 5. All remaining thread will be inherited from parent to child. Then whatever parent thread has will be there for child thread.

Example:

Output:

In below example, child thread “t” get priority inherited from parent thread i.e. “main” thread. That’s why we can’t predict in which order we will get output.

Output:

After changing the priority of child thread to 7, child thread will complete execution first.

Output:

Note: Many operating system won’t support priorities.

You may be interested
Thread.yeild()
Thread.join()
Thread.sleep()

Help others by sharing the content!

yield() method

Thread.yield() method cause to pause current thread execution to give chance to waiting thread of same priority.

yield() method present in Thread class and in java.lang.Thread.yield() package.

If there is no waiting thread of same priority or waiting thread of low priority then same thread can continue its execution.

If multiple threads are waiting with same priority then which thread will get a chance it’s totally depend on Thread Scheduler.

Example without yield()

Output:

In above program, child and main thread have same priority 5 so they executed simultaneously. That’s why we got mix output.

Example using yield()

Output:

Above program shows main thread completed first and got more chances than child thread. Because child thread yield it’s execution and gave chance to waiting thread “main” of same priority 5.

Note: Some platforms won’t provide support to Thread.yield() method. So don’t get output as expected.

You may be interested
Thread Priority
Thread.join()
Thread.sleep()

Help others by sharing the content!

Thread.join() method

If a thread wants to wait until completing some other thread then go for Thread.join() method. This method present in Thread class of java.

Consider a thread t1 wants to wait until completing execution of t2 then t1 has to call t2.join().
If t1 execute t2.join() then t1 will go to waiting state until t2 completes. Once t2 complete t1 can continue it’s execution.

Syntax:

join() throws “InterruptedException” which is checked exception hence compulsory we should handle it by try-catch or throws. Otherwise we will get compile time exception saying “unreported exception InterruptedException; must be caught or declared to be throw t.join();”
Example:

Output:

Example with join(): “main” thread will wait until child thread “t” complete its execution as “main” thread calling t.join().


Output:

Example without using Thread.join(): output will be in any order

Output:

You may be interested
Thread.yeild()
Thread Priority
Thread.sleep()

Help others by sharing the content!

Thread.sleep() method

Thread.sleep() method of Thread class is used to sleep a thread for specific time period.

Syntax:

sleep() method of Thread class is static and does not return anything. We must provide a argument milliseconds otherwise we will get compiler time error.
By passing argument millisecond thread will sleep for that time.

Example to demonstrate sleep() method:

Output: we get output in time laps of 2 sec.

sleep() throws “InterruptedException” which is checked exception hence compulsory we should handle it by try-catch or throws. Otherwise we will get compile time exception saying “unreported exception InterruptedException; must be caught or declared to be throw”

Example to demonstrate sleep() method throws “InterruptedException”:

At compiling we will get below exception:

You may be interested
Thread.yeild()
Thread Priority
Thread.join()

Help others by sharing the content!

Core Java-Most asked interview questions

So in this post we are going to add all interview asked questions on java.
These questions asked for 2 years of experience person.
All below questions are based on Core Java.
We are also providing answers.

Interview questions on Multithreading in java

  • How we can define a Thread in java?
  • Thread can define in two ways in java. By extending a Thread class and by implementing a Runnable interface.

  • Which one Runnable/Thread is recommended to use while defining a Thread.
  • It is recommended to use Runnable interface while defining a Thread in java. Because we can extend other classes also. In java we can extend only one class at a time. So if we extend Thread class we can can’t extend other classes. But if we implement Runnable interface we can extend other classes also. That’s why recommended to implement Runnable interface.

  • Difference between start() and run() in Java?
  • Thread.start() creates new thread which is responsible for the execution of run() method. Thread.start() is also responsible to register a thread with thread scheduler.
    Thread.run() method won’t create new thread and just act as normal method.

  • Importance of Thread.start()?
  • In java, there is no other way to start a new thread. Only Thread.start() creates new thread which is responsible for the execution of run() method. Thread.start() is also responsible to register a thread with thread scheduler. That’s why, Thread.start() is consider as Heart of Multi-threading.

  • Can we Overload a run()? / Overloading run().
  • Yes, we can overload a Thread.run() method in our class. But Thread.start() always call no-argument run() method only. So if you want to call overloaded method, you have to call it explicitly.

    Output:

  • Can we Override a run()? / Overriding run().
  • Yes, we must override a run() method if we want to use multi-threading. If we don’t override a run(), then start() call Thread.run() which has empty implementation. so will not get any output.

    Output:No output

  • Can we Override a start()? / Overriding Thread.start().
  • If we override a Thread.start() method, it will not create a new thread. It will act as normal method.

    Output:

  • Can we restart Thread?
  • No, we can’t restart a Thread again. If we try to restart a thread then we will get a runtime exception “IllegalThreadStateException”.

    Output:

  • Can we get and set name of a Thread?
  • We can get and set name of thread by using following two methods of Thread class.

    • public final string getName()
    • public final void setName(String name)

    currentThread().getName():- Method to get name of current thread.
    currentThread().setName():- Method to set name of a thread.

    We can change name if “main” thread also.
    eg:

    Every thread in java have some name provided by JVM as Thread-0,Thread-1……Thread-n.
    eg:

    We can change name of current thread as follow. We also can change name of “main” thread.
    eg:

Interview question on String in java

  • What is immutable. Examples of immutable class other than String
Help others by sharing the content!

get and set name of a current thread

We can get and set name of thread by using following two methods of Thread class.

  • public final string getName()
  • public final void setName(String name)

currentThread().getName()

Method to get name of current thread.
Every thread in java have some name provided by JVM as Thread-0,Thread-1……Thread-n.

Syntax:

Example to get a name of current thread

Output

currentThread().setName()

Method to set name of a thread. We can change name of current thread as follow. We also can change name of “main” thread.

Syntax:

Example to change name of current thread

Output

Help others by sharing the content!

Restarting a thread in java

No, we can’t restart a Thread again. If we try to restart a thread then we will get a runtime exception “IllegalThreadStateException”.

Output:

Help others by sharing the content!