Saturday, March 22, 2008

why Swing is not thread safe and AWT is

Simple answer is - "that's the design choice the Swing team made". It is a well-known fact that writing thread safe API/library is more difficult and inefficient.
So to simplify the implementation of Swing library they chose it to be not thread safe. The argument being that most of the GUI related work happens in the callbacks from the GUI which happen on the single GUI thread anyways. Granted - for long running tasks the user will have to do more work if he/she wants to do multithreaded activity. Not making Swing thread safe allowed them to implement the Swing which covered a lot more ground (new controls, layouts, keyboard actions, layered pane etc) in a short amount of time.

It is not that bad though - Swing does provide a mechanism to deal with the issues of threading -

javax.swing.SwingUtilities.invokeLater(Runnable ...);
javax.swing.SwingUtilities.invokeAndWait(Runnable ...);
javax.swing.JProgressBar class
javax.swing.ProgressMonitor
javax.swing.ProgressMonitorInputStream
SwingWorker
For more explaination of why they made that decision please see the following URLs:

http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html
http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html
http://java.sun.com/products/jfc/tsc/articles/threads/threads3.html
The AWT is based on the OS's WIndowing System's peer objects which are inherently thread safe. That is why AWT is thread safe.

One can argue though that they should have provided factory methods (similar to collections framework) or subclasses to get thread safe versions of the Swing classes - for example, TSJTextField or TSJTree where the "TS" stands for 'thread safe'

Friday, March 21, 2008

Synchronized Multithreading with Swing

For some people, hearing the word "thread" brings to mind spiders, or else other creeping things which can be seen on dark nights when one is coding alone in the office. However, this should not be the case, for in a Java program threads are your friend, and perhaps unbeknownst to you, they have been aiding your adventures from the first time you used the Swing library.

Before we slide down into a possible tangle of multiple threads, remember that one should not begin creating threads without a good purpose, for they are complex and need to be completely thought through before being used. When you are creating threaded code, keep it as simple as possible, for any complexity you introduce will surely lead you into some sticky situations like a moth who gets trapped forever in a deadlocked situation.

You may be surprised to find out that Swing already uses multiple threads. "How is this possible?" you might ask. "I have never implemented a Runnable interface nor extended Thread in my years of using Swing." Swing utilizes something called the event dispatch thread which operates behind the scenes. This thread is responsible for handling system events, such as when a user clicks the mouse button or when a Swing timer goes off. Fortunately, event handling code automatically executes in the event dispatch thread, so all of your callbacks are already taking place on this thread. When the user clicks on one of your controls, the event is handled by the event dispatch thread and your code that responds to this event is executed on this separate thread.

Try running this example which shows the name of the thread in the label on the left. Source Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ThreadDemo extends JFrame {
JLabel label;

public ThreadDemo() {
super("Thread Demo");
setSize(300,50);

this.getContentPane().setLayout(new GridLayout(1,2));

label = new JLabel();
label.setText(Thread.currentThread().getName());
this.getContentPane().add(label);

JButton button = new JButton();
button.setText("Get Thread");

ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText(Thread.currentThread().getName());
}
};

button.addActionListener(listener);
this.getContentPane().add(button);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String args[]) {
new ThreadDemo();
}
}




The first time the call Thread.currentThread().getName() is invoked, it is in the thread named "main", because the label is created within the main thread. However, within the ActionListener which is invoked when you press the on screen button the thread name is "AWT-EventQueue-0". The actionPerformed call is invoked when you click the mouse button, which is handled in the event dispatch thread. You can use this technique of checking the thread name to ensure any code you are writing is actually being run in the event dispatch thread.

One of the fortunate things about the fact that events are handled automatically on the event dispatch thread is that Swing is not thread safe and you must modify any realized GUI components from within the event dispatch thread. Thus, the difficult and dangerous task of keeping Swing thread-safe is happening by default for your event handling code, and is already taking place within this context. You could imagine if a separate thread began modifying a combo box at the same moment a user chose that combo box and started scrolling through it. The technical term for such a confluence of events is "uh oh". In the worst case, not only will data integrity be compromised, but the entire application will lock up, and the hours of work the user has spent using your application will vanish into a cloud of smoke coming out of his or her ears.

