Sie sind auf Seite 1von 24

Java is born with some unique and interesting features that made it most powerful and demanded language

of the times. Following are the features of Java. a) Platform-Independent "Java compiled file known as .class file can be executed on any OS without bothering on which platform (OS) the source code was compiled". That is, a Java source file can be compiled on any OS and executed on the same or any other OS. This is quiet contradictory to other languages like C/C++ where these languages should be executed on the same OS where they were compiled earlier. This Java feature is very unique and is unparalled by any other language from the day Java came into its existence, the year 1995; a period of 16 years. Java's Magic Touch Bytecode Bytecode is a new term to the programming world introduced by Java. The compilation product of Java source file is a .class file consisting of bytecode. This bytecode makes Java platform-independent where as the binary code of C/C++ makes C/C++ platformdependent. The bytecode is not an ultimate format that is readily understood by the microprocessor. It must be converted into binary code format that can be processed by the microprocessor directly. This conversion is taken care by the JVM. The format conversion takes some time and thereby Java executes slower. Incase of C/C++, they contain binary code directly. The slow nature is overcome to some extent with the introduction of JIT (Just-In-Time) compiler . Following figure gives the concept.

Java Compiler Is Platform-Independent?

A compiler job is to compile the source code into an executable file. An executable file, as the name indicates, gives output when executed. Every OS comes with its own set of functions and for every OS operation, the OS makes a function call to do the job. The functions may relate to the resource management like file system, memory and thread operations. Every OS comes with its own functions written in proprietory code. The compiler should thoroughly understand these functions. For this reason, the compilers are different for different operating systems. For example, a C/C++ compiler developed for UNIX understands the functions of UNIX but not that of Windows. For the above rule, Java compiler is not an exception. A Java compiler developed and executed on UNIX does not work on Macintosh etc. That is, Java compiler, like any other compiler, is platform-dependent. The difference with Java compiler is it produces a platform-independent executable file known as .class file. Following figure explains.

Note: The .class file is not really an executable file because it must be converted in binary code specific to the OS at execution time. 2. Portable Portability for Java comes from its bytecode. A Java .class file, obtained from the compilation on one platform can be ported or carried, for execution, to a different platform. The necessity is to have a compatible JVM (specific to the platform). JDKs are different for different platforms. 3. Simple and Familiar The main motto of Java designers is to take out the language very simple to practice and develop the code. Many confusing concepts of C++ are simply deleted from Java and right

