Tuesday, November 13, 2012

Creating scenarios in FitNesse


|import           |
|net.indecomm.euil|


!|Scenario|abbc|url|def|data|ghi|locator|
|start    |UserInteractionWeb              |
|openURL  |@url                              |
|maximizeBrowser                             |

                       

|Abbc Def Ghi                                                       |
|url                       |data                |locator               |
|www.google.com|abhishekkumar|.//*[@id='Email']|
|www.gmail.com  |abhishekkumar|.//*[@id='Email']|

Friday, July 13, 2012

Log4j Example

Create a class where you need to implement log

package com.vaannila.dmin;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class SampleAdmin {
    static Logger logger = Logger.getLogger(SampleAdmin.class);

    public void generateReport() {
        logger.debug("Sample amit debug message");
        logger.info("Sample amit info message");
        logger.warn("Sample amit warn message");
        logger.error("Sample amit error message");
        logger.fatal("Sample fatal message");
        logger.trace("Sample trace message");
    };
}


A test class to run the above class.
package com.vaannila.admin;
import org.apache.log4j.Logger;

public class test {

    public static void main(String[] args) {
        SampleAdmin s = new SampleAdmin();
        s.generateReport();
    }
}

log4j.properties 
right click the src folder create a log4j.properties file.

log4j.rootLogger=TRACE
# AdminFileAppender - used to log messages in the admin.log file.
log4j.appender.AdminFileAppender=org.apache.log4j.FileAppender
log4j.appender.AdminFileAppender.File=admin.log
log4j.appender.AdminFileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.AdminFileAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

log4j.logger.com.vaannila.admin=,AdminFileAppender


admin.log
Right click the project and create a admin.log file, which would conatin you log.

 log4j.jar file
Download the log4j.jar file which is log4j-1.2.15.

All other important points are highlighted, dont miss that.
If required result not comming, tell me.





















Wednesday, July 11, 2012

Handling Pop up in Selenium2

public class closeopen {
    public static void main(String[] args) {
       
         WebDriver driver = new FirefoxDriver();
         driver.get("http://www.javascripter.net/faq/alert.htm");
         driver.findElement(By.xpath("html/body/p[1]/table/tbody/tr/td[1]/form/input")).click();
         Alert alert = driver.switchTo().alert();
         alert.accept();
}
}

enjoy

Tuesday, May 29, 2012

object oriented design

How I explained OOD to my wife

 

Introduction

My wife Farhana wants to resume her career as a software developer (she started her career as a software developer, but couldn't proceed much because of our first child's birth), and these days, I am trying to help her learn Object Oriented Designs as I've got some experience in software design and development.
Since my early days in software development, I have always observed that no matter how hard a technical issue seems, it always becomes easier if explained from a real life perspective and discussed in a conversational manner. As we had some fruitful conversations on Object Oriented Designs, I thought I could share it because someone might find it an interesting way of learning OOD.
Following is how our OOD conversation took place:

Topic: Introducing OOD

Shubho: Darling, let's start learning Object Oriented Designs. You know Object Oriented Principles, right?
Farhana: You mean, Encapsulation, Inheritance, and Polymorphism, right? Yes, I know the principles.
Shubho: OK, I hope you already know how to use classes and objects. Let us learn Object Oriented Designs today.
Farhana: Hold on a second. Isn't Object Oriented Principles enough to do Object Oriented programming? I mean, I can define classes and encapsulate properties and methods. I can also define a class hierarchy based upon their relationship. So, what's left?
Shubho: Good question. Object Oriented Principles and Object Oriented Design are actually two different things. Let me give you a real life example to help you understand.
When you were child you learned alphabets first, right?
Farhana: Yes.
Shubho: OK. You also learned words and how to assemble the alphabets to make those meaningful words. Along with that, you learned some basic grammar to assemble the words into sentences. For example, you had to maintain tenses, and you had to use prepositions, conjunctions, and others properly to create grammatically correct sentences. Say, a sentence like the following:
"I" (pronoun) "want" (Verb) "to" (Preposition) "learn" (Verb) "OOD" (Noun)
You see, you are assembling the words in some order, and you are also choosing the correct words to end up with a sentence that has some meaning.
Farhana: OK, so, what does this mean?
Shubho: This is analogous to Object Oriented Principles. OOP says about the basic principles and the core ideas to do Object Oriented programming. Here, OOP can be compared to the basic English grammar, where the basic grammar teaches you how to construct a meaningful and correct sentence using words, and OOP teaches you to construct classes, encapsulate properties and methods inside them, and also develop a hierarchy between them and use them in your code.
Farhana: Hm..I got the point. So, where does OOD fit here?
Shubho: You'll get your answer soon. Now, suppose you need to write articles and essays on some topics. You may also wish to write books on different subjects that you have expertise on. Knowing how to construct sentences is not enough to write good essays/articles or books, right? You need to write a lot, and need to learn to explain things in a good way so that readers can easily understand what you are trying to say.
Farhana: Seems interesting... carry on.
Shubho: Now, if you want to write a book on a particular subject (say, Learning Object Oriented Design), you got to know how to divide the subject into smaller topics. You also need to write chapters on those topics, and you need to write prefaces, introductions, explanations, examples, and many other paragraphs in the chapters. You need to design the overall book and learn some best practices of writing techniques so that the reader can easily understand what you are trying to explain. This is about the bigger picture.
In software development, OOD addresses the bigger picture. You need to design your software in a way that your classes and code are modularized, re-usable, and flexible, and there are some good guidelines to do that so that you don't have to re-invent the wheel. There are some design principles that you can apply to design your classes and objects. Makes sense?
Farhana: Hmm.. got the initial idea, but need to learn more.
Shubho: Don't worry, you will learn soon. Just let our discussion going.

Topic: Why OOD?

Shubho: This is a very important question. Why should we care about Object Oriented Design when we can create some classes quickly and finish development and deliver? Isn't that enough?
Farhana: Yes, I didn't know about OOD earlier, and still I was able to develop and deliver projects. So, what is the big deal?
Shubho: OK, let me get a classic quote for you:
"Walking on water and developing software from a specification are easy if both are frozen."
- Edward V. Berard
Farhana: You mean software development specifications keep changing constantly?
Shubho: Exactly! The universal truth of software is "your software is bound to change". Why?
Because, your software solves real life business problems and real life business processes evolve and change - always.
Your software does what it is supposed to do today and does it good enough. But, is your software smart enough to support "changes"? If not, you don't have a smartly designed software.
Farhana: OK, so, please explain "smartly designed software" sir!
Shubho: "A smartly designed software can adjust changes easily; it can be extended, and it is re-usable."
And, applying a good "Object Oriented Design" is the key to achieve such a smart design. Now, when can you claim that you have applied good OOD in your code?
Farhana: That's my question too.
Shubho: You are doing Object Oriented Design if your code is:
  • Of course, object oriented.
  • Re-usable.
  • Can be changed with minimal effort.
  • Can be extended without changing existing code.
