Saturday, October 31, 2009

ways of creating Threads in Java Program

Multi threaded applications are the base of all modern computing applications.Threads save lot of time and keeps utilizing computing resources to the optimum levels.It is important for a Java developer to understand how to create Threads.
There are two ways by which you can create Threads:-

1.By extending Thread class
2.By implementing Runnable Interface

Creating Threads by extending Thread class

The java.lang.Thread class is used to construct and access individual threads in a multi threaded application.Thread class supports many methods that obtain information about the activities of a Thread,set and check properties of a Thread and cause a Thread to wait,be interrupted or be destroyed.Extending the Thread class enables your class to run in a separate new call stack.Just like the main Thread.

Example:-

class MThread extends Thread{

// code goes here

}

Creating Threads by Implementing Runnable Interface

Extending Thread class for creating Threads is no doubt a bad OO Practice because since Java doesn't support multiple Inheritance,if you extend one class and also need to incorporate features of Other class then what you are supposed to do?
Let us Consider a scenario where we want to create an Applet which has some Thread capabilities,now if you extend Thread then from where applet methods come from and if you extend Applet class then from where the Thread capabilities come from.This is the reason why the Java creators decided to give some extra flexibility by providing us with Runnable Interface which consists of only a single method called run().All the Thread related code goes inside run() method and Thread run() method is invoked when we call start() method on Thread object.This run() method starts a new call stack in this case but it has to be invoked to get things working.

Example:-

class MThread implements Runnable{

public void run(){
//Thread stuff goes here
}

}

NOTE:-Consider the context of Applet and Thread scenario ,when you use Runnable interface,the Thread becomes a part of the Applet and grants full access to its data members and methods.The subclass of Thread is limited to access the public components of any class.Therefore ,when the Thread depends strongly on the components of Applet class use Runnable Interface.Use this concept in general terms not only for Applet context.

Suggested Reading:-

Java Thread Basics

Thread Life Cycle

Read more...

Thursday, October 29, 2009

Thread Life Cycle

A Thread encounters four states during its life time which are:-


1.New Thread(Init)
2.Runnable
3.Waiting/Blocked/Ready
4.Terminated




In order to get to the roots of the threads you have to understand all the states of Threads life cycle.

1.New Thread(Init) :- Whenever an instance of Thread is created it enters the new Thread state.It is not mandatory for you to always extend the Thread class.In order to create a new Thread instance there is also another convenient option which is implementing the Runnable interface.Once a new Thread is created you can start the thread.Consider following example:-

Creating a new Thread

Thread NThread = new Thread(this);
The above expression creates an empty Thread with no resources allocated to it.The NThread can be started by using the start() method on the Thread object.

i.e. NThread.start();

2.Runnable:- When the start() method is invoked,the Thread enters Runnable state.Thread invokes start() method doesn't mean that the Thread will go on to execute straight away.It may begin execution but its not mandatory,it will begin executing when the processor becomes idle.If processor is idle then the Thread will start executing straight away.The processor maintains a queue to know about which Thread is coming next.

NOTE:- Invoking start() method does not guarantee about the execution of the Thread,Thread may begin execution immediately or it may keep you waiting for a long time anything can happen,but the bottom line is "In case of Threads Nothing is Guaranteed" until and unless you make them do guaranteed behaviour.

3.Waiting/Blocked/Ready :- During this state the Threads are remained in a pool .This Thread pool contains Threads which are either blocked by some IO or resource or waiting for their turn.sleep(),wait() and notify() are a few methods which put threads into this state.Once again I will say that the order in which the Threads are waiting does not holds any importance in context to their execution because selection of Thread to execute is totally based on the decision of the underlying OS.That is why nothing is guaranteed in Thread world!!!!


Terminated:- A Thread can be either killed or die naturally .When the thread completes its run() method then it dies naturally,but if you want to kill a Thread the assign null to its object.The best way to check whether the Thread is dead or alive is to use isAlive() method.It returns state dead or alive.

Important:- If a Thread is once dead or terminated then it cannot be restarted.You can also not call the methods of a dead Thread.

NOTE:- " IN THE WORLD OF THREAD NOTHING IS GUARANTEED!!!!!!" but you can assume you will learn the behaviours of Threads.

Suggested Reading:-

Java Thread Basics
Ways of creating Threads

Read more...

Saturday, October 17, 2009

How to Compute Program Execution Time in Java

