Search

Showing posts with label Multithreading. Show all posts
Showing posts with label Multithreading. Show all posts

Friday, April 16, 2010

is locking possible on primitive type or on static variable

No , Only object level locking is supported in JAVA . so locks are possible only on Objects .

i.e Synchronized works with the object and methods only.

What methods are responsible for inter thread communication

Following Three Methods are responsible for inter thread communication :

1. wait()
2. notify()
3. notifyAll()

These methods are part of Object class. And should always called within Synchronized block .

Let us understand from following example : 

class Operator extends Thread {
public void run(){
while(true){
// Get shape from user
synchronized(this){ // lock the same object
// Calculate new machine steps from shape // finish the work
notify(); // notify the waiting thread i.e Machine thread
}
}
}
}
class Machine extends Thread {
Operator operator; // assume this gets initialized
public void run(){
while(true){
synchronized(operator){ // lock on the operator object
try {
operator.wait(); // waiting for notification from operator object , once notify will call
} catch(InterruptedException ie) {}
// Send machine steps to hardware
}
}
}
}
The machine thread, once started, will immediately go into the waiting state and
will wait patiently until the operator sends the first notification.

Note : When the wait() method is invoked on an object, the thread executing
that code gives up its lock on the object immediately. However, when
notify() is called, that doesn’t mean the thread gives up its lock at that
moment. If the thread is still completing synchronized code, the lock is not
released until the thread moves out of synchronized code. So just because
notify() is called doesn’t mean the lock becomes available at that moment.

What is Daemon Thread ? What is the use of deamon thread?

Daemon term is mainly used in UNIX. In Java, this is used to indicate a special type of thread. Normally when a thread is created in Java, by default it is a non-daemon thread. Whenever a Java Program is executed, the Java Virtual Machine (JVM) will not exit until any non-daemon threads are still running. This means if the main thread of an application ends and the remaining threads left are Daemon threads, then the JVM will exit killing all the daemon threads without warning.
A daemon thread should be used for some background task that might provide a service to the applications. e.g. a Server thread listening on a port for the clients` requests. A thread for which an exit method is not provided or which does not have an exit mechanism can be marked as a daemon thread.