now Java proved that a language can exist without these concepts. Following list gives a few concepts not supported by Java but supported by other object-oriented languages like C++. 1. No support for pointers. 2. No "goto" keyword. The minus point of "goto" is that you loose the command on control flow of the code and thereby debugging becomes a nightmare. 3. No support for unsigned data types. 4. No operator overloading. 5. No preprocessor directives (# define). 6. No multiple inheritance. 7. No garbage values for unassigned data types. 8. No explicit memory management by the developer. Memory management is taken care implicitly. 9. No structures, no templates and no unions. Java looks as if it is a known language, familiar earlier, as much of the syntax is borrowed from C/C++. The control structures, functions, arrays and data types etc. looks the same of C/C++. Even though it is a derivative of C++, Java is fully an independent language where the execution entity is a class. 4. Object-Oriented Encapsulation, Inheritance and Polymorphism, the three object-oriented principles are duly supported by Java. Object-oriented methodology aims at reusability of code written only once earlier. Java supports reusability through composition and inheritance. Everything can be viewed as an object; to achieve this, the Java API includes a plethora of classes like java.lang.Integer (to treat a primitive data type as an object), java.io.File (to view an ordinary text file as an object) and java.net.URL (to convert an IP address of a system into an object) etc. Apart this, Java supports dynamic binding and static binding of methods and object casting etc. Benefits of OOPs OOPS comes with many advantages over procedure-oriented languages useful for product architects and programmers. The main and foremost advantage is productivity with lowmaintenance cost. Following list illustrates a few important. 1. With Java design patterns, the product architects can develop modules that can be integrated later to evolve as a big reusable component. 2. Using objects, a programmer can divide his work into a number entities (units) and coding each entity separately. 3. Data hiding helps to hide the data of one entity (unit or object) from another. This helps to write secured programs that cannot be accessed by other parts of the code.

4. With encapsulation, the same data (variables) can co-exist with different objects but without overlapping and ambiguity. 5. Due to encapsulation, software complexity can be reduced. 6. Inheritance helps reusability of code by avoiding redundancy. 7. Object-oriented systems can be scaled up easily from small to medium or medium to large business systems. 8. Using objects, message servicing systems can be developed easily to integrate modules of a business process. 5. Architecture Neutral We know earlier, the Java compiler generates an intermediary bytecode that must be again converted into binary code at execution time. This binary code conversion is effected by the JVM. The bytecode is OS architecture neutral. Any OS can execute the bytecode without bothering its architecture. 6. Robust Java is a robust language which avoids many mistakes a programmer can commit at coding level. First and foremost towards this goal is exception handling mechanism which takes care of user's mistakes at runtime. Java includes a strong type checking for objects and data types both at compile time and runtime. Variables must be assigned before they are used. Array size should not be given in initialization. Java comes with implicit memory management which takes care of many mistakes a programmer can commit in coding. Java eliminates the memory manipulations functions like free() or delete() etc. 7. Internet-based Java started its development for Web-based communication. Java is a strong supporter of Web. Java comes with special programs, Applets and Servlets useful for Internet (Web) communication. Applets placed on client-side can communicate with servlets placed on server-side. Applets written in Java can be downloaded from any Web server and executed on any client system irrespective of OS. 8. Implicit Memory Management We know earlier, one of the striking features of Java is its implicit memory management. It avoids much of the tedious code of memory management by the programmer. If a programmer does not manage the memory robustly with utmost care, as in C/C++, the system may crash sometimes while executing the program. The programmer is relieved of

the usage of destructors and many functions like malloc(), calloc(), sizeof(), free() and delete() etc. When Java software starts, it spawns a garbage collector (gc) thread that takes cares of the garbage of a process. The objects not required in further process of a program are treated as garbage. Keeping the memory for unwanted objects is a wastage. The garbage collector removes these garbage objects while execution is going on; even without a message or warning to the programmer. 9. Interpreted Generally, a language like C/C++ is compiled or a HTML is parsed or VBScript is interpreted; but Java is both compiled and interpreted. At compilation stage, the Java source code is converted into a bytecode file. As bytecode cannot be executed by a microprocessor, at runtime, the JVM converts the bytecode into binary code. This platform-specific binary code is executed and generates output. That is, in Java, from source code to the output, two stages exist compilation and interpretation. 10. Distributed No language can parallel Java in networking support. Java supports both LAN programming (TCP/IP and UDP) and distributed programming. In distributed computing, the systems in communication are spread across the globe. Again this is of two types Internet-based and non internet-based. Java includes sockets and server sockets to support socket (LAN) programming (with java.net package), servlets and JSP (with javax.servlet.http package) for Internet-based programming and RMI/EJB (with java.rmi and javax.ejb packages) to support distributed non Internet-based communication. Java wisely knows the utilization of HTTP, SMTP, POP3 and FTP protocols etc. to communicate between systems. 11. Multithreaded For latest computing techniques, multitasking is a must as in multimedia (animation). Multitasking is a concept supported by OS. A language can utilize effectively the multitasking capabilities of an OS. Java too feels its necessity and supports through its built-in classes from java.lang package. Java supports multitasking through multithreading. A single Java process can be divided into multiple threads and each thread can be given a different task. If one thread's execution stops for some reason, the microprocessor can be assigned with the task of another thread. This shifting of threads reduces microprocessor idle time and thereby output is given at an earliest and looks at the same time. 12. Dynamic Generally in coding, one class may require the functionality of another class. At runtime, JRE can search, hook and load the necessary classes required for the smooth execution of

the program. Do not bother where the files are, may be on your own local disk or in a server at a far off place, JRE knows well how to play the game dynamically. Java has got built-in support for many protocols like HTTP and FTP using which the JRE can download the classes, files and libraries required for the execution of a program. 13. Secured Java, with its good support for distributed technology, comes with many security features required in programming. Java does not support pointers and thereby avoids accidental erasures or changes of the values existing in a different location. Bytecode verifier checks the permissions in between the classes whether they can access or not. Java includes encryption algorithms that can be used by the programmer in distributed communication. Applets are not permitted to access the hard disk files and software. 14. High-Performance We know earlier, Java is slower in its execution. To enhance the performance, the designers took utmost care in designing the API libraries like introducing StringBuffer in place of String, StringBuilder in place of StringBuffer, lightweight Swing GUI components in place of AWT heavyweight components. ArrayList (methods are not synchronized) can be used for Vector (methods are synchronized).

Java Drawbacks
By admin on November 2, 2010

Even though Java is projected as the most demanded language of the times, but has its own disadvantages. Of course, they are very minor in nature and need not be considered as drawbacks compared to the advantages it brings forward.

Java Drawbacks
By admin on November 2, 2010

Even though Java is projected as the most demanded language of the times, but has its own disadvantages. Of course, they are very minor in nature and need not be considered as drawbacks compared to the advantages it brings forward. a) Slow performance: The first and foremost drawback everyone accepts is Java's slow speed of execution. Of course it is designed so to get the affect of platform-independent feature. Designers do trying to increase the performance in other aspects like the introduction of JIT (Just-In-Time) compiler.

