Sunday, April 7, 2013

Multitasking

Before learning about multithreading, we should know what necessitated multithreading for that. we need to know about multithreading.

Considering the following program.

Class MSD
{
fun1()  fun2() fun3()
{
----
}
public static void main(String args[])
{
MSD s1 = new MSD();
S1.fun1();
S1.fun2();
S3.fun3();
}
}

Normally, if the class is compiled and JVM executes the program, then the order of executing is that, first fun1() is called and ofter complete execution of fun1(), then control comes back to main() and then fun2() is called.After complete execution of fun2(), then fun3() is called and executed this is 

how the flow goes on.

Now, let us assume that fun1() has some statements which involve data transfer.

We know that data trandfer is not the job of the processor.

It is the duty of a separate individual circuit (DMA) which functions under the control of the processor.

Since fun1() has data transfer statements, processor assign that job to DMA. During this the processor should runtime idle.

The state of CPU where CPU waits for DMA circuit to transfer the data is known as Idle state.

This made software developers to think that, efficiency of the processor would be increased if processor is made to do some other useful work during this idle state. The useful work is nothing but, executing other functions present in the program.

This need led to the concepts of multitasking.

Remember that processor is also an electrical circuit and at any instant of time, it can execute only one statement. It can not execute multiple statements simultaneously.

Multitasking : The concept of executing multiple functionalities simultaneously is known as multitasking.

If we apply the concept of multitasking to our program, then control flow would be as follows.

A part of fun1() will be executed and then control switches to func2(). Now, here also, a part of fun2() is executed and then control again comes back to fun1(). Now it contains executing fun1() from where it had stopped earlier. Similarly, for fun2() and fun3(). This is not guaranteed. The sequence may change)

Now when we see the output, we feel that the processor is executing the three functionalities simultaneously avoid the Idle States of CPU.

In multitasking we said that, a part of a functionality is executed one at a time. Now, the question is ‘part’ means how many statements.

This conflict is resolved by Scheduling.

Scheduling:  It is the process in which a specific time period is allocated to a functionality where the control remains in that particular functionality for that specific time period.

Once the time period is lapsed, control switches to another functionality with another time slice so on.

Scheduling is supervised by the scheduler.

The time slices allocated will be in the order off nano seconds.

Thus, by the time our eye recognizes the execution of one part, control switches to another part of the program.

Now, it is clear that, without applying multitasking,one function will depend upon another function. i.e: after execution of fun1(), fun2() will be executed and so on.

Advantages of multitasking:

i)                    Multitasking was invented to avoid Idle states of CPU.
ii)                   Butt interestingly, it is used to make the functions get executed independently.

Note : Actually, in realtime we use multitasking to make the most of the second advantage rather than the first, because in case of small projects, idle state of CPU is not a big concern.

Animation along with from submission is a very good example of multitasking.
Multitasking is two types

i)                     Thread based multitasking

ii)                   Process based multitasking

Java supports aonly thread based multitasking.

Process based multitasking:

Concept of executing more than program simultaneously which are presents in different locations of RAM is known as process based multitasking.

Thread based multitasking:

Concept of executing more than one functionality simultaneously belonging to the same memory(i.e same program) is known as thread based multitasking.

Thread : Thread is a functionality (group of statements) which would be getting executed simultaneously with the other part of the program.

Interview Q: What is the difference between a process and a thread?

Process is any program under execution thread is a part of the process.

In other words, thread is the smallest part of a process.




Exception Handling

Exceptions are objects created by JVM that represent the corresponding logical errors.

Syntax errors: Syntax errors occur whenever a statement written by the programmer cannot be compiled by the compiler.

Whenever a source code is compiled, first compiler checks whether a proper environment is available for the JVM or not to execute the byte code which it has generated for the source code.
Thus, Syntax errors and improper environment result in compilation errors.

Logical Errors: Sometimes, JVM would be unable to execute statement(s) in the byte code for some reasons. This results in logical errors.

Note  : Whenever a logical errors, program is terminated and control comes out of the program unconditionally without mentioning from which part of the program it has come out.

Ex: Class A
{
Public static void main(String args[])
{
int i =100;
int j = 0;
int x= i/j;
system.out.println(x);
}
}

-          The above program will be perfectly compiled. But, while executing it, value of x becomes “infinity” and size x is of type integer(32 bit) JVM would not understand how to store infinity value in 32 bit location.

-          Thus are some predefined classes in java.lang.package whose objects are created by JVM whenever it encounters a logical error. (Names of such classes are found under the exception classes in API).

-          For each and every logical error, there is a corresponding exception class in the java.lang.package.

-          Whenever JVM encounters a logical error, it creates an object of the corresponding exception class and since this object is not explicitly handled, this object reaches back to the JVM. JVM(a set of programs) accepts these objects and terminates the program.

-          Now, if we are able to handle those exception class objects, we can prevent the program from getting terminated.

-          Thus, concept of handling the exception class object and avoiding them from reaching back to the JVM known as Exception Handling.

-          We can handle the exception class objects by assigning them to the corresponding exception class refrences.

Procedure of handling the exceptions:

-          We have two key words ‘try’ & ‘catch’ to implement exception handling.

-          The ‘try’ keyword recognizes the exception class object created by the JVM and it gets hold of these objects and transfers them to the “catch” block.

-          In the “catch” block we should be able to assign those objects to the appropriate refrences so that they will not reach JVM and therefore program would not be terminated.