Farhana: And..?
Shubho: We are not alone. Many people have already given lots of thoughts and put a lot of effort on this issue, and they've tried to achieve good Object Oriented Design and identify some basic principles for doing Object Oriented Design (some basic inspirations which you can use to lay out your object oriented design). They also have identified some common design patterns that are applicable to common scenarios (based on the basic principles).
Farhana: Can you name some?
Shubho: Sure. There are many design principles out there, but at the basic level, there are five principles which are abbreviated as the SOLID principles (thanks to Uncle Bob, the great OOD mentor).
S = Single Responsibility Principle
O = Opened Closed Principle 
L = Liscov Substitution Principle
I = Interface Segregation Principle
D = Dependency Inversion Principle
In the following discussion, we will try to understand each of these in detail.

Topic: Single Responsibility Principle

Shubho: Let me show you the poster first. We should thank the person who made the posters, these are really interesting.

Single Responsibility Principle poster
It says, "just because you can implement all the features in a single device, you shouldn't". Why? Because it adds a lot of manageability problems for you in the long run.
Let me tell you the principle in Object Oriented terms.
"There should never be more than one reason for a class to change."
Or, differently said: "A class should have one and only one responsibility".
Farhana: Can you please explain?
Shubho: Sure, this principle says that if you have a class that has more than one reason to change (or has more than one overall responsibility), you need to split the class into multiple classes based upon their responsibility.
Farhana: Hmm... does that mean that I can't have multiple methods in a single class?
Shubho: Not at all. Rather, you surely can have multiple methods in a single class. The issue is, they have to meet a single purpose. Now, why is splitting important?
It's important because:
  • Each responsibility is an axis of change.
  • Code becomes coupled if classes have more than one responsibility.
Farhana: Could you please give me an example?
Shubho: Sure, take a look at the following class hierarchy. Actually, this example is taken from Uncle Bob, so thanks to him again.

Class hierarchy showing violation of SRP principle
Here, the Rectangle class does the following:
  • It calculates the value of the rectangular area.
  • It renders the rectangle in the UI.
And, two applications are using this Rectangle class:
  • A computational geometry application uses this class to calculate the area
  • A graphical application uses this class to draw a rectangle in the UI
This is violating the SRP (Single Responsibility Principle)!
Farhana: How?
Shubho: You see, the Rectangle class is actually performing two different things. It is calculating the area in one method, and it is returning a GUI representation of the rectangle in another method. This leads to some interesting problems:
  • We must include the GUI in the computational geometry application. While deploying the geometry application, we must include the GUI library.
  • A change to the Rectangle class for the graphical application may lead to a change, build, and test for the computational geometry application, and vice-versa.
Farhana: It's getting interesting. So I guess we should break up the class based on its responsibilities, right?
Shubho: Exactly. Can you predict what we should do?
Farhana: Sure, let me try. Following is what we might need to do:
Separate the responsibilities into two different classes, such as:
  • Rectangle: This class should define the area() method.
  • RectangleUI: This class should inherit the Rectangle class and define the Draw() method.
Shubho: Perfect. In this case, the Rectangle class will be used by the computational geometry application, and the RectangleUI class will be used by the graphical application. We could even separate the classes into two separate DLLs, and that will allow us not to touch the other in case a change is needed to be implemented in one.
Farhana: Thanks, I think I understand SRP. One thing, SRP seems to be an idea of breaking things into molecular parts so that it becomes reusable and can be managed centrally. So, shouldn't we apply SRP in the method level as well? I mean, we might have written methods that have many lines of code for doing multiple things. These methods might be violating SRP, right?
Shubho: You got it right. You should break down your methods so that each method does a particular work. That will allow you to re-use methods, and in case a change is required, you are able to do the change by modifying minimal amount of code.

Topic: Open-Closed Principle

Shubho: Here goes the poster for the Open-Closed Principle:

Figure: Open Closed Principle poster
If I need to explain it in design oriented terms, it would be as follows:
"Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification."
At the most basic level, that means, you should be able to extend a class's behavior without modifying it. It's just like I should be able to put on a dress without doing any change to my body, ha ha.
Farhana: Interesting. You can change your look by putting any dress you want, and you don't have to change your body for that. So you are open for extension, right?
Shubho: Yes. In OOD, open for extensions means that the behavior of the module/class can be extended and we can make the module behave in new and different ways as the requirements change, or to meet the needs of new applications.
Farhana: And your body is closed for modification. I like this example. So, the source code for a core class or module should not be modified when it needs an extension. Can you explain with some examples?
Shubho: Sure, take a look at the following example. This doesn't support the "Open-Closed" principle:

Class hierarchy showing violation of Open Closed principle
You see, the Client and Server classes are both concrete. So, if for any reason, the server implementation is changed, the client also needs a change.
Farhana: Makes sense. If a browser is implemented as tightly coupled to a specific server (such as IIS), then if the server is replaced for some reason with another one (say, Apache) the browser also needs to be changed or replaced. That would be really horrible!
Shubho: Correct. So following would be the correct design:

Class hierarchy showing Open Closed Principle
In this example, there is an Abstract Server class added, and the client holds a reference to the abstract class, and the Concrete Server class implements the Abstract Server class. So, if for any reason the Server implementation is changed, the Client is not likely to require any change.
The Abstract Server class here is closed for modification, and the concrete class implementations here are open for extension.
Farhana: As I understand, abstraction is the key, right?
Shubho: Yes, basically, you abstract the things that are the core concepts of your system, and if you do the abstraction well, most likely, it would require no change when the functionality is to be extended (such as the server is an abstract concept). And, you define the abstract things in the implementations (say, IISServer implements the Server) and code against abstractions (Server) as much as possible. This would allow you to extend the abstract thing and define a new implementation (say, ApacheServer) without doing any change in the client code.

Topic: Liskov's Substitution Principle

Shubho: The name "Liskov's Substitution Principle" sounds very heavy, but the idea is pretty basic. Take a look at this interesting poster:

Liskov Substitution Principle poster
The principle says:
"Subtypes must be substitutable for their base types."
Or, if said differently:
"Functions that use references to base classes must be able to use objects of derived classes without knowing it."
Farhana: Sorry, sounds confusing to me. I thought this is the basic rule of OOP. This is polymorphism, right? Why was an Object Oriented Principle required on this issue?
Shubho: Good question. Here is your answer:
In basic Object Oriented Principles, "Inheritance" is usually described as an "is a" relationship. If a "Developer" is a "SoftwareProfessional", then the "Developer" class should inherit the "SoftwareProfessional" class. Such "Is a" relationships are very important in class designs, but it's easy to get carried away and end up in a wrong design with a bad inheritance.
The "Liskov's Substitution Principle" is just a way of ensuring that inheritance is used correctly.
Farhana: I see. Interesting.
Shubho: Yes darling, indeed. Let's take a look at an example:

Class hierarchy showing an example of Liskov Substitution Principle
Here, the KingFisher class extends the Bird base class and hence inherits the Fly() method, which is pretty good.
Now take a look at the following example:

Corrected class hierarchy of Liskov Substitution Principle
Ostrich is a Bird (definitely it is!) and hence it inherits the Bird class. Now, can it fly? No! Here, the design violates the LSP.
So, even if in real world this seems natural, in the class design, Ostrich should not inherit the Bird class, and there should be a separate class for birds that can't really fly and Ostrich should inherit that.
Farhana: OK, understood. So, let me try to point out why the LSP is so important:
  • If LSP is not maintained, class hierarchies would be a mess, and if a subclass instance was passed as parameter to methods, strange behavior might occur.
  • If LSP is not maintained, unit tests for the base classes would never succeed for the subclass.
Am I right?
Shubho: You are absolutely right. You can design objects and apply LSP as a verification tool to test the hierarchy whether inheritance is properly done.

Topic: The Interface Segregation Principle

Shubho: Today, we will learn the "Interface Segregation Principle". Here is the poster:

Interface Segregation Principle poster
Farhana: What does it mean?
Shubho: It means the following:
"Clients should not be forced to depend upon interfaces that they do not use."
Farhana: Explain please.
Shubho: Sure, here is your explanation:
Suppose you want to purchase a television and you have two to choose from. One has many switches and buttons, and most of those seem confusing and doesn't seem necessary to you. Another has a few switches and buttons, which seems familiar and logical to you. Given that both televisions offer roughly the same functionality, which one would you choose?
Farhana: Obviously the second one with the fewer switches and buttons.
Shubho: Yes, but why?
Farhana: Because I don't need the switches and buttons that seem confusing and unnecessary to me.
Shubho: Correct. Similarly, suppose you have some classes and you expose the functionality of the classes using interfaces so that the outside world can know the available functionality of the classes and the client code can be done against interfaces. Now, if the interfaces are too big and have too many exposed methods, it would seem confusing to the outside world. Also, interfaces with too many methods are less re-usable, and such "fat interfaces" with additional useless methods lead to increased coupling between classes.
This also leads to another problem. If a class wants to implement the interface, it has to implement all of the methods, some of which may not be needed by that class at all. So, doing this also introduces unnecessary complexity, and reduces maintainability or robustness in the system.
The Interface Segregation principle ensures that Interfaces are developed so that each of them have their own responsibility and thus they are specific, easily understandable, and re-usable.
Farhana: I see. You mean interfaces should contain only the necessary methods and not anything else?
Shubho: Exactly. Let's see an example.
The following interface is a "Fat interface" which violates the Interface Segregation principle:

Example of an interface violating the Interface Segregation principle
Note that the IBird interface has many bird behaviours defined along with the Fly() behaviour. Now, if a Bird class (say, Ostrich) implements this interface, it has to implement the Fly() behaviour unnecessarily (Ostrich doesn't fly).
Farhana: That's correct. So, this interface must be split?
Shubho: Yes. The "Fat Interface" should be broken down into two different interfaces, IBird and IFlyingBird, where the IFlyingBird inherits IBird.

Correct version of the interface in the Interface Segregation principle example
If there is a bird that can't fly (say, Ostrich), it would implement the IBird interface. And if there is a bird that can fly (say, KingFisher), it would implement the IFlyingBird interface.
Farhana: So, if I go back to the example with the television with many switches and buttons, the manufacturer of that television must have a blueprint of that television where the switches and buttons are included in the plan. Whenever they want to create a new model of the television, if they need to re-use this blueprint, they would need to create as many switches and buttons as included in the plan. That wouldn't allow them to re-use the plan, right?
Shubho: Right.
Farhana: And, if they really want to re-use their plans, they should divide their television's blueprint into smaller pieces so that they can re-use the plan whenever any new kind of television is to be created.
Shubho: You got the idea.

Topic: The Dependency Inversion Principle

Shubho: This is the last principle among the SOLID principles. Here is the poster:

Dependency Inversion principle poster
It says..
"High level modules should not depend upon low level modules. Rather, both should depend upon abstractions."
Shubho: Let's consider a real world example to understand it. Your car is composed of lots of objects like the engine, the wheels, the air conditioner, and other things, right?
Farhana: Yes, of course.
Shubho: OK, none of these things are rigidly built within a single unit; rather, each of these are "pluggable" so that when the engine or the wheel has problem, you can repair it (without repairing the other things) and you can even replace it.
While replacement, you just have to ensure that the engine/wheel conforms to the car's design (say, the car would accept any 1500 CC engine and will run on any 18 inch wheel).
Also, the car might allow you to put a 2000 CC engine in place of the 1500 CC, given the fact that the manufacturer (say, Toyota) is the same.
Now, what if the different parts of your car were not built in such a "pluggable nature"?
Farhana: That would be horrible! Because, in that case, if your car's engine is out of order, you will have to fix the whole car or purchase a new one!
Shubho: Yes. Now, how can the "pluggable nature" be achieved?
Farhana: "Abstraction" is the key, right?
Shubho: Yes. In real world, Car is the higher level module/entity, and it depends on the lower level modules/entities like the Engines or Wheels.
Rather than directly depending on the Engines or Wheels, the car depends on the abstraction of some specification of Engine or Wheels so that if any the Engine or Wheel conforms to the abstraction, these could be assembled with the car and the car would run.
Let's take a look at the following class diagram:

Dependency Inversion principle class hierarchy
Shubho: In the above Car class, notice that there are two properties, and both of these are of abstract type (Interface) rather than concrete type.
The Engine and Wheels are pluggable because the car would accept any object implementing the declared interfaces, and that will not require any change in the Car class.
Farhana: So, if Dependency Inversion is not implemented in the code, we run the risk of:
  • Damaging the higher level code that uses the lower level classes.
  • Requiring too much time and effort to change the higher level code when a change occurs in the lower level classes.
  • Producing less-reusable code.
Shubho: You got it perfect darling!

Summary

Shubho: There are many other Object Oriented principles other than the SOLID principles. Some are:
  • "Composition over Inheritance": This says about favoring composition over inheritance.
  • "Principle of least knowledge": This says that "the less your class knows, the better".
  • "The Common Closure principle" : This says that "related classes should be packaged together".
  • "The Stable Abstractions principle": This says that "the more stable a class is, the more it must consist of abstract classes."
Farhana: Shouldn't I learn those principles too?
Shubho: Yes, of course. You have the whole world wide web to learn from. Just Google on those principles and try to understand. And of course, don't hesitate me to ask me if you need help.
Farhana: I've heard there are many Design Patterns built upon those design principles.
Shubho: You are right. Design Patterns are nothing but some commonly suggested design suggestions in commonly recurring situations. These are mainly inspired by the Object Oriented Design principles. You can think of Design Patterns as "Frameworks" and OOD principles as "Specifications".
Farhana: So, am I going to learn Design Patterns next?
Shubho: Yes darling.
Farhana: That would be exiting, right?
Shubho: Yes, that would be really exiting.

Next

 

Design Patterns

How I explained Design Patterns to my wife: Part 1

Introduction

Me and my wife had some interesting conversations on Object Oriented Design principles. After publishing the conversation on CodeProject, I got some good responses from the community and that really inspired me. So, I am happy to share our next conversation that took place on Object Oriented Design Patterns. Here it is.

What is a Design Pattern?

Shubho: I guess you already have some basic idea about Object Oriented Design principles. We had a nice talk on the OOD principles (SOLID principles), and I hope you didn't mind that I published our conversation in a CodeProject article. You can find it here: How I explained OOD to my wife.
Design Patterns are nothing but applications of those principles in some specific and common situations, and standardizing some of those. Let's try to understand what Design Patterns are by using some examples.
Farhana: Sure, I love examples.
Shubho: Let's talk about our car. It's an object, though a complex one, which consists of thousands of other objects such as the engine, wheels, steering, seats, body, and thousands of different parts and machinery.

Different parts of a car.
While building this car, the manufacturer gathered and assembled all the different smaller parts that are subsystems of the car. These different smaller parts are also some complex objects, and some other manufacturers had to build and assemble those too. But, while building the car, the car company doesn't really bother too much about how those objects were built and assembled (well, as long as they are sure about the quality of these smaller objects/equipments). Rather, the car manufacturer cares about how to assemble those different objects into different combinations and produce different models of cars.

Different models of cars, produced by assembling different parts and following different designs.
Farhana: The car manufacturer company must have some designs or blue prints for each different model of car which they follow, right?
Shubho: Definitely, and, these designs are well-thought designs, and they've put a good amount of time and effort to sketch those designs. Once the designs are finalized, producing a car is just a matter of following the designs.
Farhana: Hm.. it's good to have some good designs upfront and following those allows to produce different products in a quick amount of time, and each time the manufacturer has to build a product for a specific model, they don't have to develop a design from scratch or re-invent the wheel, they just follow the designs.

Different design plans for producing different models of products (cars).
Shubho: You got the point. Now, we are software manufacturers and we build different kinds of software programs with different components or functionality based upon the requirements. While building such different software systems, we often have to develop code for some situations that are common in many different software systems, right?
Farhana: Yes. And often, we face common design problems while developing different software applications.
Shubho: We try to develop our software applications in an Object Oriented manner and try to apply OOD principles for achieving code that is manageable, reusable, and expandable. Wouldn't it be nice whenever we see such design problems, we have a pool of some carefully made and well tested designs of objects for solving those?
Farhana: Yes, that would save us time and would also allow us to build better software systems and manage them later.
Shubho: Perfect. The good news is, you don't have to really develop that pool of object designs from scratch. People already have gone through similar design problems for years, and they already have identified some good design solutions which have been standardized already. We call these Design Patterns.
We must thank the Gang of Four (GoF) for identifying the 23 basic Design Patterns in their book Design Patterns: Elements of Reusable Object-Oriented Software. In case you are wondering who formed this famous gang, they are Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. There are many Object Oriented Design Patterns, but these 23 patterns are generally considered the foundation for all other Design Patterns.
Farhana: Can I create a new pattern? Is that possible?
Shubho: Yes darling, why not? Design Patterns are not something invented or newly created by scientists. They are just discovered. That means, for each kind of common problem scenario, there must be some good design solutions there. If we are able to identify an object oriented design that could solve a new design related problem, that would be a new Design Pattern defined by us. Who knows? If we discover some a Design Pattern, someday people may call us Gang of Two.. Ha ha.
Fahana: :)