b) No support for low-level programming: With Java, low-level programming cannot be done as it is intended to be portable across platforms. c) Poor features in GUI: Java supports GUI controls but with less features. For example, an image cannot be placed on a button. The is overcome with the introduction of javax.swing package. Swing controls come with abundant features that are comparable with any GUI available. d) No control over garbage collection: Garbage collection is one of the built-in features of Java and is entirely managed by JVM. programmer is not given any handles to control the garbage collection to make coding simple. For this reason, Java does not come with delete(), free(), malloc() and sizeof() etc. functions. What Java Can't Do? Even though Java is termed as a production language where productivity is very high, but still it cannot do certain things. The productivity is possible due to the abundant classes available in Java API that can cater to the very specific needs of the programmer. Java includes a few thousands of classes with JDK 1.5 that takes care of many minute aspects of coding. Even though it is hyped so heavily, but it cannot be used to develop low-level programming. Using Java, a new OS or new protocols or DVD burning software etc. cannot be programmed.

Garbage Collection gc() and exit(0)


By admin on March 27, 2011

More on gc() method Unwanted (not used in the remaining part of the program) objects generated in the process are known as garbage. Java includes a special built-in style of removing the garbage known as garbage collection. Garbage collector is a low-priority service thread that removes the garbage periodically. It is a two step style and the algorithm is known as Mark and Sweep. First, the collector marks those objects that are not referenced anywhere in the program. In the second step, it removes those marked objects. The speed of removal varies depending upon the size of the heap and the microprocessor speed etc. The programmer cannot force the JVM to go for garbage collection. It is an in-built phenomenon and is done at the discretion of the JVM. Programmer can maximum ask the JVM to go for garbage collection with the following statement, which need not be honored. System.gc( ); System.exit(0)

exit(0) is a static method of System class which terminates a normal execution of a program. This style is used in AWT GUI to close the window. The zero parameter indicates a normal shutdown. Other than zero indicates abnormal shutdown.

Data Type Casting (Type Conversion)


By S. Nageswara Rao, Corporate Trainer on May 29, 2011 Contents [show/hide]

Java supports two types of castings primitive data type casting and reference type casting. Reference type casting is nothing but assigning one Java object to another object. It comes with very strict rules and is explained clearly in Object Casting. Now let us go for data type casting. Java data type casting comes with 3 flavors.
1. Implicit casting 2. Explicit casting 3. Boolean casting.

1. Implicit casting (widening conversion) A data type of lower size (occupying less memory) is assigned to a data type of higher size. This is done implicitly by the JVM. The lower size is widened to higher size. This is also named as automatic type conversion. Examples:
int x = 10; double y = x; System.out.println(y); // occupies 4 bytes // occupies 8 bytes // prints 10.0

In the above code 4 bytes integer value is assigned to 8 bytes double value. 2. Explicit casting (narrowing conversion) A data type of higher size (occupying more memory) cannot be assigned to a data type of lower size. This is not done implicitly by the JVM and requires explicit casting; a casting operation to be performed by the programmer. The higher size is narrowed to lower size.
double x = 10.5; int y = x; // 8 bytes // 4 bytes ; raises compilation error

In the above code, 8 bytes double value is narrowed to 4 bytes int value. It raises error. Let us explicitly type cast it.

double x = 10.5; int y = (int) x;

