Wednesday, July 14, 2010

Interview - II

Interview QA :


http://en.wikipedia.org/wiki/SwingWorker

Worker Thread and Swing Worker :
When a Swing program needs to execute a long-running task, it usually uses one of the worker threads, also known as the background threads. Each task running on a worker thread is represented by an instance of javax.swing.SwingWorker. SwingWorker itself is an abstract class; you must define a subclass in order to create a SwingWorker object; anonymous inner classes are often useful for creating very simple SwingWorker objects.

SwingWorker provides a number of communication and control features:

  • The SwingWorker subclass can define a method, done, which is automatically invoked on the event dispatch thread when the background task is finished.
  • SwingWorker implements java.util.concurrent.Future. This interface allows the background task to provide a return value to the other thread. Other methods in this interface allow cancellation of the background task and discovering whether the background task has finished or been cancelled.
  • The background task can provide intermediate results by invoking SwingWorker.publish, causing SwingWorker.process to be invoked from the event dispatch thread.
  • The background task can define bound properties. Changes to these properties trigger events, causing event-handling methods to be invoked on the event dispatch thread.


class Task extends SwingWorker {
/*
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
Random random = new Random();
int progress = 0;
//Initialize progress property.
setProgress(0);
while (progress < task =" new" progress =" (Integer)">

Note : "progress" is build in field name inside swing worker class. which is set by setProgress in doIn Background Method.

The Event Dispatch Thread :
Swing event handling code runs on a special thread known as the event dispatch thread. Most code that invokes Swing methods also runs on this thread. This is necessary because most Swing object methods are not "thread safe": invoking them from multiple threads risks thread interference or memory consistency errors. Some Swing component methods are labelled "thread safe" in the API specification; these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.

Memory consistency errors :
Memory consistency errors occur when different threads have inconsistent views of what should be the same data. The causes of memory consistency errors are complex and beyond the scope of this tutorial. Fortunately, the programmer does not need a detailed understanding of these causes. All that is needed is a strategy for avoiding them.

The key to avoiding memory consistency errors is understanding the happens-before relationship. This relationship is simply a guarantee that memory writes by one specific statement are visible to another specific statement. To see this, consider the following example. Suppose a simple int field is defined and initialized:

int counter = 0;
The counter field is shared between two threads, A and B. Suppose thread A increments counter:
counter++;
Then, shortly afterwards, thread B prints out counter:
System.out.println(counter);
If the two statements had been executed in the same thread, it would be safe to assume that the value printed out would be "1". But if the two statements are executed in separate threads, the value printed out might well be "0", because there's no guarantee that thread A's change to counter will be visible to thread B — unless the programmer has established a happens-before relationship between these two statements.

There are several actions that create happens-before relationships. One of them is synchronization, as we will see in the following sections.

We've already seen two actions that create happens-before relationships.

  • When a statement invokes Thread.start, every statement that has a happens-before relationship with that statement also has a happens-before relationship with every statement executed by the new thread. The effects of the code that led up to the creation of the new thread are visible to the new thread.
  • When a thread terminates and causes a Thread.join in another thread to return, then all the statements executed by the terminated thread have a happens-before relationship with all the statements following the successful join. The effects of the code in the thread are now visible to the thread that performed the join.
Starvation and livelock :

Starvation and livelock are much less common a problem than deadlock, but are still problems that every designer of concurrent software is likely to encounter.

Starvation

Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.

Livelock

A thread often acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread, then livelock may result. As with deadlock, livelocked threads are unable to make further progress. However, the threads are not blocked — they are simply too busy responding to each other to resume work. This is comparable to two people attempting to pass each other in a corridor: Alphonse moves to his left to let Gaston pass, while Gaston moves to his right to let Alphonse pass. Seeing that they are still blocking each other, Alphone moves to his right, while Gaston moves to his left. They're still blocking each other, so...


EDT :

The event dispatching thread (EDT) is a background thread to process events from the AWT graphical user interface(GUI) event queue. These events are primarily update events that cause user interface (UI) components to redraw themselves, or input events from input devices such as the mouse or keyboard. The AWT uses a single-threaded painting model in which all screen updates must be performed from a single thread. The event dispatching thread is the only valid thread to update the visual state of visible user interface components. Updating visible components from other threads is the source of many common bugs in Java programs that use Swing.


Observer and Observable

The Java programming language provides support for the Model/View/Controller architecture with two classes:

  • Observer -- any object that wishes to be notified when the state of another object changes

  • Observable -- any object whose state may be of interest, and in whom another object may register an interest
These two classes can be used to implement much more than just the Model/View/Controller architecture. They are suitable for any system wherein objects need to be automatically notified of changes that occur in other objects.

Typically, the model is a subtype of Observable and the view is a subtype of observer. These two classes handle the automatic notification function of the Model/View/Controller architecture. They provide the mechanism by which the views can be automatically notified of changes in the model. Object references to the model in both the controller and the view allow access to data in the model.

JTable Notes :

Table support for Swing is found in the javax.swing.table package. The package consists of a series of classes and interfaces to handle the creation and display of columnar data. The way Swing supports tables is another example of MVC. The table data model is found in the TableModel interface, while the View/Controller part is found in the JTable class.

TableModel

The TableModel interface specifies how to describe the data in the table cells, and requires the maintaining of a TableModelListener list. Because whenever you create the table's data model you need to maintain this list, there is an AbstractTableModel class which maintains the list for you. The methods of TableModel consist of the following:

int getColumnCount()
Returns count of columns in data model
int getRowCount()
Returns count of rows in data model
Class getColumnClass(int column)
Returns the class of the column
String getColumnName(int column)
Returns a non-unique name for the column header label
Object getValueAt(int row, int column)
Returns the current cell value for a row / column combination
void setValueAt(Object aValue, int row, int column)
Changes a cell value for a specific row / columns. Need to notify listener list after change via fireTableChanged() method of AbstractTableModel.
boolean isCellEditable(int row, int column)
Reports if the changing of a particular cell is permissible. Returning true means it is.
void addTableModelListener(TableModelListener l)
Add listener to TableModelListener list
void removeTableModelListener(TableModelListener l)
Remove listener to TableModelListener list

As mentioned above, AbstractTableModel maintains the listener list for you. The list is available from the protected listenerList variable. Then, when you subclass the adapter, you only need to implement getColumnCount(), getRowCount(), and getValueAt(). If you are creating a read-only table (Getter Methods are provided), the setValueAt() method is stubbed out for you in AbstractTableModel, and isCellEditable() returns false by default, so you don't have to implement either. However, when you do want to support editability and implement (SetterMethods and Editable) setValueAt() (and isCellEditable()), you have to remember to notify the listener list about the change. Besides changing the data, use the fireTableCellUpdated() method of AbstractTableModel to notify those interested in cell-level changes.

For Moving Cell Cursor from Left to Right ( by default top to bottom) :

KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
InputMap map = this.getInputMap(JTable.WHEN_FOCUSED);
map.put(enter, "selectNextColumnCell");

For TabOut from the JTable to Next Component :

Action tabOut = new AbstractAction()
{
private static final long serialVersionUID = -178840152285711197L;

public void actionPerformed(ActionEvent ae)
{
KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
}
};

this.getInputMap(JComponent.WHEN_FOCUSED).

put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "tabOut");
this.getActionMap().put("tabOut", tabOut);

For Exit from the Last Column and Last Row of JTable :

This has to be implemented in Key Pressed by implementing Key Listener in JTable


Action exit = new AbstractAction()
{
/**
*
*/
private static final long serialVersionUID = 6402639250679311576L;

public void actionPerformed(ActionEvent ae)
{
KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
}
};