How will we learn Design Patterns?

Shubho: As I have always believed, examples are the greatest way of learning. In our learning approach, we won't discuss the theories first and implement later. I think this is a BAD approach. Design Patterns were not invented based on theories. Rather, the problem situations occurred first and based upon the requirement and context, some design solutions were evolved, and later some of them were standardized as patterns. So, for each design pattern we discuss, we will try to understand and analyze some real life example problems, and then we will try to formulate a design in a step by step process and end up with a design that will match with some patterns; Design Patterns were discovered in this same process. What do you think?
Farhana: I think this approach makes more sense to me. If I can end up with Design Patterns by analyzing problems and formulating solutions, I won't have to memorize design diagrams and definitions. Please proceed using your approach.

A basic design problem and its solution

Shubho: Let's consider the following scenario:
Our room has some electric equipments (lights, fans etc). The equipments are arranged in a way where they could be controlled by switches. At any time, you can replace or troubleshoot an electrical equipment without touching the other things. For example, you can replace a light with another without replacing or changing the switch. Also, you can replace a switch or troubleshoot it without touching or changing the corresponding light or fan; you can even connect the light with the fan's switch and connect the fan with the light's switch, without touching the switches.

Electrical equipments: A fan and a light.

Two different switches for fan and light, one is normal and the other is fancy.
Farhana: Yes, but that's natural, right?
Shubho: Yes, that's very natural, and that's how the arrangement should be. When different things are connected together, they should be connected in a way where change or replacement of one system doesn't affect another, or even if there is any effect, it stays minimal. This allows you to manage your system easily and at low cost. Just imagine if changing the light in your room requires you to change the switch also. Would you care to purchase and set up such a system in your house?
Farhana: Definitely no.
Shubho: Now, let's think how the lights or fans are connected with the switches so that changing one doesn't have any impact on the other. What do you think?
Farhana: The wire, of course!
Shubho: Perfect. It's the wire and the electrical arrangement that connect the lights/fans with the switches. We can generalize it as a bridge between the different systems that can get connected through it. The basic idea is, things shouldn't be directly connected with one another. Rather, they should be connected though some bridges or interfaces. That's what we call "loose coupling" in software world.
Farhana: I see. I got the idea.
Shubho: Now, let's try to understand some key issues in the light/fan and switch analogy, and try to understand how they are designed and connected.
Farhana: OK, let me try.
We have switches in our example. There may be some specific kinds of switches like normal switches, fancy ones, but, in general, they are switches. And, each switch can be turned on and off.
So, we will have a base Switch class as follows:
public class Switch
{
  public void On()
  { 
    //Switch has an on button
  }
  public void Off()
  {
    //Switch has an off button
  }
}
And, as we may have some specific kinds of switches, for example a fancy switch, a normal switch etc., we will also have FancySwitch and NormalSwitch classes extending the Switch class:
public class NormalSwitch : Switch
{
}

public class FancySwitch : Switch
{
}
These two specific switch classes may have their own specific features and behaviours, but for now, let's keep them simple.
Shubho: Cool. Now, what about fan and light?
Farhana: Let me try. I learned from the Open Closed principles from Object Oriented Design principles that we should try to do abstractions whenever possible, right?
Shubho: Right.
Farhana: Unlike switches, fan and light are two different things. For switches, we were able to use a base Switch class, but as fan and light are two different things, instead of defining a base class, an interface might be more appropriate. In general, they are all electrical equipments. So, we can define an interface, say, IElectricalEquipment, for abstracting fans and lights, right?
Shubho: Right.
Farhana: OK, each electrical equipment has some common functionality. They could all be turned on or off. So the interface may be as follows:
public interface IElectricalEquipment
{
    void PowerOn(); //Each electrical equipment can be turned on
    void PowerOff(); //Each electrical equipment can be turned off
}
Shubho: Great. You are getting good at abstracting things. Now, we need a bridge. In real world, the wires are the bridges. But, in our object design, a switch knows how to turn on or off an electrical equipment, and the electrical equipment somehow needs to be connected with the switches, As we don't have any wire here, the only way to let the electrical equipment be connected with the switch is encapsulation.
Farhana: Yes, but switches don't know the fans or lights directly. A switch actually knows about an electrical equipment IElectricalEquipment that it can turn on or off. So, that means, an ISwitch should have an IElectricalEquipment instance, right?
Shubho: Right. Here, the encapsulated instance, which is an abstraction of fan or light (IElectricalEquipment) is the bridge. So, let's modify the Switch class to encapsulate an electrical equipment:
public class Switch
{
  public IElectricalEquipment equipment
  {
    get;
    set;
  }
  public void On()
  {
    //Switch has an on button
  }
  public void Off()
  {
    //Switch has an off button
  }
}
Farhana: Understood. Let me try to define the actual electrical equipments, the fan and the light. As I see, these are electrical equipments in general, so these would simply implement the IElectricalEquipment interface.
Following is the Fan class:
public class Fan : IElectricalEquipment
{
  public void PowerOn()
  {
    Console.WriteLine("Fan is on");
  }
  public void PowerOff()
  {
    Console.WriteLine("Fan is off");
  }
}
And, the Fan class would be as follows:
public class Light : IElectricalEquipment
{
  public void PowerOn()
  {    
    Console.WriteLine("Light is on");
  }
  public void PowerOff()
  {
    Console.WriteLine("Light is off");
  }
}
Shubho: Great. Now, let's make switches work. The switches should have the ability inside them to turn on and turn off the electrical equipment (it is connected to) when the switch is turned on and off.
These are the key issues:
  • When the On button is pressed on the switch, the electrical equipment connected to it should be turned on.
  • When the Off button is pressed on the switch, the electrical equipment connected to it should be turned off.