Historically there has been one mighty exception to the rule that you must modify any GUI components from within the event dispatch thread; that was at startup. It had been considered safe to create the GUI in the application's main thread provided no GUI components were visible. This is the way most programs are written, and is likely to be safe, but now as you can see the official way to ensure complete safety is to now also create the GUI itself within the event dispatch thread. This will ensure you have no lockup at startup.

There are two methods for invoking code inside the event dispatch thread when you are not already in that thread: invokeLater and invokeAndWait. The invokeLater is utilized by passing in a Runnable interface object with a run method which executes at a later time on the event dispatch thread. The invokeAndWait operates in the same way, but does not return until the event dispatch thread has finished executing the code. When you create these Runnable objects and pass them to the invoke methods, they are executed on the event dispatch thread.

Below is the code to replace the main method coded above with the creation of the GUI taking place on the event dispatch thread. An anonymous class is created with the Runnable interface which calls the new ThreadDemo(); to create the GUI. As you can tell if you run the modified code, the creation of the label now takes place on the event dispatch thread. Source Code
public static void main(String args[]) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ThreadDemo();
}
});
}




Using other threads
If you have ever used an application and wondered "What the heck is taking so long here?" you have encountered a reason to use multiple threads. The user is in charge of your application, and as soon as you wander off with the event dispatch thread with an extremely slow piece of code, your user has lost control. The application will appear to hang, since no other mouse or keyboard events can be handled as long as the event dispatch thread is busy.

For this sample application we will compute the value of P using perhaps the slowest algorithm possible. Since P is an irrational number, a complete implementation could take forever to complete. In case the user is not willing to wait forever, we will utilize multiple threads: one thread to compute the value of P, and the other default event dispatch thread to keep the user informed of what we think P is at the moment. For this example we store the approximated value of pi in a double.

As an aside, the way we are computing P here is by throwing random darts that hit a square with a quarter of a circle inscribed in it. The ratio of darts which fall within the circle to the total number of darts thrown gives a way to approximate P. The square is 1 unit across, and the circle has a radius of 1 unit. The complete circle has an area of P * radius * radius so the quarter circle has an area of P / 4. Thus P is approximately equal to 4 * the number of circle quadrant hits divided by the number of throws.




P is roughly equal to the 4 * number of green dots / (number of green dots + red dots).
Since this is random, there is no guarantee we will converge on P- all of the darts may well fall into the circle quadrant and it will appear P is very close to 4.0. In reality the most significant digits of PI will be calculated fairly quickly and it will take a very long time to find additional significant digits. This is useful, however, as an example utilizing concurrent threading with Swing. Source Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CalculatePi extends JFrame {
JLabel label;
volatile double pi = 0;

synchronized void setPi(double value) {
pi = value;
}

synchronized double getPi() {
return pi;
}

class ThrowDarts implements Runnable {

public void run() {

long counter = 0;
long hits = 0;
double x = 0;
double y = 0;

while (counter < Long.MAX_VALUE)
{
counter++;
x = Math.random();
y = Math.random();
if (Math.sqrt(x*x + y*y) < 1.0f)
{
hits++;
}

setPi(4 * (double) hits / (double) counter);

if (counter%1000 == 0)
{
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
label.setText("" + getPi());
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
}

public CalculatePi() {

super("Throwing Darts");
setSize(300,50);

label = new JLabel();
label.setText(Thread.currentThread().getName());
this.getContentPane().add(label);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);

ThrowDarts dartThrower = new ThrowDarts();
Thread t = new Thread(dartThrower);
t.start();
}

public static void main(String args[]) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CalculatePi();
}
});
}
}




Notice that the variable pi is declared to be volatile. This tells the compiler not to place the value of pi into any registers so that it can be accessed from any thread. To guarantee that any accesses to the value of pi are atomic, that is taking place in a single operation, both set and get methods exist with the keyword synchronized to make sure that these operations complete fully before any other thread executes. The code that runs within these synchronized methods will be mutually exclusive; both of these methods can not be executed at once by different threads. Depending on the Java Virtual Machine implementation potentially half of the bytes of pi could be accessed when the other thread changes the value.