int totalrow = getRowCount() - 1;
int totalcolumn = getColumnCount() - 1;
if ((getSelectedRow() == totalrow) && (getSelectedColumn() == totalcolumn))
{
getInputMap(JComponent.WHEN_FOCUSED).

put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "enterOut");
getActionMap().put("enterOut", exit);
}


Component Model Interface Model Type
JButton ButtonModel GUI
JToggleButton ButtonModel GUI/data
JCheckBox ButtonModel GUI/data
JRadioButton ButtonModel GUI/data
JMenu ButtonModel GUI
JMenuItem ButtonModel GUI
JCheckBoxMenuItem ButtonModel GUI/data
JRadioButtonMenuItem ButtonModel GUI/data
JComboBox ComboBoxModel data
JProgressBar BoundedRangeModel GUI/data
JScrollBar BoundedRangeModel GUI/data
JSlider BoundedRangeModel GUI/data
JTabbedPane SingleSelectionModel GUI
JList ListModel data
JList ListSelectionModel GUI
JTable TableModel data
JTable TableColumnModel GUI
JTree TreeModel data
JTree TreeSelectionModel GUI
JEditorPane Document data
JTextPane Document data
JTextArea Document data
JTextField Document data
JPasswordField Document data

collections - Collection.html

Resource Pooling :
Object creation and garbage collection are costly operations. Performance is adversely affected by object creation - What do you do?