Basically, following is what we want to achieve:
static void Main(string[] args)
{
  //We have some electrical equipments, say Fan, Light etc.
  //So, lets create them first.

  IElectricalEquipment fan = new Fan();
  IElectricalEquipment light = new Light();

  //We also have some switches. Lets create them too.

  Switch fancySwitch = new FancySwitch();
  Switch normalSwitch = new NormalSwitch();

  //Lets connect the Fan to the fancy switch

  fancySwitch.equipment = fan;

  //As the switch now has an equipment (Fan),
  //so switching on or off should 
  //turn on or off the electrical equipment  

  fancySwitch.On(); //It should turn on the Fan. 

  //so, inside the On() method of Switch,  
  //we must turn on the electrical equipment.
    
  //It should turn off the Fan. So, inside the On() method of  
  fancySwitch.Off();
  //Switch, we must turn off the electrical equipment

  //Now, lets plug the light to the fancy switch

  fancySwitch.equipment = light;
  fancySwitch.On(); //It should turn on the Light now
  fancySwitch.Off(); //It should be turn off the Light now
}
Farhana: I got it. So, the On() method of the actual switches should internally call the TurnOn() method of the electrical equipment, and the Off() should call the TurnOff() method on the equipment. So, the Switch class should be as follows:
public class Switch
{
  public void On()
  {
    Console.WriteLine("Switch on the equipment");
    equipment.PowerOn();
  }
  public void Off()
  {
    Console.WriteLine("Switch off the equipment");
    equipment.PowerOff();
  }
}
Shubho: Great work. Now, this certainly allows you to plug a fan from one switch to another. But you see, the opposite should also work. That means, you can change the switch of a fan or light without touching the fan or light. For example, you can easily change the switch of the light from FancySwitch to NormalSwitch as follows:
normalSwitch .equipment = light;
normalSwitch.On(); //It should turn on the Light now
normalSwitch.Off(); //It should be turn off the Light now
So, you see, you can vary both the switches and the electrical equipments without any effect on the other, and connecting an abstraction of the electrical equipment with a switch (via encapsulation) is letting you do that. This design looks elegant and good. The Gang of Four has named this a pattern: The Bridge Pattern.
Farhana: Cool. I think I've understood the idea. Basically, two systems shouldn't be connected or dependent on another directly. Rather, they should be connected or dependent via abstraction (as the Dependency Inversion principle and the Open-Closed principle say) so that they are loosely coupled, and thus we are able to change our implementation when required without much effect on the other part of the system.
Shubho: You got it perfect darling. Let's see how the Bridge Pattern is defined:

"Decouple an abstraction from its implementation so that the two can vary independently"

You will see that our design perfectly matches the definition. If you have a class designer (in Visual Studio, you can do that, and other modern IDEs should also support this feature), you will see that you have a class diagram similar to the following:

Class diagram of Bridge pattern.
Here, Abstraction is the base Switch class. RefinedAbstraction is the specific switch classes (FancySwitch, NormalSwitch etc.). Implementor is the IElectricalEquipment interface. ConcreteImplementorA and ConcreteImplementorB are the Fan and Light classes.
Farhana: Let me ask you a question, just curious. There are many other patterns as you said, why did you start with the Bridge pattern? Any important reason?
Shubho: A very good question. Yes, I started with the Bridge pattern and not any other pattern (unlike many others) because of a reason. I believe the Bridge pattern is the base of all Object Oriented Design Patterns. You see:
  • It teaches how to think abstract, which is the key concept of all Object Oriented Design Patterns.
  • It implements the basic OOD principles.
  • It is easy to understand.
  • If this pattern is understood correctly, learning other Design Patterns becomes easy.
Farhana: Do you think I have understood it correctly?
Shubho: I think you have understood it perfectly darling.
Farhana: So, what's next?
Shubho: By understanding the Bridge pattern, we have just started to understand the concepts of Design Patterns. In our next conversation, we would learn other Design Patterns, and I hope you won't get bored learning them.
Farhana: I won't. Believe me.

 

Friday, May 25, 2012

1.7 Threads and Multithreading

The Thread Scheduler

The thread scheduler is the part of the JVM that decides which thread should run at any given moment, and also takes threads out of the run state. Assuming a single processor machine, only one thread can actually run at a time. Only one stack can ever be executing at one time. And it’s the thread scheduler that decides which thread among all other eligible threads will actually run. When I say eligible, it means threads that are in the runnable state.

Any thread in the runnable state can be chosen by the scheduler to be the one and only running thread. If a thread is not in a runnable state, then it cannot be chosen to be the currently running thread. And, to repeat something I have already said:


THE ORDER IN WHICH RUNNABLE THREADS ARE CHOSEN TO RUN IS NOT AND I MEAN IS NOT GUARANTEED!


Although we don’t control the thread scheduler, we can sometimes influence it. The following methods give us some tools for influencing the scheduler. Just don’t ever mistake influence for control.



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)

Note that both sleep() and join() have overloaded versions which not shown here.

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()

The wait() method has three overloaded versions (including the one listed here).

Don't worry too much about the functionalities of these methods because we are going to have a full chapter dedicated to these babies.

For now, the chapter is over. You can give a sigh of relief which is exactly what I am doing now.. Huh!!!

1.6 Threads and Multithreading

Each thread will start, and each thread will run to completion.


Within each thread, things will happen in a predictable order. But the actions of different threads can mix together in unpredictable ways. If you run the program multiple times, or on multiple machines, you may see different output. Even if you don’t see different output, you need to realize that the behavior you see is not guaranteed. Sometimes a little change in the way the program is run will cause a difference to emerge. Just for fun we bumped up the loop code so that each run() method ran the for loop 400 times rather than 3, and eventually we did start to see some wobbling:




public void run() {

for (int x = 1; x <= 400; x++) {
System.out.println("Run by "

+ Thread.currentThread().getName()

+ ", x is " + x);

}

}



