Pages

Monday, September 24, 2012

Abstract Class and Interfaces


What are the differences between Interface and Abstract class?
Abstract Class :

  • An abstract class can provide complete, default code and/or just the details that have to be overridden.
  • In case of abstract class, a class may extend only one abstract class.
  • An abstract class can have non-abstract methods.
  • An abstract class can have instance variables.
  • An abstract class can have any visibility: public, private, protected.
  • If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.An abstract class can contain constructors .
  • An abstract class can contain constructors .
  • Abstract classes are fast.


Interface :

  • An interface cannot provide any code at all,just the signature
  • A Class may implement several interfaces.
  • All methods of an Interface are abstract.
  • An Interface cannot have instance variables.
  • An Interface visibility must be public (or) none.
  • If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
  • An Interface cannot contain constructors .
  • Interfaces are slow as it requires extra indirection to find corresponding method in the actual class.



When should I use abstract classes and when should I use interfaces?


Use Interfaces when…
  • You see that something in your design will change frequently.
  • If various implementations only share method signatures then it is better to use Interfaces.
  • you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.
Use Abstract Class when…
  • If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
  • When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.
  • Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies

Thread States



Thread States :

New: This is the state the thread is in after the Thread instance has been created, but the start() method has not been invoked on the thread. It is a live Thread object, but not yet a thread of execution. At this point, the thread is considered not alive

Runnable: This is the state a thread is in when it's eligible to run, but the scheduler has not selected it to be the running thread. A thread first enters the runnable state when the start() method is invoked, but a thread can also return to the runnable state after either running or coming back from a blocked, waiting, or sleeping state. When the thread is in the runnable state,it is considered alive.

Running: This is it. The "big time." Where the action is. This is the state a thread is in when the thread scheduler selects it (from the runnable pool) to be the currently executing process.

Waiting/blocked/sleeping: This is the state a thread is in when it's not eligible to run. Okay, so this is really three states combined into one, but they all have one thing in common: the thread is still alive, but is currently not eligible to run.
Some methods may look like they tell another thread to block, but they don't. If you have a reference t to another thread, you can write something like this
                            t.sleep(); or t.yield()
But those are actually static methods of the Thread class—they don't affect the instance t; instead they are defined to always affect the thread that's currently executing.

Dead: A thread is considered dead when its run() method completes. It may still be a viable Thread object, but it is no longer a separate thread of execution. Once a thread is dead, it can never be brought back to life! If you invoke start() on a dead Thread
instance, you'll get a runtime (not compiler) exception. 

Running Mulitple Threads


Running Multiple Threads :

Just because a series of threads are started in a particular order doesn't mean they'll run in that order. For any group of started
threads, order is not guaranteed by the scheduler. And duration is not guaranteed. You don't know, for example, if one thread will run to completion before the others have a chance to get in or whether they'll all take turns nicely, or whether they'll do a combination of both.

There is a way, however, to start a thread but tell it not to
run until some other thread has finished. You can do this with the join() method,

Once a thread has been started, it can never be started again. If you have a reference to a Thread, and you call start(), it's started. If you call start() a second time, it will cause an exception (an IllegalThreadStateException, which is a kind of RuntimeException.

Methods influencing scheduler :


               Methods from the java.lang.Thread Class Some of the methods that can help us influence thread scheduling are as follows:

public static void sleep(long millis) throws InterruptedException
public static void yield()
public final void join() throws InterruptedException
public final void setPriority(int newPriority)


Methods from the java.lang.Object Class Every class in Java inherits the following three thread-related methods:

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

Starting Threads


Starting a Thread : 
Thread t = new Thread();
t.start() : 

what happens after you call start()?
The good stuff:
¦ A new thread of execution starts (with a new call stack).
¦ The thread moves from the new state to the runnable state.
¦ When the thread gets a chance to execute, its target run() method will run.