At regular intervals, whenever the counter is a multiple of 1000, an anonymous class implementing Runnable is created that updates the label. It is passed to invokeAndWait which will wait for the event dispatch thread to return before processing further. In this way, the update to the label that shows pi takes place on the event dispatch thread.

The invokeAndWait will wait for the event dispatch thread to return before computing more, thus preventing us from adding too many Runnable objects on the event dispatch thread. Do not create too many Runnable objects on the event dispatch thread or the thread can get bogged down. An alternative technique would be to utilize a timer to periodically update the label.

In the main method of the program, the interface is created on the event dispatch thread with its own anonymous instantiation of the Runnable interface.

Parting ideas
There are some methods which are thread safe within the Swing component hierarchy. They will be marked in the documentation as "This method is thread safe".

In summary, there is no need to create separate threads for the general Swing application, although you are advised to instantiate your GUI on the event dispatch thread. All of your event handling code will take place on the event dispatch thread by default. If you are doing something advanced that does require multiple threads, be sure to make it thread safe and manipulate Swing components from within the event dispatch thread. Java Virtual Machine implementations of threading are not consistent so code that works in your test environment may fail elsewhere unless you are careful. Unless the documentation explicitly states that methods are thread safe, you should assume that they are not.

Tuesday, March 18, 2008

Successful Trading

Successful Trading = (Knowledge + Experience + Discipline) * Luck.

Sunday, March 16, 2008

Factory v/s Facade Design Pattern.

The Factory Pattern :

--------------------------------------------------------------------------------
The factory completely abstracts the creation and initialization of the product from the client
This indirection enables the client to focus on its discrete role in the application without concerning itself with the details of how the product is created. Thus, as the product implementation changes over time, the client remains unchanged.

Client--------------------->Factory----------------->Product


The Facade Pattern



--------------------------------------------------------------------------------
Encapsulate the subsystem using a High-Level Interface/provides a
simplified and uniform interface to a large subsytem of classes.

The Client communicates with the 'Facade' which has methods to interact
with subsystems.The Client very rarely accesses objects in the subsystems.
Subsystems objects usually retain no knowledge of the client.
Subsystem objects do not normally maintain any reference to Faýade.

Client------------------->Facade------->Subsystems


My Question is this:

Arent both these pattern quite similar becos both designs access an Interface
which inturn invokes the required object of the subsystems?

Can anyone explain the major difference?

1. the Factory Pattern, is very useful for the creation of
the objects which it then hands to you and you deal with
the objects directly.

The Facade pattern, tries to simplify things for you, as
it keeps the objects away from you. This simplifies your
life if you are dealing with several complex objects.

2.Faýade
The Faýade pattern simplifies access to a related set of objects by providing one object that all objects outside the set use to communicate
with the set. This also promotes a weak coupling between the subsystem and its clients. This weak coupling allows you to vary the
components of the subsystem without affecting the clients.

Factory
Centralize the assembly of resources necessary to create an object. This prevents the need to change all classes from changing when a
Product changes and makes any change needed occur only in the Factory.

Structural Patterns - Facade Pattern

Overview
This article provides a brief introduction to Facade Design Patterns. Facade Design pattern provides an easy to use interface to an otherwise complicated collection of interfaces or subsystems. It makes things easier by hiding the details of the implementation.

When designing good programs, programmers usually attempt to avoid excess coupling between module/classes. Using this pattern helps to simplify much of the interfacing that makes large amounts of coupling complex to use and difficult to understand.

In a nutshell, this is accomplished by creating a small collection of classes that have a single class (Facade) that is used to access them.

The facade pattern is an object-oriented design pattern. A facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can accomplish all of the following.

It can make a software library easier to use and understand since the facade has convenient methods for common tasks.
It makes code that uses the library more readable for the same reason.
It can reduce dependencies of outside code on the inner workings of a library since most code uses the facade. This allows for more flexibility in developing the system.
It can wrap a poorly designed collection of APIs with a single well-designed API.
The following Non-software and software examples demonstrate this pattern.