Running the preceding code, with each thread executing its run loop 400 times, started out fine but then became nonlinear. Here’s just a snip from the command-line output of running that code:

Run by Rocky, x is 345

Run by Triple H, x is 313

Run by Cena, x is 341

Run by Triple H, x is 314

Run by Cena, x is 342

Run by Triple H, x is 315

Run by Rocky, x is 346

Run by Cena, x is 343

Run by Rocky, x is 347

Run by Cena, x is 344

And so on…


Notice that there’s not really any clear pattern here. If we look at only the output from Rocky, we see the numbers increasing one at a time, as expected:

Run by Rocky, x is 345

Run by Rocky, x is 346

Run by Rocky, x is 347



And similarly if we look only at the output from Cena, or Triple H. Each one individually is behaving in a nice orderly manner. But together, it is utter chaos! In the fragment above we see Rocky, then Cena, then Triple H (in the same order we originally started the threads), but then Cena moves in when it was Rocky’s turn. And then Triple H and Cena trade back and forth for a while until finally Rocky gets another chance. They jump around like this for a while after this. Eventually (after the part shown above) Rocky finishes, then Triple H, and finally Cena finishes with a long sequence of output. So even though Triple H was started third, he actually completed second. And if we run it again, we’ll get a different result.


Why?


Because it’s up to the scheduler, and we don’t control the scheduler! Which brings up another key point to remember: 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.


A thread is no longer a thread when its run() method completes execution.


When a thread completes its run() method, the thread ceases to be a thread of execution. The stack for that thread dissolves, and the thread is considered dead. Not dead and gone, but, just dead. It’s still a Thread object, just not a thread of execution. So if you’ve got a reference to a Thread instance, then even when that Thread instance is no longer a thread of execution, you can still call methods on the Thread instance, just like any other Java object. What you can’t do, though, is call start() again.


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, but you don’t need to worry about catching it). This happens whether or not the run() method has completed from the first start() call. Only a new thread can be started, and then only once. A runnable thread or a dead thread cannot be restarted.

1.5 Threads and Multithreading

Starting and Running Multiple Threads


Let’s actually get down to business and get multiple threads going (more than two, that is). We already had two threads, because the main() method starts in a thread of its own, and then t.start() started a second thread. Now we’ll do more. The following code creates a single Runnable instance and three Thread instances. All three Thread instances get the same Runnable instance, and each thread is given a unique name. Finally, all three threads are started by invoking start() on the Thread instances.



class TestRunnableWithNames implements Runnable {

public void run() {

for (int x = 1; x <= 3; x++) {
System.out.println("Run by "

+ Thread.currentThread().getName()

+ ", x is " + x);

}

}

}

public class ManyNames {

public static void main(String [] args) {

// Make one Runnable

TestRunnableWithNames nr = new TestRunnableWithNames();

Thread one = new Thread(nr);

Thread two = new Thread(nr);

Thread three = new Thread(nr);



one.setName("Rocky");

two.setName("Cena");

three.setName("Triple H");

one.start();

two.start();

three.start();

}

}

Running this code might produce the following:



% java ManyNames

Run by Rocky, x is 1

Run by Triple H, x is 1

Run by Rocky, x is 2

Run by Cena, x is 1

Run by Rocky, x is 3

Run by Cena, x is 2

Run by Cena, x is 3

Run by Triple H, x is 2

Run by Triple H, x is 3



Well, at least that’s what it printed when we ran it—this time, on our machine. But the behavior you see above is not guaranteed. I repeat, “THE BEHAVIOR IS NOT GUARANTEED.” You need to know, for your future as a Java programmer as well as for the exam, that there is nothing in the Java specification that says threads will start running in the order in which they were started (in other words, the order in which start() was invoked on each thread). And there is no guarantee that once a thread starts executing, it will keep executing until it’s done. Or that a loop will complete before another thread begins. Nothing is guaranteed in the preceding code except this:

1.4 Threads and Multithreading

Starting a Thread

You’ve created a Thread object and it knows its target. Now it’s time to get the whole thread thing running. It’s pretty straight forward:
t.start();

Prior to calling start() on a Thread instance, the thread (when we use lowercase t, we’re referring to the thread of execution rather than the Thread class) is said to be in the new state as we said. The new state means you have a Thread object but you don’t yet have a true thread. So what happens after you call start()?

• 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.

Be sure you remember the following: You start a Thread, not a Runnable. You call start() on a Thread instance, not on a Runnable instance. The following example demonstrates what we’ve covered so far—defining, instantiating, and starting a thread:



class TestRunnable implements Runnable {

public void run() {

for(int x = 1; x < 6; x++) {
System.out.println("Runnable running");

}

}

}



public class TestMyThreads {

public static void main (String [] args) {

TestRunnable r = new TestRunnable();

Thread t = new Thread(r);

t.start();

}

}



Running the preceding code prints out exactly what you’d expect:

% java TestMyThreads

Runnable running

Runnable running

Runnable running

Runnable running

Runnable running






So what happens if we start multiple threads? We’ll run a simple example in a moment, but first we need to know how to print out which thread is executing. We can use the getName() method of class Thread, and have each Runnable print out the name of the thread executing that Runnable object’s run() method. The following example instantiates a thread and gives it a name, and then the name is printed out from the run() method:

class TestRunnableWithNames implements Runnable {
public void run() {
System.out.println("TestRunnableWithNames running");
System.out.println("Run by "
+ Thread.currentThread().getName());
}
}
public class NameThread {
public static void main (String [] args) {
TestRunnableWithNames nr = new TestRunnableWithNames();
Thread t = new Thread(nr);
t.setName("Rocky");
t.start();
}
}

Running this code produces the following, extra special, output:

% java NameThread
TestRunnableWithNames running
Run by Rocky

To get the name of a thread you call 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.

Even if you don’t explicitly name a thread, it still has a name. Let’s look at the previous code, commenting out the statement that sets the thread’s name:

public class NameThread {
public static void main (String [] args) {
TestRunnableWithNames nr = new TestRunnableWithNames();
Thread t = new Thread(nr);
// t.setName("Rocky");
t.start();
}
}
Running the preceding code now gives us
% java NameThread
TestRunnableWithNames running
Run by Thread-0

And since we’re getting the name of the current thread by using the static Thread.currentThread() method, we can even get the name of the thread running our main code,
public class NameThreadTwo {
public static void main (String [] args) {
System.out.println("thread is "
+ Thread.currentThread().getName());
}
}

which prints out
% java NameThreadTwo
thread is main

That’s right, the main thread already has a name—main.


1.3 Threads and Multithreading

Implementing java.lang.Runnable

Implementing the Runnable interface gives you a way to extend any class you like, but still define behavior that will be run by a separate thread. It looks like this:

class MyFirstRunnableClass implements Runnable {
public void run() {
System.out.println("Imp job running in MyFirstRunnableClass");
}
}
Regardless of which mechanism you choose, you’ve now got yourself some code that can be run by a thread of execution. So now let’s take a look at instantiating your thread-capable class, and then we’ll figure out how to actually get the thing running.

Instantiating a Thread

Remember, every thread of execution begins as an instance of class Thread. Regardless of whether your run() method is in a Thread subclass or a Runnable implementation class, you still need a Thread object to do the work.