The double x is explicitly converted to int y. The thumb rule is, on both sides, the same data type should exist. 3. Boolean casting A boolean value cannot be assigned to any other data type. Except boolean, all the remaining 7 data types can be assigned to one another either implicitly or explicitly; but boolean cannot. We say, boolean is incompatible for conversion. Maximum we can assign a boolean value to another boolean. Following raises error.
boolean int y = boolean int y = x = true; x; x = true; (int) x; // error // error

byte > short > int > long > float > double In the above statement, left to right can be assigned implicitly and right to left requires explicit casting. That is, byte can be assigned to short implicitly but short to byte requires explicit casting. Following char operations are possible.
1 public class Demo 2 { 3 public static void main(String args[]) 4 { 5 char ch1 = 'A'; 6 double d1 = ch1; 7 8 System.out.println(d1); 9 System.out.println(ch1 * ch1); 10 11 double d2 = 66.0; 12 char ch2 = (char) d2; 13 System.out.println(ch2); 14 } 15 }

// prints 65.0 // prints 4225 , 65 * 65

// prints B

Object casting discusses casting between objects of different classes involved in inheritance. ============================================================ Your one stop destination for all data type conversions

byte TO short TO int TO float TO

short int byte int

long float double char long float double char

boolean boolean boolean boolean boolean

byte short long float double char byte short int long double char char

double TO byte short int long float char TO byte short int long float

double boolean double char

boolean TO byte short int long float

String and data type conversions


String TO byte short int long float byte short int double char boolean

long float double char

boolean TO String

Object Casting
By S. Nageswara Rao, Corporate Trainer on May 17, 2011