Non-Software examples
In most of the Pizza centers, orders will be given through phone calls with the customer interacting with the Customer service representative. In this case, consumers do not have access to the Billing system, Kitchen and delivery department. The customer service representative acts as an interface and interacts with each of the departments involved in the transaction and ensures that Pizzas are delivered to the consumer.

We can relate this non-software example against the facade design pattern in the following way:

Customer Service representative corresponds to the facade.
Individual departments involved in the transaction correspond to Sub-systems.
Another example we can consider is Emergency services. In the event of fire we just inform an Emergency Service operator. The emergency operator interacts with police, ambulance and fire services and dispatches them. Here the client is shielded from individual emergency services.

Software examples
Web Service Facade Solution Architecture provides an example for Facade design pattern. In this architectural solution, instead of rewriting legacy applications or customizing those with middleware to connect to other applications one by one, this solution helps create a "facade" for the legacy application. Other applications are easily "plugged into" this facade. By modeling a legacy application into its basic functions of create, read, update, and delete and then exposing these functions as Web methods, the Web service facade solution allows other applications to access legacy data by making use of common Web services through standardized protocols. In this way, Facade decouples layers so that they do not depend on each other which can make it easier to develop, to use and to promote code re-use.

Facade as the name suggests means the face of the building. The people walking past the road can only see this glass face of the building. They do not know anything about it, the wiring, the pipes and other complexities. The face hides all the complexities of the building and displays a friendly face.

This is how facade pattern is used. It hides the complexities of the system and provides an interface to the client from where the client can access the system. In Java, the interface JDBC can be called a facade. We as users or clients create connection using the “java.sql.Connection” interface, the implementation of which we are not concerned about. The implementation is left to the vendor of driver.

Definition
Make a complex system simpler by providing a unified or general interface, which is a higher layer to these subsystems.

Where to use & benefits
Want to reduce complexities of a system.
Decouple subsystems , reduce its dependency, and improve portability.
Make an entry point to your subsystems.
Minimize the communication and dependency between subsystems.
Security and performance consideration.
Shield clients from subsystem components.
Simplify generosity to specification.

Related patterns include
Abstract Factory, which is often used to create an interface for a subsystem in an independent way, and can be used as an alternative way to a facade.
Singleton, which is often used with a facade.
Mediator, which is similar to facade, but a facade doesn't define new functionality to the subsystem.

Example
JDBC design is a good example of Façade pattern. A database design is complicated. JDBC is used to connect the database and manipulate data without exposing details to the clients.

Security of a system may be designed with Façade pattern. Clients' authorization to access information may be classified. General users may be allowed to access general information; special guests may be allowed to access more information; administrators and executives may be allowed to access the most important information. These subsystems may be generalized by one interface. The identified users may be directed to the related subsystems.

interface General {
public void accessGeneral();
}
interface Special extends General {
public void accessSpecial();
}
interface Private extends General {
public void accessPrivate();
}

class GeneralInfo implements General {
public void accessGeneral() {
//...
}
//...
}
class SpecialInfo implements Special{
public void accessSpecial() {
//...
}
public void accessGeneral() {}
//...
}
class PrivateInfo implements Private, Special {
public void accessPrivate() {
// ...
}
public void accessSpecial() {
//...
}
public void accessGeneral() {
// ...
}
//...
}

class Connection {
//...

if (user is unauthorized) throw new Exception();
if (user is general) return new GeneralInfo();
if (user is special) return new SpecialInfo();
if (user is executive) return new PrivateInfo();
//...
}

The above code example illustrates that the whole system is not exposed to the clients. It depends on the user classification.

Sunday, March 9, 2008

Ways to survive a Stock Market Correction!

Global markets all have corrected lately. Irrespective of which market you are investing in, you would have been affected by the recent volatility. You could be an investor in America, India, China, Korea or anywhere else in the world- your situation would be pretty much the same. Many of you who are new investors might have entered panic mode, where you are unable to relax and have lots of stress and depression. I understand how it must be for somebody who just started investing in either stocks or mutual funds two months ago to see a notional loss of 30% or more now.