If you extended the Thread class, instantiation is dead simple:
MyFirstThread t = new MyFirstThread()

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 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-a-thread code.

First, you instantiate your Runnable class:
MyFirstRunnableClass r = new MyFirstRunnableClass();

Next, you get yourself an instance of java.lang. Thread, and you give it your job!
Thread t = new Thread(r); // Pass your Runnable to the Thread

If you create a thread using the no-arg constructor, the thread will call its own run() method when it’s time to start working. That’s exactly what you want when you extend Thread, but when you use Runnable, you need to tell the new thread to use your run() method rather than its own. The Runnable you pass to the Thread constructor is called the target or the target Runnable.
You can pass a single Runnable instance to multiple Thread objects, so that the same Runnable becomes the target of multiple threads, as follows:

public class TestMyThreads {
public static void main (String [] args) {
MyFirstRunnableClass r = new MyFirstRunnableClass();
Thread aaa = new Thread(r);
Thread bbb = new Thread(r);
Thread ccc = new Thread(r);
}
}

Giving the same target to multiple threads means that several threads of execution will be running the very same job and that same job will be done multiple times.



Besides the no-arg constructor and the constructor that takes a Runnable (the target, i.e., the instance with the job to do), there are other overloaded constructors in class Thread. The constructors we care about are
• Thread()
• Thread(Runnable target)
• Thread(Runnable target, String name)
• Thread(String name)

You need to recognize all of them for the exam! Don't worry, we’ll discuss some of the other constructors in the preceding list a little later.

So now you’ve made yourself a Thread instance, and it knows which run() method to call. But nothing is happening yet. At this point, all we’ve got is a Java object of type Thread. It is not yet a thread of execution. To get an actual thread and a new call stack—we still have to start the thread.

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.

Note: The getState() method is very useful for debugging, but you won’t get any questions about it in the exam.
 

1.2 Threads and Multithreading

Creating a Thread

A thread in Java begins as an instance of java.lang.Thread. You’ll find methods in the Thread class for managing threads including creating, starting, and pausing them. They are:
start()
yield()
sleep()
run()

All the awesome action happens in the run() method. Think of the code you want to execute in a separate thread as the job to do. Lets say, you have some work that needs to be done, in the background while other things are happening in the program, so what you really want is that work to be executed in its own thread. All that code you want executed in a separate thread goes into the run() method.

Ex:
public void run() {
// your job code goes here
}

The run() method will call other methods, of course, but the thread of execution—the new call stack—always begins by invoking run(). So where does the run() method go? In one of the two classes you can use to define your thread job.

You can define and instantiate a thread in one of two ways:
• Extend the java.lang.Thread class.
• Implement the Runnable interface.

You need to know about both for the exam, although I would personally recommend that you implement Runnable than extend Thread. Extending the Thread class is the easiest, but it’s usually not a good OO practice.

Now, you may ask me “Why? Why should I choose the Runnable over Thread?”
Well, if you thought of the why before reading the preceding line, give yourself a pat on the back. Well done!

Because, if you extend the Thread class what would you do if you have to extend another concrete parent class that has vital/important behavior that you need in your class? Get the point? Java does not support direct multiple inheritance and hence, once you extend the Thread class, you are done, for good. You cannot extend any other class. That is why I recommended the Runnable interface. Even if you implement the interface, you are free to extend any class you want. Convenient, right?

Defining a Thread

To define a thread, you need a place to put your run() method, and as we just discussed, you can do that by extending the Thread class or by implementing the Runnable interface. We’ll look at both in this section.

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.
It looks like this:
class MyFirstThread extends Thread {
public void run() {
System.out.println("Important job running in MyFirstThread");
}
}
The limitation with this approach is that if you extend Thread, you can’t extend anything else. And it’s not as if you really need that inherited Thread class behavior, because in order to use a thread you’ll need to instantiate one anyway.

Keep in mind that you’re free to overload the run() method in your Thread subclass:
class MyFirstThread extends Thread {
public void run() {
System.out.println("Important job running in MyFirstThread");
}
public void run(String s) {
System.out.println("String running is " + s);
}
}

Note: 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 class 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.

1.1 Threads and Multithreading

This chapter and the subsequent ones on Threads and Multi-threading is probably by far the most complex topic we will be covering as part of our aim at getting a SCJP Certification.
Before we begin – let me put out a Disclaimer…


Disclaimer: This chapter makes almost no attempt to teach you how to design a good, safe, multithreaded application. The concepts covered in this article are just the tip of the iceberg and you’re here only to learn the basics of threading, and what you need to get through the thread questions on the exam. Before you can write decent multithreaded code, however, you really need to study more on the complexities and subtleties of multithreaded code.

In a single-threaded runtime environment, actions execute one after another. The next action can happen only when the previous one is finished. If task A takes half an hour, and the user wants to do something else, he is doomed to wait until task A is over.

Ideally, the user should be able to carry on with his other task until his first task is complete. Imagine having to wait till your eclipse build all your source code before you could check your email? Thankfully windows uses multiple threads to run your eclipse and outlook. So you don't have to go through this pain. Similarly java has options wherein the programmer can have multiple threads of execution running.

Now you are ready to dive into the magical or rather complicated world of threads.

Lets get started!!!

What is a Thread?

In Java, “thread” means:
• A thread of execution

A thread of execution is an individual 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. Even if you don’t create any new threads in your program, threads are there running without your knowledge.
If you are curious and ask me how? Just stop for a moment and think how you would execute a java program? You’ll write a main method and then execute it from the command line using the “java” command. Well, you have already answered the question because, when your main method starts, the JVM assigns a thread for this main method and assigns it a call stack. So, eventhough you did not intentionally create a thread, the system did one for you.

The most important concept to understand from this entire chapter is this:

When it comes to threads, very little is guaranteed.

So be very cautious about interpreting the behavior you see on one machine as “the way threads work.” The exam expects you to know what is and is not guaranteed behavior, so that you can design your program in such a way that it will work regardless of the underlying JVM.

NEXT

Creating a Thread

Creating a Thread is fairly simple. The complexities get introduced once you have your threads running and then you see that the output isn’t what you exactly expected. Well, I don’t want to jump ahead too much. We will learn all those complexities one by one. For now lets keep our focus on how to create threads.

You can create threads in two ways:

1. By Extending the Thread Class
2. By Implementing the Runnable Interface

Common sense related to Java Programming tells us that using the interface may be a better option because, your class may need to inherit features from its parent class or such a feature may be required in future. Either ways, it would be a better idea to implement the Runnable Interface so that our classes can do, what they were designed/created to do.

Saturday, April 7, 2012

understanding threads in java-what the heck is thread

A thread is an application task that is executed by a host computer. The notion of a task should be familiar to you even if the terminology is not.

Suppose you have a Java program to do some task:

public class DoSomething{
public static void main(String[] args) {
Task 1;
Task 2;
Task 3;

Task N;
}
}

When your computer runs this application, it executes a sequence of commands. At an abstract level, that list of commands looks like this:

• Do Task 1
• Do Task 2
• Continue on until you reach Task N
• Exit the Program

