Thursday, July 17, 2008

JAVA-MULTI THREADING

MULTI-THREADED PROGRAMMING

1) What is the difference between process and thread?

Process is a program in execution whereas thread is a separate path of execution in a program.

2) What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?

Multithreading is the mechanism in which more than one thread run independent of each other within the process.

wait (), notify () and notifyAll () methods can be used for inter-thread communication and these methods are in Object class.

wait( ) : When a thread executes a call to wait( ) method, it surrenders the object lock and enters into a waiting state.

notify( ) or notifyAll( ) : To remove a thread from the waiting state, some other thread must make a call to notify( ) or notifyAll( ) method on the same object.

3) What is the class and interface in java to create thread and which is the most advantageous method?

Thread class and Runnable interface can be used to create threads and using Runnable interface is the most advantageous method to create threads because we need not extend thread class here.

4) What are the states associated in the thread?

Thread contains ready, running, waiting and dead states.

5) What is synchronization?

Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time.

6) When you will synchronize a piece of your code?

When you expect different threads will access your code and these threads may change a particular data causing data corruption.

7) What is deadlock?

When two threads are waiting each other and can't precede the program is said to be deadlock.

8) What are daemon thread and which method is used to create the daemon thread?

Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.

9). What are the disadvantages of using threads?

DeadLock

10).What are mutex and semaphore? What is the difference between them?

A mutex is a synchronization object that allows only one process or thread to access a critical code block. A semaphore on the other hand allows one or more processes or threads to access a critical code block. A semaphore is a multiple mutex.

11). Describe synchronization in respect to multithreading.?

With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

12) What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class.

Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

13). What are three ways in which a thread can enter the waiting state?

A thread can enter the waiting state by invoking its sleep () method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait () method. It can also enter the waiting state by invoking its (deprecated) suspend () method.

14). In a lock be acquired on a class?

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

15). What's new with the stop(), suspend() and resume() methods in JDK 1.2?

The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

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

When a thread terminates it’s processing, it enters the dead state.

17). What is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state.

When a task invokes its sleep() method, it returns to the waiting state.

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

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence.

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.

19). Can an anonymous class be declared as implementing an interface and extending a class?

An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

20). What invokes a thread's run () method?

After a thread is started via its start () method or that of the Thread class, the JVM invokes the thread's run () method when the thread is initially executed.

21). What is the purpose of the wait(), notify(), and notifyAll() methods?

The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate each other.

22). What are the high-level thread states?

The high-level thread states are ready, running, waiting, and dead.

23) How does multithreading take place on a computer with a single CPU?

The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

24). What is a thread?

It’s a single sequential stream of execution.

A thread is an independent path of execution in a system.

25). What is runnable?

It’s an Interface through which Java implements Threads. The class can extend from any class but if it implements Runnable, Threads can be used in that particular application.

26). What are the various thread priorities?.

(i) Min-Priority-value(1).

(ii) Normal-Priority-value(5).

(iii)Max-Priority-value(10).

27).What is Inter-Thread communication?.

To exchange information between two threads.

28) What do you understand by Synchronization?
Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value.
Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
// Appropriate method-related code.
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
synchronized (this) {
// Synchronized code here.
}
}

29) What is multi-threading?

Multi-threading means various threads that run in a system.

34) How to create a thread in a program?
You have two ways to do so. First, making your class "extends" Thread class. Second, making your class "implements" Runnable interface. Put jobs in a run() method and call start() method to start the thread.

35) Can Java object be locked down for exclusive use by a given thread?
Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.

36) Can each Java object keep track of all the threads that want to exclusively access to it?
Yes. Use Thread.currentThread() method to track the accessing thread.

37) What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

38) What is the difference between Process and Thread?
A process can contain multiple threads. In most multithreading operating systems, a process gets its own memory address space; a thread doesn't. Threads typically share the heap belonging to their parent process. For instance, a JVM runs in a single process in the host O/S. Threads in the JVM share the heap belonging to that process; that's why several threads may access the same object. Typically, even though they share a common heap, threads have their own stack space. This is how one thread's invocation of a method is kept separate from another's. This is all a gross oversimplification, but it's accurate enough at a high level. Lots of details differ between operating systems. Process vs. Thread A program vs. similar to a sequential program an run on its own vs. Cannot run on its own Unit of allocation vs. Unit of execution Have its own memory space vs. Share with others Each process has one or more threads vs. Each thread belongs to one process Expensive, need to context switch vs. Cheap, can use process memory and may not need to context switch More secure. One process cannot corrupt another process vs. Less secure. A thread can write the memory used by another thread