You Pool. Pooling avoids object creation by object reuse. Pooling requires coder discipline-> Dont create objects, request them from Pool and return to Pool upon completion.

This is highly desirable for temporary objects- ie objects that have a short life-span, eg local variables in functions etc. Class level variables ( objects) are not good candidates for pooling.

This class implements an abstract type for resource pooling. The resource is obtained from the free list and put on the list of busy resources by calling get(). When the use of the resource has expired one must call release() passing the object as a parameter to it.

It is HIGHLY recommended to use one POOL to manage one type of resource. Please do not use the same pool for resources of different types (you may get runtime exceptions of type ClassCastExceptions, unless adequate checks are performed).

This class is deliberately left as abstract. Implementations must derive classes from this and implement resource management. If you observe carefully - calling get() or release() in this implementation will do nothing as the free and busy vectors will be empty. Hence implementations must devise mechanisms to place resources into these vectors(lists).

All sorts of mechanisms can be implemented - like forcing only a Maximum number of objects in the resource pool, etc.
It is left upon the implementors to select the best mechanism for their particular usage.
Another useful extension to this class will be to add time-stamps to the objects in the busy list. A thread could then reap objects out of the busy list, if their lifetime has expired.

What I mean here is that, it may be the case that some objects release() method is never called ( because of poor programming or some exception being thrown). The busy vector will keep holding these (possibly) useless objects. Such objects, whose lease on life, has expired must be pruned from the busy vector. These must not be put on the free list - rather they should be left to the JVM to garbage collect. WHY ? Coz, we cannot know if this object is actually being used somewhere or not - it may so happen that the object lease on life is over, but it is still a valid reference being used somewhere in the code. Hence - lets not put it on the free list but let the JVM take care of it. After we detect some objects that we prune, its a good idea to call System.gc() to hint the JVM that we wish garbage collection to kick in.

1 - Create the abstract class ResourcePool.java which has 2 Vectors free and busy vectors. get and release method for making free vector to busy vector and vice versa.

2 - Create class implements the Pool for Point3d objects We let the pool grow as large as Point3d objects required. We also provide for some sort of resource utilization estimates by providing counts of points requested and released using this pool. May be useful later for further optimization of code.

-----------------------------------------------------------------------------------------------------------------


Study :
http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html
HashMap Class - equals and hashcode override :

Actual equals method was in AbstractHashMap
Map.Entry (equals overrides)

public final boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
Object k1 = getKey();
Object k2 = e.getKey();
if (k1 == k2 || (k1 != null && k1.equals(k2))) {
Object v1 = getValue();
Object v2 = e.getValue();
if (v1 == v2 || (v1 != null && v1.equals(v2)))
return true;
}
return false;
}

public final int hashCode() {
return (key==null ? 0 : key.hashCode()) ^ (value==null ? 0 : value.hashCode());
}

Equals Method - Contract :

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.


String Class - equals Method Override :


public boolean equals(Object anObject) {
if (this == anObject)
return true;
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}


Make deep Cloning for Immutable Class ? (did in CAD*Impl using constructor passing same class and copy method will call this constructor for Undo Redo Operation)

Note : No Need to Implement super.Clone or Cloneable Interface for deep Cloning

Check Link Implemented similar

Copy Constructor must be in "private"
e.g : private ClassName(ClassName obj) {
Assign all variables from obj to this class ,
Assign User defined Class Object reference with use the copy method of corresponding class object
}
Otherwise if "public" will result in wrong cloning : say Outside world can call constructor with even derived class and making the copy will result wrong.
See Ex:






public class Person
{
private Brain brain;
private int age;
public Person(Brain aBrain, int theAge)
{
brain = aBrain;
age = theAge;
}

public
Person(Person another)
{
age = another.age;
brain = new Brain(another.brain);
// we assume we have a copy constructor for Brain
}
}

public class Brain
{
public Brain() {}
public Brain(Brain another) {} // Assume proper copying of the Brain
}

Main Class :

Person sam = new Person(new Brain(), 1);
Person bob = new Person(sam);
System.out.println(sam);
System.out.println(bob);



The output from the above statements will be:

This is person with Brain@3fbdb0
This is person with Brain@3e86d0

The copy constructor of Person depends on the Brain class. It creates an instance of the Brain. What if we have a class, say SmarterBrain which extends Brain and we have a user writing code like the following:

Person sam = new Person(new SmarterBrain(), 1);
Person bob = new Person(sam);
System.out.println(sam);
System.out.println(bob);

The output from the above code will be:

This is person with SmarterBrain@3e86d0
This is person with Brain@50169

This Fails the Deep Copy Method

Note : If Derived Class did copy constructor, correspondingly super(obj) should be called for executing the super Class Constructor (As we did in CAD say SolidLoft Class to Parametric Class)

This Method will call from the outside world for deep cloning and will call the same class with same class obj Constructor.

className copymethod () {
return new ClassName(this);
}

-------------------------------------------------------------------------------------

How will you implement the checkbox in JTable with editable option ?



First Create the Table with DefaultTableModel and add the rowdata and column

JTable table = new JTable(DefaultTableModel Type Class);
//setting the checkbox renderer
CheckBoxRenderer checkBoxRenderer = new CheckBoxRenderer();
table.getColumn(colNameText[2]).setCellRenderer(checkBoxRenderer);
//setting the checkbox editor
CheckBoxEditor checkBoxEditor = new CheckBoxEditor();
table.getColumn(colNameText[2]).setCellEditor(checkBoxEditor);

public class CheckBoxRenderer extends JCheckBox implements TableCellRenderer
{
public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)
{
setSelected((value != null && ((Boolean) value).booleanValue()));
return this;
}
}
public class CheckBoxEditor implements TableCellEditor
{
private DefaultCellEditor editor;
CheckBoxEditor()
{
setEditor();
}
public void setEditor()
{
editor = new DefaultCellEditor(new JCheckBox());
}
public TableCellEditor getEditor()
{
return editor;
}
public Component getTableCellEditorComponent(JTable table, Object value,boolean isSelected, int row, int column)
{
return editor.getTableCellEditorComponent(table,value,isSelected,row,column);
}
public Object getCellEditorValue()
{
return editor.getCellEditorValue();
}
public boolean stopCellEditing()
{
return editor.stopCellEditing();
}
public void cancelCellEditing()
{
editor.cancelCellEditing();
}
public boolean isCellEditable(EventObject anEvent)
{
return editor.isCellEditable(anEvent);
}
public void addCellEditorListener(CellEditorListener l)
{
editor.addCellEditorListener(l);
}
public void removeCellEditorListener(CellEditorListener l)
{
editor.removeCellEditorListener(l);
}
public boolean shouldSelectCell(EventObject anEvent)
{
return editor.shouldSelectCell(anEvent);
}
}



How will you create instance of String ?

say com.mytest > com is package and mytest is class
A : by using reflection API
Class.forName(String name).newInstance();


How will you register a Key in Button for pressing tab key and Enter key in Key ?

A :
/**
* When we pressed enter the default button is always 'pressed'.
* To use the button that has currently the focus we have to press space bar
* instead of Enter. when we pressed enter then default button action
* event is being fired. To avoid this we use this method.
*/

public static void enterPressesWhenFocused(JButton button) {
button.registerKeyboardAction(
button.getActionForKeyStroke(
KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, false)),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false),
JComponent.WHEN_FOCUSED);
button.registerKeyboardAction(
button.getActionForKeyStroke(
KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0, true)),
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true),
JComponent.WHEN_FOCUSED);
}

ok = new JButton("OK" );
ok.addActionListener( this );
enterPressesWhenFocused(ok);
and
cancel = new JButton("Cancel" );
cancel.addActionListener( this );
enterPressesWhenFocused(cancel);



The Above Type of "registerKeyboardAction" of keybinding is older ways now InputMap and ActionMap has to be used.

How will you allow only numbers in JTextField ?? Not Implementing KeyListener

The Method has to be Override is (Older Way is boolean KeyDown() Method which is not longer used) processKeyEvent() where value can be checked inside JTextField which must call super.processKeyEvent() . See Example :



import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class KeyDownTest extends JFrame
{
Container contain;
private JLabel label = new JLabel("Name ");
private JTextField field;
KeyDownTest()
{
super("Testing ");
contain = getContentPane();
contain.add(addedPanel());
setSize(300,200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public JPanel addedPanel()
{
JPanel panel = new JPanel();
panel.add(label);
field = new JTextField(20){

This is the Method has to be override for manipulating the keyevent for TextField

public void processKeyEvent(KeyEvent e)
{
char keyChar = e.getKeyChar();
if ( ((keyChar > '0') && (keyChar < '9')) ||
(keyChar == '.') || (keyChar == '-') ||
(keyChar == 8 ) || (keyChar == 127) )
{
super.processKeyEvent(e);
return;
}
else
return;
}
};
panel.add(field);
return panel;
}

public static void main(String[] arg)
{
new KeyDownTest();
}
}



http://www.javacoffeebreak.com/java107/java107.html


CaughtException : Exception - Except Runtime Exception and subclasses of Runtime

Eg : IOException , SQLException, ClassNotFoundException, CloneNotSupported, DateFormat, InterruptedException.

UnCaught Exeption :

RunTime Exception Eg : Arithmatic, IndexOutofBound, NullPointer, ClassCast, ConcurrentException, IllegalMonitorException

Error : IOError

Nested Interface inside Interface ?

Yes

validate, revalidate, invalidate,

repaint() and revalidate().

repaint - redraw the component (for example if you do custom painting on a component, it will cause the paint() method to be called from the AWT event dispatch thread. For normal GUI this usually automatically called if you eg change a JLabel icon or text, or in fire a list/table/tree changed event.

revalidate - relayout the component (which can cause a repaint as well), it will cause validate() to be called on the EDT.

BoderLayout in North, How to set the size it ?

MVC in JTextField - JTable?

Component Model Interface Model Type
JButton ButtonModel GUI
JToggleButton ButtonModel GUI/data
JCheckBox ButtonModel GUI/data
JRadioButton ButtonModel GUI/data
JMenu ButtonModel GUI
JMenuItem ButtonModel GUI
JCheckBoxMenuItem ButtonModel GUI/data
JRadioButtonMenuItem ButtonModel GUI/data
JComboBox ComboBoxModel data
JProgressBar BoundedRangeModel GUI/data
JScrollBar BoundedRangeModel GUI/data
JSlider BoundedRangeModel GUI/data
JTabbedPane SingleSelectionModel GUI
JList ListModel data
JList ListSelectionModel GUI
JTable TableModel data
JTable TableColumnModel GUI
JTree TreeModel data
JTree TreeSelectionModel GUI
JEditorPane Document data
JTextPane Document data
JTextArea Document data
JTextField Document data
JPasswordField Document data

Marker Interface ?

In java language programming, interfaces with no methods are known as marker interfaces. Marker interfaces are Serializable, Clonable, SingleThreadModel, Event listener. Marker Interfaces are implemented by the classes or their super classes in order to add some functionality.

e.g. Suppose you want to persist (save) the state of an object then you have to implement the Serializable interface otherwise the compiler

will throw an error. To make more clearly understand the concept of marker interface you should go through one more example.

Suppose the interface Clonable is neither implemented by a class named Myclass nor it's any super class, then a call to the method clone() on Myclass's object will give an error. This means, to add this functionality one should implement the Clonable interface. While the Clonable is an empty interface but it provides an important functionality.


Null Pointer Exception :

Thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

Applications should throw instances of this class to indicate other illegal uses of the null object.

2 - How to create Immutable Type Class

Our Template for Immutable Classes

  • Make all fields private
  • Don't provide mutators (setter method)
  • Ensure that methods can't be overridden by either making the class final (Strong Immutability) or making your methods final (Weak Immutability)
  • If a field isn't primitive or immutable, make a deep clone on the way in and the way out.

Which classes are Immutable?

To finish up, lets discuss the common Java classes that are immutable and those that aren't. Firstly, all of the java.lang package wrapper classes are immutable: Boolean, Byte, Character, Double, Float, Integer, Long, Short, String.

Accessors :
An accessor is a method that accesses the contents of an object but does not modify that object. In the simplest case, an accessor just returns the value of one of the fields. In general, an accessor performs some computation using the fields as long as that computation does not modify any of the fields.

Mutators :
A mutator is a method that can modify an object. In the simplest case, a mutator just assigns a new value to one of the fields. In general, a mutator performs some computation and modifies any number of fields.

Sometimes, accessors are called 'getter' methods and mutators are called 'setter' methods.
Now we have a template for creating immutable objects.

No comments:

Bird

Bug

Image and video hosting by TinyPic