Java - Interview Questions and Answers on Scheduling

Q1.  Why threads block or enters to waiting state on I/O?

Ans. Threads enters to waiting state or block on I/O because other threads can execute while the I/O operations are performed.

Q2.  What is the difference between yield() and sleep()?

Ans. When a object invokes yield() it returns to ready state. But when an object invokes sleep() method enters to not ready state.

Q3.  What is the difference between time slicing and preemptive scheduling ?

Ans. In preemptive scheduling, highest priority task continues execution till it enters a not running state or a higher priority task comes into existence. In time slicing, the task continues its execution for a predefined period of time and reenters the pool of ready tasks.

Q4.  Can a lock be acquired on a class ?

Ans. Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

Q5.  What state does a thread enter when it terminates its processing?

Ans. When a thread terminates its processing, it enters the dead state.

Q6.  What is an object's lock and which object's have locks?

Ans. An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

Q7.  Explain Thread States ?

Ans. Runnable - waiting for its turn to be picked for execution by the thread schedular based on thread priorities.

Running - The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn. 

Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.

Sleeping - Java threads are forcibly put to sleep (suspended) with Thread.sleep. they can resume using Thread.resume method.

Blocked on I/O - Will move to runnable after I/O condition like reading bytes of data etc changes.

Blocked on synchronization - Will move to Runnable when a lock is acquired.

Dead - The thread is finished working.

Q8.  Difference between yield() and sleeping()? 

Ans. When a task invokes yield(), it changes from running state to runnable state. When a task invokes sleep(), it changes from running state to waiting/sleeping state.