39)Two methods have key words static synchronized and synchronized separately. What is the difference between them?
Both are synchronized methods. One is instance method, the other is class method. Method with static modifier is a class method. That means the method belongs to class itself and can be accessed directly with class name and is also called Singleton design. The method without static modifier is an instance method. That means the instance method belongs to its object. Every instance of the class gets its own copy of its instance method.
When synchronized is used with a static method, a lock for the entire class is obtained. When synchronized is used with a non-static method, a lock for the particular object (that means instance) of the class is obtained.
Since both methods are synchronized methods, you are not asked to explain what is a synchronized method. You are asked to tell the difference between instance and class method. Of course, your explanation to how synchronized keyword works doesn't hurt. And you may use this opportunity to show your knowledge scope.

40)What's the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

41) Why do threads block on I/O?
Threads block on I/O (that is enters the waiting state) so that other threads may execute while the I/O Operation is performed.

42)When a thread blocks on I/O, what state does it enter?
A thread enters the waiting state when it blocks on I/O.

43)When a thread is created and started, what is its initial state?
A thread is in the ready state after it has been created and started.

44)What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.

45)What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.

46)What is an object's lock and which objects have locks?
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.

47) What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

48) What happens when you invoke a thread's interrupt method while it is sleeping or waiting?
When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.

48)What state is a thread in when it is executing?
An executing thread is in the running state.

49)How can a dead thread be restarted?
A dead thread cannot be restarted.

50)What method must be implemented by all threads?
All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.

51)What are the different identifier states of a Thread?
The different identifiers of a Thread are:
R - Running or runnable thread
S - Suspended thread
CW - Thread waiting on a condition variable
MW - Thread waiting on a monitor lock
MS - Thread suspended waiting on a monitor lock

52)What is the difference between notify() and notifyAll()?
notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when releasing a "writer" lock on a file might permit all "readers" to resume).

53)How is static Synchronization different form non-static synchronization?
When Synchronization is applied on a static Member or a static block, the lock is performed on the Class and not on the Object, while in the case of a Non-static block/member, lock is applied on the Object and not on class. [Trail 2: There is a class called Class in Java whose object is associated with the object(s) of your class. All the static members declared in your class will have reference in this class(Class). As long as your class exists in memory this object of Class is also present. Thats how even if you create multiple objects of your class only one Class object is present and all your objects are linked to this Class object. Even though one of your object is GCed after some time, this object of Class is not GCed untill all the objects associated with it are GCed.
This means that when ever you call a "static synchronized" block, JVM locks access to this Class object and not any of your objects. Your client can till access the non-static members of your objects.

54) Why Thread is faster compare to process?
A thread is never faster than a process. If you run a thread(say there's a process which has spawned only one thread) in one JVM and a process in another and that both of them require same resources then both of them would take same time to execute. But, when a program/Application is thread based(remember here there will be multiple threads running for a single process) then definetly a thread based appliation/program is faster than a process based application. This is because, when ever a process requires or waits for a resource CPU takes it out of the critical section and allocates the mutex to another process.
Before deallocating the ealier one, it stores the context(till what state did it execute that process) in registers. Now if this deallocated process has to come back and execute as it has got the resource for which it was waiting, then it can't go into critical section directly. CPU asks that process to follow scheduling algorithm. So this process has to wait again for its turn. While in the case of thread based application, the application is still with CPU only that thread which requires some resource goes out, but its co threads(of same process/apllication) are still in the critical section. Hence it directly comes back to the CPU and does not wait outside. Hence an application which is thread based is faster than an application which is process based.
Be sure that its not the competion between thread and process, its between an application which is thread based or process based.

55) Explain different way of using thread?
The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritances. The only interface can help.

56) What method must be implemented by all threads?
All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.

57) What is more advisable to create a thread, by implementing a Runnable interface or by extending Thread class?
Strategically speaking, threads created by implementing Runnable interface are more advisable. If you create a thread by extending a thread class, you cannot extend any other class. If you create a thread by implementing Runnable interface, you save a space for your class to extend another class now or in future.

58). Garbage collector thread belongs to which priority?