Assigning one data type to another or one object to another is known as casting. Java supports two types of casting data type casting and object casting. Java permits to assign objects of different classes one to another subject to some conditions. 1. Same class objects can be assigned one to another and it is what we have done with Officer1 class. 2. Subclass object can be assigned to a super class object and this casting is done implicitly. This is known as upcasting (upwards in the hierarchy from subclass to super class). 3. Java does not permit to assign a super class object to a subclass object and still to do so, we need explicit casting. This is known as downcasting (super class to subclass). Downcasting requires explicit conversion. The above rules are explained through the following program.
1 class Flower 2 { 3 public void smell()

// I

4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

{ System.out.println("All flowers give smell, if you can smell"); } } public class Rose extends Flower { public void smell() // II { System.out.println("Rose gives rosy smell"); } public static void main(String args[]) { Flower f = new Flower(); Rose r = new Rose(); f.smell(); r.smell(); f = r; f.smell(); // r = f; r = (Rose) f; f.smell(); } } // I // II // subclass to super class, it is valid // II // super class to subclass, not valid // explicit casting // II

The super class Flower includes only one method smell() and it is overridden by subclass Rose.
f.smell(); r.smell(); // I // II

In the above two statements, nothing is new as both object are calling their own smell() methods. Observe the following two statements.
f = r; f.smell();

In the first statement, subclass object r is assigned (casted) to super class object f. It is a perfect assignment accepted by JVM and casting is done implicitly. In the super class

object f, the subclass object reference (address) r exists. Calling f.smell(), f will call Rose smell() method. From the above observation, a rule can be made as follows. "If a subclass object is assigned to a super class object, the super class object will call subclass overridden method". This is an important rule which leads to dynamic polymorphism.
// r = f;

The above statement does not compile as super class object is assigned to subclass object. To do it, we require explicit casting.
r = (Rose) f; f.smell(); // explicit casting // II

In the above statement, Flower object f is explicitly casted to Rose object r. In the earlier statement f = r, the f includes Rose reference. Now, f returns the Rose reference to Rose itself. For this reason f.smell() prints the subclass Rose smell(). That is, r is calling its own smell(). What happens if f = r does not exist earlier. It will be a compilation error. That is, "before doing explicit casting, implicit casting must be done".

Three Great Principles Data Binding, Data Hiding, Encapsulation


By admin on April 9, 2011

To go before into the subject, just read the program twice. You may guess some values how they are printed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class Officer { int salary; public static void main(String args[]) { Officer o1 = new Officer(); Officer o2 = new Officer(); o1.salary = 5000; o2.salary = 6000; System.out.println("Salary of o1 before initially Rs." + o1.salary);// 5000 System.out.println("Salary of o2 before initially Rs." + o2.salary);// 6000 o1.salary = 7000; System.out.println("Salary of o1 after changing o1 Rs.:" + o1.salary);// 7000 System.out.println("Salary of o2 after changing o1 Rs." + o2.salary);//

21 6000 22 23 o2.salary = 8000; System.out.println("Salary of o1 after changing o2 Rs.:" + o1.salary);// 7000 System.out.println("Salary of o2 after changing o2 Rs." + o2.salary);// 8000 } }

Output screen of Officer.java

salary is an instance variable and should be accessed with an object only, through static main() method. Two objects o1 and o2 are created and salary field is called. The object o1 gets a salary of 5000 and o2 gets 6000. If an instance variable is called with an object, a location is created in the memory. Now two locations are created in the memory for o1.salary and o2.salary. That is, one location of salary is binded with o1 and another location of salary is binded with o2. This is is known as data binding. Due to this binding habit, the salary location of o1 is hidden from o2 and similarly the salary location of o2 is hidden from o1. This is known as data hiding. Due to hiding, o1 cannot access o2 salary and o2 cannot access o1 salary. That is, the variable salary is encapsulated with object o1 and becomes one unit of data. Similarly another unit o2 is made with its own salary, entirely separate from o1 unit. This is known as encapsulation. Encapsulation is a pharmaceutical term where drug powder is placed in a capsule to hide its properties, like taste and color etc., from the patients. Due to data hiding, the properties (the value of fields(instance variables)) of an object are hidden from other objects. This exactly resembles a capsule. The advantage of encapsulation is one instance variable can be given multiple values, of course, by calling with different objects. Encapsulation is an object oriented concept or paradigam or design or principle; you may say anything, all amounts the same.

In the later part of the program, salary of o1 is changed. Only the salary of o1 is affected but not o2 and when o2 salary is changed, o1 salary is not affected. It is due the concept of encapsulation. This is where object-oriented programming takes a lead over procedureoriented programming, like C. Finally, data binding leads to data hiding and data hiding leads to encapsulation.

Encapsulation Want or Dont Want Now let us see how to assign the properties of one object to another by modifying the previous Officer program.
public class Officer1 { int salary; public static void main(String args[]) { Officer1 o1 = new Officer1(); Officer1 o2 = new Officer1(); Officer1 o3 = new Officer1(); Officer1 o4 = new Officer1(); o1.salary = 5000; o2.salary = o1.salary; // assigning variable to variable System.out.println("o1 initial salary Rs." + o1.salary); // 5000 System.out.println("o2 initial salary Rs." + o2.salary); // 5000 o1.salary = 6000; System.out.println("o1 salary after changing o1 Rs." + o1.salary); // 6000 System.out.println("o2 salary after changing o1 Rs." + o2.salary); // 5000 o3.salary = 7000; o4 = o3; // assigning object to object System.out.println("o3 initial salary Rs." + o3.salary); // 7000 System.out.println("o4 inital salary Rs." + o4.salary); // 7000 o3.salary = 8000; System.out.println("o3 salary after changing o3 Rs." + o3.salary); 8000 System.out.println("o4 salary after changing o3 Rs." + o4.salary); 8000 } } // //

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

Output screen of Officer1.java The basic concept in the above code is to observe encapsulation by assigning variable to variable and object to object. Four objects are created. o1 salary is set to 5000 and later o1 salary is assigned to o2 salary. They maintain separate locations and advantage is if o1 salary is changed to 6000, o2 salary is not affected. Observe the output. Later o3 salary is set to 8000. Object o4 is assigned with o3. In Java, when object to object is assigned, they maintain or refer the same location. That is, o3 and o4 refer or point to one salary only. The affect is if one object o3 changes the salary, the other object o4 also changes. Observe the output. Similarly, you can change o4 salary and notice o3 salary also changes; no encapsulation. Copying concepts are more discussed in Copying an Object Shallow Copying Vs. Deep Copying. Final conclusion, we can make out is, if variable to variable is assigned perfect encapsulation is maintained and object to object is assigned no encapsulation is maintained. This must be kept in mind while assigning properties of one object to another. Another style of copying is cloning which we get later.
Using Thin main() Method

In the previous, Officer1 program, all the code is written in the main() method only. You may get output but it is against coding principles. Coding principles say, keep the main() method as thin as possible by placing less code. Limit the main() method just to create objects and calling the methods. Write any code in a method and call the method from the main(). This increases the reusability, readability and debugging becomes easier. Let us modify the previous program.
1 public class Officer2 2 { 3 int salary; 4 public void display(int sal) 5 { 6 salary = sal; 7 } 8 public static void main(String args[]) 9 { 10 Officer2 o1 = new Officer2(); 11 Officer2 o2 = new Officer2(); 12 13 o1.display(5000); 14 o2.display(6000); 15 16 System.out.println(o1.salary); 17 System.out.println(o2.salary); 18 } 19 }

// 5000 // 6000

Output screen of Officer2.java The difference between Officer1 and Officer2 programs is assigning the values to objects o1 and o2. sal is a local variable to display() method and salary is an instance variable (the other name of global variable). Local variable sal is assigned to instance variable salary. When o1.display(5000) is called, 5000 goes to sal and in turn sal gives to salary. Because salary is an instance variable, one location on the name o1.salary is created and is accessed though main(). But o1 is not linked to sal because sal is a local variable and thereby no location is created. Similar discussion is available in Using Variables from Methods.

Java I/O Streams Overview


By S. Nageswara Rao, Corporate Trainer on April 17, 2011

Data can be stored on a computer system, as per the code requirements, in two ways, either permanently or temporarily. Temporary storage can be accomplished by storing the data in datastructures or instance variables. The data is temporary because it is stored in RAM. For a permanent storage, the data should be stored on the hard disk either in the form of database tables or files. This tutorial is concerned with I/O streams used to write data to a file and later read from the file. Overview of Streams There comes two entities a source and a destination. Source is that from where data is read and the destination is that one to where data is written. The source and destination need not be a file only; it can be a socket or keyboard input etc. To do the job of reading and writing, there comes two types of streams input streams and output streams. An input stream job is to read from the source and the output stream job is to write to the destination. That is, in the program, it is necessary to link the input stream object to the soruce and the output stream object to the destination. I/O streams are carriers of data from one place to another. The input stream carries data from the source and places it temporarily in a variable (like int k or String str etc.) in the process (program). The output stream takes the data from the variable and writes to the destination. The variable works like a temporary buffer between input stream and output stream.

It is clear from the above figure, the input stream reads from the soruce and puts in the buffer (actually in programming, in a temporary variable, shown later). The output stream takes from the memory and writes to the destination.

All the classes needed to do with reading and writing (like file copying) are placed in the package java.io by the designers. All the I/O streams do the file reading or writing sequentially (means, one byte after another from start to the end of file). It can be done at random also. For this another class exists RandomAccessFile. The java.io package also includes another class, File, to know the properties of a file like the file has read permission or write permission etc. Java IO at a Glance

Multithreading Concepts
By admin on March 21, 2011

Introduction Comparative to other languages, multithreading is very easy and simple in Java and the credit goes to the portability nature and support of many Java API classes. The built-in support for threads is simple and straight so that any programmer can do with multithreading operations without confusion and special attention. Multithreading uses very effectively the microprocessor time by reducing its idle time. When the processor's

idle time is reduced, the output of the programs comes earlier. Multithreading is a concept that should be supported by the operating system. Now-a-days, all operating systems support multithreading. Multitasking, Multiprocessing and Multithreading A program under execution is called a process. The general definition, a novice expresses, of multithreading is "performing multiple tasks at the same time is called multitasking ". This is very wrong and is the result of misunderstanding the concept. Every computer person knows well that microprocessor can execute only one instruction (task) at a time. That is, the earlier definition is going wrong somewhere else. This is the point of confusion about multithreading for everyone. Let us be clear about the concept. When a process is being executed, there may be an interruption, sometimes, for execution; for example, a keyboard input (scanf) may not be fed immediately. When not fed, the execution is halted (observe, the cursor will be blinking even for the whole day when the input is not given). Now the processor is free and idle. We can ask the microprocessor to do another process meantime. The processor obliges (as underlying OS supports multitasking). Now, two programs are under execution the first one half the way completed and kept apart and the other being executed. When the second task (process) is over, if the input is ready, the control will be shifted to the first process and now the first process is executed completely. The result is output of both the programs is obtained earlier. All this is transparent (not known) to the user as context switching occurs at very fast speed. "Shifting the microprocessor to execute another process when the first process is stopped its execution, is known as multithreading". Shifting between the processes is known as context switching. Do not shift unnecessarily when the first program is going smooth with its execution as context switching takes more time and performance looses. Shift only when a running process is stopped for some reason. Putting multiple processors (say two) and feeding multiple processes simultaneously is known as multiprocessing and is a very rare phenomenon as multiple processors on desktop PCs is uncommon (only super computers have). Multithreading is the Java's style of achieving multitasking. A single Java program can be divided into a number of threads and executed simultaneously while shifting between the threads when one stops its execution. The current tutorial discusses how to divide a Java program into multiple threads and how to execute them. Simultaneously, concurrently, parallely These terms are put here as they are again confusing. All means the same of doing multiple tasks at the same time. "At the same time" is a confusing idiom. Many processes may exist whose execution is stopped in the middle for some reason. Remember, only one can be active at any time. Which ever process is ready is called and executed. "Many" must be interpreted this way. It looks all at a time as context switching happens very fast (like cinema where a number of frames of images are run is such a speed, our eye cannot catch).

Some more confusing terms are Preemptive and Cooperative Multitasking and Timesharing . These terms are also discussed hereunder. Preemptive multitasking and Time-sharing At a given time, a number of processes may be getting executed on the CPU. CPU allocates a certain period of time, known as time-slice, for each process to execute. Each process is guaranteed of a time-slice. In preemptive multitasking , one process empties (forcibly evacuating) the other process for the time-slice period and thus every process definitely gets the CPU time. Thus, CPU time is shared by all the processes and is known as time sharing. Time sharing is a CPU architecture where CPU distributes its time equally to all the processes waiting for execution. Preemptive and Cooperative Multitasking In multitasking two types of algorithms exists preemptive multitasking and cooperative multitasking. In preemptive multitasking, each process is allotted a certain period of time known as time slice. With time slices, the waiting processes get evenly all the CPU time and one process cannot hold the CPU time as long it wants. In contrary, in cooperative multitasking, one process can hold the microprocessor time as long as it would like. But the CPU is empowered to remove the process if the process does not utilize the time after holding it. Preemptive multitasking is supported by OS/2, UNIX, Windows NT etc. Cooperative multitasking is supported by Windows 3.1, UNIX, Windows NT etc. Each type comes with its own advantages. When an immediate action or attention is required, like keyboard input or a button click, preemptive is preferred. The disadvantage of cooperative multitasking is, if designed poorly, it may hang the system. Preemptive Scheduling and Non-preemptive Scheduling For forcing the thread to vacate the microprocessor, two properties can be considered priority and waiting time. In preemptive scheduling, a thread with more priority vacates the executing thread of low priority. That is, low-priority thread yields to the high-priority thread. In contrary, in non-preemptive scheduling, waiting time is considered and not priority. That is, the high-priority thread cannot relinquish a low-priority thread having more waiting time. Memory Protection With multitasking, the operating system must be built in a robust way. One ill-behaved process (a process that went out of control) may ruin or overwrite the other process data. This is a very serious condition. This is taken care by the OS in its architecture. Every process (or thread later) comes with its own execution area known as context area. One process is not allowed to access, by the OS, other process context area. To some extent, the programmer can also restrict this by issuing privileges to the processes. By issuing a lowprivilege, the process may be restricted from accessing a particular memory region.

Java Thread Basics


By admin on March 7, 2011

Introduction If only one process exists before the processor and if the process execution is stopped for some reason, the microprocessor becomes idle without any work. This type of programming is known as monolithic programming. In monolithic programming, the whole process consitutes a single module. To get a better understanding, Lord Buddha statue in Hussain Sagar in Hyderabad, India is a monolithic statue (single stone carvation). The minus point of single stone is if some part is to be replaced in long future, the whole statue is to be replaced. The same is the problem with monolithic programming also; if a part of the program is stopped, the whole program comes to standstill. There comes to the rescue multithreading. A Java process can be divided into a number of threads (or to say, modules) and each thread is given the responsibility of executing a block of statements. That is, a thread is an incharge of a few statements of a program. If one thread stops its execution, the execution control can be shifted to another thread. Remember, here all threads belong to the same process. This is the advantage of threads over monolithic programming. The ultimate result is microprocessor idle time is reduced. The end result is output of the program comes earlier.

A thread is a part of a process. A thread lives within a process. No process, no thread. To understand better, we cannot keep our brain outside for sometime and place it back; it is because brain is a part of human body. Similarly, a thread cannot be there without a process. Infact, a process is divided into a number of threads.

Now let us define a thread; "a thread is a single sequential flow of control within a process". It is something confusing. Let us be clear. As said earlier, a thread comprises of a block statements. These statements are executed one-by-one sequentially. Every thread maintains its own execution context within a process context area. We can say, a thread is a sub process. For execution, one thread does not depend on other; every thread is independent of other. This tutorial gives you how to divide a process into a number of threads or to say, how to create threads, how to assign different tasks, priorities and synchronization Lightweight process and Heavyweight process If the execution shifts between the threads of the same process, it is known as lightweight process. If the execution shifts between the threads of different processes, it is known as heavyweight process.

In the above figure, if the control shifts between the threads t1 and t2 of the same process p1, it is known as lightweight process. If the control shifts between the threads t1 of process p1 and t1 of process p2, it is known as heavyweight process. Generally, threads are designed to be lightweight because heavyweight is a big overhead to the OS. Advantages of Multithreading First and foremost advantage is, as you have understood so far, microprocessor idle time is reduced and consequently output is obtained faster. When a program is divided into number of threads, each comprising a few statements, the code becomes simpler, readability increases, debugging and maintenance becomes easier. Generally, user's input is very slow in GUI environment. This late user's response is best utilized by other threads (reduces overall execution time).

Applications of Multithreading
1. Playing media player while doing some activity on the system like typing a document. 2. Transferring data to the printer while typing some file. 3. Downloading some files like images while browsing is going on (downloading images is very slow). 4. Running animation while system is busy on some other work. 5. Honoring requests from multiple clients by an application/web server. 6. Threads are useful in handling events generated by components like mouse etc. A thread is capable to produce a frame with images.

Java API support for Threads Multithreading is one of the built-in and important feature of Java language. Java's builtin classes, useful to develop a multithreaded program, are hereunder and all are from java.lang package.
Class Thread Useful Methods sleep(), join(), suspend(), resume(), stop() and run() etc.

Runnable interface only run() method Object ThreadGroup wait(), notify() and notifyAll() getName(), getParent() and activeCount() etc.

Common Exceptions in Threads The following are common exceptions that come in thread programming. All are from java.lang package.
1. InterruptedException : It is thrown when the waiting or sleeping state is disrupted by another thread. 2. IllegalStateException : It is thrown when a thread is tried to start that is already started.

Life cycle of Thread


By admin on February 19, 2011

Introduction Generally, the life cycle gives the same meaning for servlets, applets and threads. Different states, a thread (or applet/servlet) comes under from its object creation to object removal

(garbage collection) is known as life cycle of thread (or applet/servlet). There are four main states in the life cycle of thread.
1. 2. 3. 4. Born state Runnable state Blocked state Dead state

The diagram given below, gives a bird view of the states.

1. Born state
Thread t1 = new Thread();

In born state, the thread object is created, occupies memory but is inactive. In the above statement t1 thread is created but is not eligible for microprocessor time as it is inactive. To make the thread active, call start() method on the thread object as t1.start(). This makes the thread active and now eligible for processor time slices. This state can be compared with start() method of applets. 2. Runnable state When the thread is active, the first and foremost job, it does implicitly, is calling run() method. When the thread is executing the run() method, we say, the thread is in runnable state. As it is a callback method, all the code expected to run by the thread, should be written here. In this state, the thread is active. This state can be compared to the paint() method of applets.

3. Blocked state The programmer can make a running thread to become inactive temporarily for some period. In this period (when inactive after starting), the thread is said to be in blocked state. The blocked state thread, as inactive, is not eligible to processor time. This thread can be brought back to the runnable state at any time. A thread can go a number of times from runnable state to blocked state and vice versa in its life cycle. This state can be compared with the stop() method of applets. 4. Dead state When the execution of run() method is over, as the job it is meant is done, it is brought to dead state. It is done implicitly by JVM. In dead state, the thread object is garbage collected. It is the end of the life cycle of thread. Once a thread is removed, it cannot be restarted again (as the thread object does not exist). This state can be compared with destroy() method of applets. A thread can be killed and brought to dead state, anytime from any state, by calling explicitly stop() method. Number of ways a thread can be brought to blocked state A normal running thread can be brought, a number of ways, into blocked state, listed hereunder.
1. 2. 3. 4. By calling sleep() method. By calling suspend() method. When wait() method is called as in synchronization When an I/O operation is performed, the thread is implicitly blocked by JVM.

IllegalStateException: This exception is thrown when you try to start a thread which is already started.

Das könnte Ihnen auch gefallen