I remember the first time several years ago when I witnessed a stock market correction, my portfolio was down by over 50% and I too had entered panic mode. But thankfully after reading books on investing and listening to more experienced investors, I decided not to panic and hold my quality stocks. I am a much happier person today thanks to that decision.

Here are some simple ways to survive a stock market correction as an investor:

1. Stop Listening To Analysts


Most analysts in the media instead of providing you with a solution will just confuse you. Somebody will say everything is doomed while others will say things are great in the long term. Forget listening to analysts- most of them won’t be of any help. The reason people listen to analysts is because they are looking for peace and hope. Trust me you will get none of that by listening to somebody else. Peace and hope are all within you.

2. Stop Staring At Your Portfolio Every Thirty Minutes


Another mistake people make is that they get up every morning and wait for the markets to open. Once markets open they start staring at their stock prices. A fall makes you feel worse and small rise makes you feel a little better. This won’t help either. Instead keep track of the fundamentals of your company every time the results are out. If your company is profitable and growing - be happy. If it isn’t, find out if you need to exit. The stock price will catch up in the near future if business is growing. Do you stare at your money kept in a bank FD everyday? Most probably not. Use the same principle when you invest in stocks or mutual funds.

3. Be Patient

Many of you might not have a lot of cash to buy cheap now; however please be patient with whatever you have bought. Even the youngest billionaire on Earth today is 23 years old. It took him 23 years to be a billionaire and he didn’t do it in few days or weeks. The youngest billionaire probably in history is 23-year-old Mark Zuckerberg - the founder of the social networking site-Facebook.

4. Speak To Actual Investors With Experience

Instead of interacting with analysts or your broker, speak with people who are actual investors and who have been in the market for longer periods of time than you. They will tell you how they have survived various stock market corrections and what has made them richer. Read and learn more about people who have actually created wealth and sustained it over a long period of time.

5. Stop Following Crazy Tips

Please for heaven’s sake stop following ‘hot’ tips which promise to make you a millionaire in a matter of months. Maybe the ‘hot’ tip is only meant for billionaires who would end up as millionaires in case they do follow the tip. If it seems to good to be true, it is probably just a scam, which hopes to take money away from retail investors and put them in the hands of greedy manipulators. Similarly stop following rumours about how fundamentally strong companies are going to be shut down and go bankrupt in the next few months. Use your own head and trust yourself.

6. Understand Market Cycles

Every asset class has a cycle. Stock markets, mutual funds, real estate all move in cycles. Please realize that nothing can keep going up forever in a single direction. There will be phases when prices will come down and again move up. If you go back into history you will see several instances when stock prices came down, however over a period of time quality companies always reward investors. Understand market cycles, and don’t become a slave to them.

7. Follow The Guru

Today the richest man on earth, Warren Buffett, is an investor who has created wealth because he has stayed away from what everybody else is doing and has simply invested in quality companies for the long term. He invested in Gillette, for the simple reason that he believed that men won’t stop shaving. It makes sense to follow, as I call him, “The Guru” and think long term and remember people who create wealth do things that others don’t.

I’m sure if you follow the simple techniques above you will be a much happier and a calmer investor. Investing is about controlling your emotions and being disciplined about what you do.

Saturday, March 8, 2008

Java Message Service

The Java Message Service (JMS) API is a Java Message Oriented Middleware (MOM) API for sending messages between two or more clients. JMS is a part of the Java Platform, Enterprise Edition, and is defined by a specification developed under the Java Community Process as JSR 914.


General idea of messaging


Messaging is a form of loosely coupled distributed communication, where in this context the term 'communication' can be understood as an exchange of messages between software components. Message-oriented technologies attempt to relax tightly coupled communication (such as TCP network sockets, CORBA or RMI) by the introduction of an intermediary component, which in this case would be a queue. The latter approach allow software components to communicate 'indirectly' with each other. Benefits of this include message senders not needing to have precise knowledge of their receivers, since communication is performed using the queue.

Elements


The following are JMS elements: [1]