I don't think you need to compute your program execution time everytime you execute your program but sometimes when you need to compare performance then it becomes necessary to compute the execution time.When you need to compare two programming styles then you may consider calculating the time required by each program program to complete the task ,lesser the time the more fast the program is.The fact is since the processors are too fast now days and due to even faster RAM's the million of loops complete within split of a second.So there is need to calculate speed till the precision of 1000th of a second.Here in order to compute the time we will use the currentTimeMillis() method of System class which returns current time of your computer system.There is a very simple logic which is implemented to create this utility.

In the following example we will compute the program execution time of main() method.As we enter the main() method we will compute the system time and after implementation of programming logic or business logic we will again compute the system time.Remember the system time is returned as long in milliseconds.So now you have two values first when we started our main() method and second just before exiting the main.We assume here is that the program exits immediately after getting second value.

Source code and Example:-

// Method to be used System.currentTimeMillis()
//This method returns long values.

class timecalc
{
public static void main(String a[]){
long time = System.currentTimeMillis();
System.out.println(time);
for(int i=0;i<5000000;i++)
{
for(int j=0;j<1000;j++);
}
long end = System.currentTimeMillis();
System.out.println(end-time);
}
}

Output :-
3782
Remember the output may vary according to your computers speed.speed is affected by various factors like RAM,processor speed,running programs,cache etc.

Here in above example I have taken such long loop because just to calculate the time difference and to just give you a demo how things goes.When you compute for several hundreds of values then it is possible that it might return 0.Everytime your run your program and you are expected to get a different value.

Suggested Reading :-

Compute any day and date in calendar
Get date and time in your specified format
How to execute system programs from your programs?
Most common scoping errors commited by Novice programmers

Read more...

Thursday, October 15, 2009

Core Java Very basic Questions || Important Core Java Questions

Java programming language is very vast programming language,even I must say each and every programming language is very vast.Understanding Java programming language and applying its concept needs the knowledge and skills of Java programming language.I have gone through various important questions during my ride to SCJP.So I have prepared a list of such important questions of Java programming language which will help you not only in understanding the topic but also If you are preparing for SCJP they will be helpful.

Try to answer these questions on your own but if you cannot recall the concept go refer book,any core Java book will do.

Important Core Java Questions :-

1.How many access modifiers a class can use and which are they?
2.What are the Instance variables?
3.What are local variables?
4.What is the default access modifier and how it is different from protected access modifier?
5.Can you ever mark a class as final?
6.Is it true that we can use abstract and final both on same time and same Java entity?
7.What is the IS-A and HAS-A relationship in Java?
8.What is multiple inheritance and how you can implement multiple inheritance in Java?
9.What is the size of compiler generated Java Bytecode?
10.Does Interfaces follow the Inheritance?
11.A subclass can inherit the private member of superclass is this statement true,give reason?
12.What is the bit depth of Boolean variable in Java?
13.What will happen if finally block itself generates an Exception?
14.What is exception propagation?
15.How Inheritance is affected by object serialization?

These are a few questions which I thought as Important.Further there are some references I am giving in order to solve these questions.

Suggested Reading:-

Exception Propagation
IS-A and HAS-A relationship
Interfaces rules and Explanations
Why Java classes are not marked final

Read more...

Tuesday, October 13, 2009

How to executing System programs from your Java programs and applications

Java is capable of executing threads by starting and running them.Java Programming language also provides you with the ability to start the heavyweight system processes.Threads are lightweight processes and can be called as a subprocess.Executing or starting a System process is completely different than executing a thread.

Java.lang provides a method exec() which is used to name and run the process.The exec() method returns a process object and is invoked on Runtime instance.Runtime is an abstract class whcih can be instantiated as following:-

Runtime rt = Runtime.getRuntime();

While you write and use exec() in your programs do remember that exce() method throws an IOException which needs to be handled as it is a checked Exception.Make sure to write the exec() inside a try/catch block which can handle an IOException.

The process object which is used to get the value from exec() can be used to control how your Java program interacts with the running process.
The exec() method is an environment dependent method so do make sure to write OS specific process names as arguments to exec().The argumemnts passed must be system recognizable commands.

Here the following example shows how the Window's notepad is launched through the Java program.Notepad is a simple text editor of windows.The example uses exec() method to invoke the notepad process.

class LaunchNotepad{
public static void main(String a[]){
Runtime rt = Runtime.getRuntime();
Process p =null;
try{
p=rt.exec("notepad");
}catch(Exception e)
{System.out.println("Error in Starting Notepad");}
}
}

Now you system is up and running the notepad process.Similarly you can invoke any process you like through you Java Application what you have to know is the system call which will be passed as argument in the exec() method.

Related posts :-

Java Thread Basics
Memory Management in Java
Compute any day in calendar

Read more...

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP