Monday, April 14, 2008

ONE BEDROOM FLAT

ONE BEDROOM FLAT...

WRITTEN BY AN INDIAN SOFTWARE ENGINEER......



As the dream of most parents I had acquired a degree in
Software Engineering and joined a company based in USA, the
land of braves and opportunity. When I arrived in the USA, it
was as if a dream had come true.


Here at last I was in the place where I want to be. I decided I
would be staying in this country for about Five years in which
time I would have earned enough money to settle down in India.

My father was a government employee and after his retirement,
the only asset he could acquire was a decent one bedroom flat.


I wanted to do some thing more than him. I started feeling
homesick and lonely as the time passed. I used to call home and
speak to my parents every week using cheap international phone
cards. Two years passed, two years of Burgers at McDonald's and
pizzas and discos and 2 years watching the foreign exchange
rate getting happy whenever the Rupee value went down.

Finally I decided to get married. Told my parents that I have
only 10 days of holidays and everything must be done within
these 10 days. I got my ticket booked in the cheapest flight.
Was jubilant and was actually enjoying hopping for gifts for
all my friends back home. If I miss anyone then there will be
talks. After reaching home I spent home one week going through
all the photographs of girls and as the time was getting
shorter I was forced to select one candidate.


In-laws told me, to my surprise, that I would have to get
married in 2-3 days, as I will not get anymore holidays. After
the marriage, it was time to return to USA, after giving some
money to my parents and telling the neighbors to look after
them, we returned to USA.


My wife enjoyed this country for about two months and then she
started feeling lonely. The frequency of calling India
increased to twice in a week sometimes 3 times a week. Our
savings started diminishing.

After two more years we started to
have kids. Two lovely kids, a boy and a girl, were gifted to us
by the almighty. Every time I spoke to my parents, they asked
me to come to India so that they can see their grand-children.


Every year I decide to go to India… But part work part
monetary conditions prevented it. Years went by and visiting
India was a distant dream. Then suddenly one day I got a
message that my parents were seriously sick. I tried but I
couldn't get any holidays and thus could not go to India ... The
next message I got was my parents had passed away and as there
was no one to do the last rights the society members had done
whatever they could. I was depressed. My parents had passed
away without seeing their grand children.


After couple more years passed away, much to my children's
dislike and my wife's joy we returned to India to settle down.
I started to look for a suitable property, but to my dismay my
savings were short and the property prices had gone up during
all these years. I had to return to the USA...


My wife refused to come back with me and my children refused to
stay in India... My 2 children and I returned to USA after
promising my wife I would be back for good after two years.

Time passed by, my daughter decided to get married to an
American and my son was happy living in USA... I decided that
had enough and wound-up every thing and returned to India... I
had just enough money to buy a decent 02 bedroom flat in a
well-developed locality.


Now I am 60 years old and the only time I go out of the flat is
for the routine visit to the nearby temple. My faithful wife
has also left me and gone to the holy abode.

Sometimes

I wondered was it worth all this?

My father, even after staying in India,

Had a house to his name and I too have
the same nothing more.

I lost my parents and children for just ONE EXTRA BEDROOM.

Looking out from the window I see a lot of children dancing.
This damned cable TV has spoiled our new generation and these
children are losing their values and culture because of it. I
get occasional cards from my children asking I am alright. Well
at least they remember me.


Now perhaps after I die it will be the neighbors again who will
be performing my last rights, God Bless them.

But the question
still
remains 'was all this worth it?'

I am still searching for an answer.................!!!

START THINKING

IS IT JUST FOR ONE EXTRA BEDROOM???

LIFE IS BEYOND THIS …..DON'T JUST LEAVE YOUR LIFE ……..
START LIVING IT …….
LIVE IT AS YOU WANT IT TO BE …….

Friday, April 4, 2008

What does volatile do?

What does volatile do?

This is probably best explained by comparing the effects that volatile and synchronized have on a method. volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:

int i1; int geti1() {return i1;}
volatile int i2; int geti2() {return i2;}
int i3; synchronized int geti3() {return i3;}
geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.

On the other hand, geti2() effectively accesses the value of i2 from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.

Well if volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3() does the following:


1. The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).
2. The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory (JVMs can use dirty sets to optimize this so that only "dirty" variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).
3. The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
4. (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
5. The thread releases the lock on the monitor for object this.
So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.

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.