59). What is the method to find if a thread is active or not?

60) What is the difference between notify() and notifyAll()?
A notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when releasing a "writer" lock on a file might permit all "readers" to resume).

Some basic question

1) What are the two types of multitasking ?
a. Process-based.
b. Thread-based.

2) What is a Thread?
A thread is a single sequential flow of control within a program.

3) What are the two ways to create a new thread?
a.Extend the Thread class and override the run() method.
b.Implement the Runnable interface and implement the run() method.

4) If you have ABC class that must subclass XYZ class, which option will you use to create a thread?
I will make ABC implement the Runnable interface to create a new thread, because ABC class will not be able to extend both XYZ class and Thread class.

5) Which package contains Thread class and Runnable Interface?
java.lang package

6) What is the signature of the run() mehod in the Thread class?
public void run()

7) Which methods calls the run() method?
start() method.

8) Which interface does the Thread class implement?
Runnable interface

9) What are the states of a Thread ?
Ready,Running,Waiting and Dead.

10) Where does the support for threading lie?
The thread support lies in java.lang.Thread, java.lang.Object and JVM.

11) In which class would you find the methods sleep() and yield()?
Thread class

12) In which class would you find the methods notify(),notifyAll() and wait()?
Object class

13) What will notify() method do?
notify() method moves a thread out of the waiting pool to ready state, but there is no guaranty which thread will be moved out of the pool.


14) Can you notify a particular thread?
No.

15) What is the difference between sleep() and yield()?
When a Thread calls the sleep() method, it will return to its waiting state. When a Thread calls the yield() method, it returns to the ready state.

16) What is a Daemon Thread?
Daemon is a low priority thread which runs in the backgrouund.

17) How to make a normal thread as daemon thread?
We should call setDaemon(true) method on the thread object to make a thread as daemon thread.

18) What is the difference between normal thread and daemon thread?
Normal threads do mainstream activity, whereas daemon threads are used low priority work. Hence daemon threads are also stopped when there are no normal threads.

19) Give one good example of a daemon thread?
Garbage Collector is a low priority daemon thread.

20) What does the start() method of Thread do?
The thread's start() method puts the thread in ready state and makes the thread eligible to run. start() method automatically calls the run () method.

21) What are the two ways that a code can be synchronised?
a. Method can be declared as synchronised.
b. A block of code be sychronised.

22) Can you declare a static method as synchronized?
Yes, we can declare static method as synchronized. But the calling thread should acquire lock on the class that owns the method.

23) Can a thread execute another objects run() method?
A thread can execute it's own run() method or another objects run() method.

24) What is the default priority of a Thread?
NORM_PRIORITY

25) What is a deadlock?
A condition that occurs when two processes are waiting for each other to complete before proceeding. The result is that both processes wait endlessly.

26) What are all the methods used for Inter Thread communication and what is the class in which these methods are defined?
a. wait(),notify() & notifyall()
b. Object class

27) What is the mechanisam defind in java for a code segment be used by only one Thread at a time?
Synchronisation

28) What is the procedure to own the moniter by many threads?
Its not possible. A monitor can be held by only one thread at a time.

29) What is the unit for 500 in the statement, obj.sleep(500);?
500 is the no of milliseconds and the data type is long.

30) What are the values of the following thread priority constants?
MAX_PRIORITY,MIN_PRIORITY and NORMAL_PRIORITY
10,1,5

31) What is the default thread at the time of starting a java application?
main thread

32) The word synchronized can be used with only a method. True/ False?
False. A block of code can also be synchronised.

33) What is a Monitor?
A monitor is an object which contains some synchronized code in it.

34) What are all the methods defined in the Runnable Interface?
only run() method is defined the Runnable interface.

35) How can i start a dead thread?
A dead Thread cannot be started again.

36) When does a Thread die?
A Thread dies after completion of run() method.

37) What does the yield() method do?
The yield() method puts currently running thread in to ready state.

38) What exception does the wait() method throw?
The java.lang.Object class wait() method throws "InterruptedException".

39) What does notifyAll() method do?
notifyAll() method moves all waiting threads from the waiting pool to ready state.

40) What does wait() method do?
wait() method releases CPU, releases objects lock, the thread enters into pool of waiting threads.

41) What is semaphore?


42) Can you explain how Scheduling and Priority works in threads?

1 comment:

sri said...

i can see only collections.what about the others