Behind the scenes, what happens is somewhat more complicated since the instructions that are executed are actually machine-level assembly instructions; each of our logical steps requires many machine instructions to execute. But the principle is the same: an application is executed as a series of instructions. The execution path of these instructions is a thread.

Consequently, every computer program has at least one thread: the thread that executes the body of the application. In a Java application, that thread is called the main thread, and it begins executing statements with the first statement of the main() method of your class. In other programming languages, the starting point may be different, and the terminology may be different, but the basic idea is the same.


Trivia:
For Java applications, execution begins with the main() method of the class being run. What about other Java programs?
In applets, servlets, and other J2EE programs, execution still begins with the main() method of the program, but in this case, the main() method belongs to the Java plug-in or J2EE container. Those containers then call your code through predetermined, well-known locations. An applet is called via its init() and start() methods; a servlet is called through its doGet() and doPost() methods, and so on.
In any case, the procedure is the same: execution of your code begins with the first statements and proceeds by a single thread sequentially.

In a Java program, it so happens that every program has more than one thread. Many of these are threads that developers are unaware of, such as threads that perform garbage collection and compile Java bytecodes into machine-level instructions. In a graphical application, other threads handle input from the mouse and keyboard and play audio. Your Java application is highly threaded, whether you program & code additional threads into it or not.

Returning to our example, let's suppose that we wrote a program that performed two tasks: one calculated the factorial of a number and one calculated the square root of that number. These are two separate tasks, and so you could choose to write them as two separate threads. Now how would your application run?

The answer to that depends on the conditions under which the application is run. The Java virtual machine now has two distinct lists of instructions to execute. One list calculates the factorial of a number, and the other list calculates the square root of the number. The Java virtual machine executes both of these lists almost simultaneously.

Although you may not have thought about it in these terms, this situation should also be familiar to you from the computer on which you normally do your work. The program you use to read your email is a list of instructions that the computer executes. So too is the program that you use to listen to music. You're able to read email and listen to music at the same time because the computer executes both lists of instructions at about the same time.

In fact, what happens is that the computer executes a handful of instructions from the email application and then executes a handful of instructions from the music program. It continues this procedure, switching back and forth between lists of instructions, and it does that quickly enough so that both programs appear to be executing at the same time. Quickly enough, in fact, that there are no gaps in the music.

If you happen to have more than one CPU on your computer, the lists of instructions can execute at exactly the same time: one list can execute on each CPU. But multiple CPUs aren't necessary to give the appearance of simultaneous execution or to exploit the power of threading. A single CPU can appear to execute both lists of instructions in parallel, letting you read your email and listen to music simultaneously.

Threads behave exactly the same way. In our case, the Java virtual machine executes a handful of the instructions to calculate the factorial and then executes a handful of instructions to calculate the square root, and so on.

So threads are simply tasks that you want to execute at roughly the same time. Why, then, write an application with multiple threads? Why not just write multiple applications? The answer lies in the fact that because threads are running in the same application, they share the same memory space in the computer. This allows them to share information seamlessly. Your email program and your music application don't communicate very well. At best, you can copy and paste some data (like the name of a file) between the two. That allows you to double-click on an MP3 attachment in your email and play it in your music application, but the only information that is shared between the two is the name of the MP3 file.

In a multitasking environment, data in the programs is separated by default: each has its own stack for local variables, and each has its own area for objects and other data. All the programs can access various types of shared memory (including the name of the MP3 file that you clicked on in your email program). The shared memory is restricted to information put there by other programs, and the APIs to access it are usually quite different than the APIs used to access other data in the program.

This type of data sharing is fine for dissimilar programs, but it is inadequate for other programs that need to communicate with one another. Consider a network server that sends stock quotes to multiple clients. Sending a quote to a client is a discrete task and may be done in a separate thread. In fact, if the client must acknowledge the quote, then sending the data in separate threads is highly recommended: you don't want all clients to wait for a particularly slow client to respond. Here the data to be sent to the clients is the same; you don't want each client to require a separate server process which must then replicate all the data held by every other server process. Instead, you want multiple threads in one program so that they may share data and each perform discrete tasks on that data.

Conceptually, the threads seem to be the same as programs. The key difference here is that the global memory is the entire Java heap: threads can transparently share access between any object in the heap. Each thread still has its own space for local variables (variables specific to the method the thread is executing). But objects are shared automatically and transparently.

A thread, then, is a discrete task that operates on data shared with other threads.

understanding threads in java-Intoroduction

Threads are an important and interesting aspect of the Java Programming Language. If you are an experienced Java Programmer, you are invariably expected to know the intricacies of multi-threading. Well, this series of chapters is aimed at helping you understand this interesting and complicated concept.

So, lets get started!!!

Why Use Threads?

The notion of threading is so ingrained in Java that it's almost impossible to write even the simplest programs in Java without creating and using threads. And many of the classes in the Java API are already threaded, so often you are using multiple threads without realizing it.


The biggest question you might have is “Why use Threads?”

Well, my friend, it is not so simple to explain the reason in a couple of lines. Maybe a 100 page thesis would sound more appropriate. But still, am gonna try explaining in a short and concise manner.

First and foremost – threads increase performance. Given the processing power of the modern day processors, irrespective of how much code you write, the processor is going to finish running them in a jiffy and will remain underutilized almost 99% or more times. By creating multiple threads in your program, you are trying to utilize the processor effectively trying to keep it as little time as possible “idle”

Some of the significant reasons for using Threads are explained in the subsequent sections of this article.

Nonblocking I/O

In Java, as in most programming languages, when you try to get input from the user, you execute a read() method specifying the user's terminal (System.in in Java). When the program executes the read() method, the program typically waits until the user types at least one character before it continues and executes the next statement. This type of I/O is called blocking I/O : the program blocks until some data is available to satisfy the read() method.

This type of behavior is often undesirable. If you're reading data from a network socket, that data is often not available when you want to read it: the data may have been delayed in transit over the network, or you may be reading from a network server that sends data only periodically. If the program blocks when it tries to read from the socket, it's unable to do anything else until the data is actually available. If the program has a user interface that contains a button and the user presses the button while the program is executing the read() method, nothing happens: the program is unable to handle the mouse events and execute the event processing method associated with the button. This can be very frustrating for the user, who thinks the program has hung.

This kind of situation is where Threads in Java look the most promising solution.

Independent Tasks

A Java program is often called on to perform independent tasks. In the simplest case, a single applet may perform two independent animations for a web page. A more complex program would be a calculation server that performs calculations on behalf of several clients simultaneously. In either case, while it is possible to write a single-threaded program to perform multiple tasks, it's easier and more elegant to place each task in its own thread.

Parallelizable Algorithms

With the advent of virtual machines that can use multiple CPUs simultaneously, Java has become a useful platform for developing programs that use algorithms that can be parallelized; that is, running one iteration of the loop on one CPU while another iteration of the loop is simultaneously running on another CPU. Dependencies between the data that each iteration of the loop needs may prohibit a particular loop from being parallelized, and there may be other reasons why a loop should not be parallelized. But for many programs with CPU-intensive loops, parallelizing the loop greatly speeds up the execution of the program when it is run on a machine with multiple processors.

Now that we know why and how threads are useful for us as programmers, lets dig deep into the magical world of Threads!!!

java-8-streams-map-examples

package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; im...