Ex:
------
function1()
{
try{
---
}
catch(Exception e1)
{
system.out.println(“Exception in fun1()”);
system.out.println(e1);
}
---
}

-          Thus, as soon as an exception is raised the user would easily know in which part of the program the logical error has occurred.

-          system.out.println(e1) prints some message instead of printing the address contained in e1.This is because the exception class overrides the tostring method of the object class.

-          In this way, we can use try and catch blocks in any part of the program.

Uses of Exception Handling:

-          We can know in which part of the program the logical error has actually occurred.

-          We are not allowing the JVM to terminate the entire program. Only the ‘try’ block in which the error has accrued would be terminated.

-          Thus, this is an easy way of debugging the program.
Note :  
 i) Once control centres the catch block. It executes the statements in the catch block and moves on further. It will not come back to the ‘try’ blocks because of which the ‘catch’ block was executed.

ii) If no exception class object is created in the ‘try’ block, control will never enter the catch block.

iii) Every ‘try’ block should be associated with at least one ‘catch’ block.

iv) A ‘try’ block can have any no .of ‘catch’ blocks.

Interview Q. Can we define a try block without a catch block?

Ans) Yes, but that procedure is not recommended.

We have altogether five keywords in the concept of exceptions. They are
i)                    try
ii)                   catch
iii)                 throw
iv)                 throws
v)                  finally

Logically errors are of two types.
i)                    Simple logical error
ii)                   Serious logical errors

Simple logical errors: There are some logical errors which can be neglected by the JVM.such errors are known as simple logical errors.

Ex: int x = 100/0; etc...

Serious logical errors : Some logical errors cannot be neglected by the JVM. Such errors are known as serious logical errors.

Ex: Creation of an object of a class. When these is no availability of memory space in the Ram.
All the classes coming under ‘exceptions’ are defined to represent ‘simple logical errors’.
All the classes coming under ‘errors’ are defined to represent ‘serious logical errors’.


Wednesday, April 3, 2013

Interfaces


In our previous  post we have discussed about the Late Binding and Early  Binding now we will discuss about how to implement Late Binding

-          We implement Late Binding through interfaces in Java. Classes is like a structure and it can be called is a fully implemented structure (providing bodies for every definition).

       -        Interfaces is a fully unimplemented structure 

i.e:  No function definition has a body inside an interface. The function will not have at least Zero body.

      -       Just as we define classes using the keyword ‘class’ we define interfaces using the keyword ‘interfaces’                                 

EX:  interfaces xyz
{
Public void funx();
Public void funy();
}

Note: Every definition inside an interface should be public.

Interview Q) 

When we compile xyz.java we get .class file even though the function funx(),funy() have no body.why and how?

Ans)  There are three types of structures in java , as given below.

i)                    Fully implemented structure                                              ---   class

ii)                   Fully un implemented structure                                        ---    Interfaces

iii)                 Partially implemented / unimplemented  structure    ---   Abstract class

The job of the java compiler is to convert any valid java structure(source code) into its equivalent  byte code.

The above example xyz.java, it’s a valid java structure. Hence it got compiled and xyz.class file was produced.

-          As we can extend one class to another class, we can implement an interface  to a class the keyword ‘implements’.

-          We should keep in mind that whenever we implement an interface to a class. we have to provide bodies for the definitions presents in the interfaces,inside the class that is implementing the interfaces.

-          References can be defined for any valid java structure but the corresponding object can be created only for classes, In other words, “we can define references in java for everything which can be represented in the form of a .class file, but the corresponding objects can be created only for classes.”

Ex:
Class A implements xyz
{
Public void functionx()
{
// Defining bodies inside the class for the definition inside the interface, where class implements the interface
}
Public void function()
{
// Defining bodies inside the class for the definition inside the interface, where class implements the interface

}
Public static void main(String args[])
{
Xyz x1 = null; // we can assign null to the reference of an interface
Xyz x2 = new xyz(); // completion error : new operator cannot be used with interfaces
A a1= new A();
a1.functionx();
a2.functiony();

Interview Q

In the above program, we can even directly define function() and function() inside Class A and call them by creating abject of class A then ,what is the use of implements ‘keyword’?

Ans:

Using ‘implement’ keyword, we can achieve ‘Late Binding’.

Differences between ‘extends’ and ‘implements’

-          Using ‘extends’ keyword we get properties of one structure to another structure.
-          Using ‘implements’ keyword we provide bodies for function definitions inside a structure(interface).
-          In side simple terms, extends means getting and implemts means giving.
-          Therefore functionality of ‘implements’ is quite opposite to that of extends.
-          Here, ‘implements’ is qgainst ‘inheritance.
A more general example as follows
Father -> son àchild1,child2,child3
Father is super class ,son is a sub class, child 1,2,3 are integers.
Son has to extend from father and can implement to all children.
This is the reason , why ,we can extend only one class but can implement any no. of interfaces.


          

Late Binding vs Early Binding



Late Binding:

The concept of binding the function body to the function definition during runtime is know as late binding.

Late Binding :

If the function body is binded with the function definition at the compilation time,then it is known as early binding.

Note: We cannot define a function in a class without body. It should have at least Zero body.

Differences between Late Binding and Dynamic Polymorphism

In dynamic polymorphisim the function to be executed is decided at run time but note that by the time of compliation the function has a body.

But, in late binding, the body of the function itself is going to get associated with the function definition during run time.

Note: 

Late binding is highly dynamic than anything else in java.

 In post we learn how to implement late binding .