There’s nothing special about the run() method as far as Java is
concerned. Like main(), it just happens to be the name (and signature) of the method that the new thread knows to invoke. So if you see code that calls the run() method on a Runnable (or even on a Thread instance), that’s perfectly legal. But it doesn’t mean the
run() method will run in a separate thread! Calling a run() method directly just means you’re invoking a method from whatever thread is currently executing, and the run() method goes onto the current call stack rather than at the beginning of a new call stack.

The following code does not start a new thread of execution:
      Thread t = new Thread();
      t.run(); // Legal, but does not start a new thread


Running this code produces the following, extra special, output:
% java NameThread
NameRunnable running
Run by Fred

To get the name of a thread you call—who would have guessed—getName() on the Thread instance. But the target Runnable instance doesn't even have a reference to the Thread instance, so we first invoked the static Thread.currentThread() method, which returns a reference to the currently executing thread, and then we invoked getName() on that returned reference.

Defining and instantiating Threads


Define and instantiate a thread in one of two ways:

¦ Extend the java.lang.Thread class.
¦ Implement the Runnable interface.

Extending java.lang.Thread
The simplest way to define code to run in a separate thread is to 
¦ Extend the java.lang.Thread class.
¦ Override the run() method.

Keep in mind that you're free to overload the run() method in your Thread
subclass:
But know this: The overloaded run(String s) method will be ignored by the Thread class unless you call it yourself. The Thread class expects a run() method with no arguments, and it will execute this method for you in a separate call stack after the thread has been started. With a run(String s) method, the Thread gisclass won't call the method for you, and even if you call the method directly yourself, execution won't happen in a new thread of execution with a separate call stack. It will just happen in the same call stack as the code that you made the call from, just like any other normal method call.

Instantiating a Thread:
                                  
                       MyThread t = new MyThread();
If you implement Runnable, instantiation is only slightly less simple. To have code run by a separate thread, you still need a Thread instance. But rather than combining both the thread and the job (the code in the run()method) into one class, you've split it into two classes—the Thread class for the thread-specific code
and your Runnable implementation class for your job-that-should-be-run-by-athread code. (Another common way to think about this is that the Thread is the "worker," and the Runnable is the "job" to be done.)
First, you instantiate your Runnable class:
                      MyRunnable r = new MyRunnable();
Next, you get yourself an instance of java.lang.Thread (somebody has to run your job…), and you give it your job                        Thread t = new Thread(r); // Pass your Runnable to the Thread

The Thread class itself implements Runnable. (After all, it has a run() method that we were overriding.) This means that you could pass a Thread to another Thread’s constructor:
                Thread t = new Thread(new MyThread());
This is a bit silly, but it’s legal. In this case, you really just need a Runnnable, and creating a whole other Thread is overkill.

When a thread has been instantiated but not started (in other words, the start() method has not been invoked on the Thread instance), the thread is said to be in the new state. At this stage, the thread is not yet considered to be alive. Once the start() method is called, the thread is considered to be alive (even though the run() method may not have actually started executing yet). A thread is considered dead (no longer alive) after the run() method completes. The isAlive() method is the best way to determine if a thread has been started but has not yet completed its run() method.

Sunday, September 23, 2012

Introduction to Threads

In a single-threaded runtime environment, actions execute one after another. The next action can happen only when the previous one is finished.

In Java, “thread” means two different things:

¦ An instance of class java.lang.Thread
¦ A thread of execution
              An instance of Thread is just…an object. Like any other object in Java, it has variables and methods, and lives and dies on the heap. But a thread of execution is an individual process (a “lightweight” process) that has its own call stack. In Java,there is one thread per call stack—or, to think of it in reverse, one call stack per thread. The new call stack if we create will run concurrently.
             You might find it confusing that we’re talking about code running concurrently—as if in parallel—given that there’s only one CPU on most of the machines running Java. What gives? The JVM, which gets its turn at the CPU by whatever scheduling mechanism the underlying OS uses, operates like a mini-OS and schedules its own threads regardless of the underlying operating system.
            The difference between the two types of threads (user and daemon) is that the JVM exits an application only when all user threads are complete—the JVM doesn’t care about letting daemon threads complete, so once all user threads are complete, the JVM will shut down, regardless of the state of any daemon threads.