JMS provider
An implementation of the JMS interface for a Message Oriented Middleware (MOM). Providers are implemented as either a Java JMS implementation or an adapter to a non-Java MOM.
JMS client
An application or process that produces and/or receives messages.
JMS producer
A JMS client that creates and sends messages.
JMS consumer
A JMS client that receives messages.
JMS message
An object that contains the data being transferred between JMS clients.
JMS queue
A staging area that contains messages that have been sent and are waiting to be read. As the name queue suggests, the messages are delivered in the order sent. A message is removed from the queue once it has been read.
JMS topic
A distribution mechanism for publishing messages that are delivered to multiple subscribers.


Models

The JMS API supports two models:

point-to-point or queuing model
publish and subscribe model
In the point-to-point or queuing model, a producer posts messages to a particular queue and a consumer reads messages from the queue. Here, the producer knows the destination of the message and posts the message directly to the consumer's queue. It is characterized by following:

Only one consumer will get the message
The producer does not have to be running at the time the consumer consumes the message, nor does the consumer need to be running at the time the message is sent
Every message successfully processed is acknowledged by the consumer
The publish/subscribe model supports publishing messages to a particular message topic. Subscribers may register interest in receiving messages on a particular message topic. In this model, neither the publisher nor the subscriber know about each other. A good metaphor for it is anonymous bulletin board. The following are characteristics of this model:

Multiple consumers can get the message

There is a timing dependency between publishers and subscribers. The publisher has to create a subscription in order for clients to be able to subscribe. The subscriber has to remain continuously active to receive messages, unless it has established a durable subscription. In that case, messages published while the subscriber is not connected will be redistributed whenever it reconnects.
Using Java, JMS provides a way of separating the application from the transport layer of providing data. The same Java classes can be used to communicate with different JMS providers by using the JNDI information for the desired provider. The classes first use a connection factory to connect to the queue or topic, and then use populate and send or publish the messages. On the receiving side, the clients then receive or subscribe to the messages.


Application programming interface

The JMS API is provided in the Java package javax.jms.


ConnectionFactory interface
An administered object that a client uses to create a connection to the JMS provider. JMS clients access the connection factory through portable interfaces so the code does not need to be changed if the underlying implementation changes. Administrators configure the connection factory in the Java Naming and Directory Interface (JNDI) namespace so that JMS clients can look them up. Depending on the type of message, users will use either a queue connection factory or topic connection factory.


Connection interface
Once a connection factory is obtained, a connection to a JMS provider can be created. A connection represents a communication link between the application and the messaging server. Depending on the connection type, connections allow users to create sessions for sending and receiving messages from a queue or topic.


Destination interface
An administered object that encapsulates the identity of a message destination, which is where messages are delivered and consumed. It is either a queue or a topic. The JMS administrator creates these objects, and users discover them using JNDI. Like the connection factory, the administrator can create two types of destinations: queues for Point-to-Point and topics for Publish/Subscribe.


MessageConsumer interface
An object created by a session. It receives messages sent to a destination. The consumer can receive messages synchronously (blocking) or asynchronously (non-blocking) for both queue and topic-type messaging.


MessageProducer interface
An object created by a session that sends messages to a destination. The user can create a sender to a specific destination or create a generic sender that specifies the destination at the time the message is sent.


Message interface
An object that is sent between consumers and producers; that is, from one application to another. A message has three main parts:

A message header (required): Contains operational settings to identify and route messages
A set of message properties (optional): Contains additional properties to support compatibility with other providers or users. It can be used to create custom fields or filters (selectors).
A message body (optional): Allows users to create five types of messages (text message, map message, bytes message, stream message, and object message).
The message interface is extremely flexible and provides numerous ways to customize the contents of a message.


Session interface
Represents a single-threaded context for sending and receiving messages. A session is single-threaded so that messages are serialized, meaning that messages are received one-by-one in the order sent. The benefit of a session is that it supports transactions. If the user selects transaction support, the session context holds a group of messages until the transaction is committed, then delivers the messages. Before committing the transaction, the user can cancel the messages using a rollback operation. A session allows users to create message producers to send messages, and message consumers to receive messages. [2]