Wednesday, 7 December 2016

Is operations on primitive types are atomic?

Java support primitive types like byte, int, long etc., following table summarizes the primitive data types and their size in bytes.

Data Type
Size (in bytes)
byte
1
short
2
int
4
long
8
float
4
double
8
char
2

Note: The boolean data type has only two possible values: true and false. This data type represents one bit of information, but its "size" isn't something that's precisely defined.

Writes and reads of primitive types other than long and double are atomic by default. But writes and reads on long, double datatypes are need not be atomic. They depend on implementation of JAVA vendor.

Non-atomic Treatment of double and long
As per the java specification, a single write to a non-volatile long or double value is treated as two separate writes: one to each 32-bit half. This can result in a situation where a thread sees the first 32 bits of a 64-bit value from one write, and the second 32 bits from another write.

How can I make the Write & Read operations on long and double as atomic?
Make the long and double variables as volatile. Writes and reads of volatile long and double values are always atomic. So while working in multi-threaded environment always make the long, double as volatile (or) use some synchronization mechanism (or) use the class AtomicLong.

Let me clarify what is atomicity with an example. I mentioned that, writes and reads of primitives (except long, double) and volatile long, double are atomic. Now go through following code and check whether it is atomic (or) not.

private static int counter = 0;
public void increment() { counter++; }

Do you think the operation counter++ is atomic?
Of course not, the statement 'counter++' is actually combination of three operations
         1. Read the value of variable counter
         2. Increment the value counter by one
         3. Write the updated value to counter

How to make the operation atomic?
By synchronizing the access to the variable counter, you can make the operation atomic.

private static int counter = 0;
public static synchronized void increment() {
   counter++;
}

                          (OR)
private static int counter = 0;
private static final Object LOCK = new Object();

public static void increment() {
   synchronized(LOCK) {
      counter++;
   }
}

You may like



Tuesday, 6 December 2016

Why to implement Comparable?

Why to implement Comparable?
If you are a Java developer, I am sure that, you already implemented Comparable interface in some of your projects. By implementing Comparable
Interface, you can impose natural ordering of elements, while sorting.

Comparable interface provides ‘compareTo’ method, all the implemented classes must provide definition to ‘compareTo’ method.

int compareTo(T o)
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

If your class implements Comparable interface, you can use Java built in classes like Arrays.sort(), Collections.sort() to sort the elements in their natural order. Let me give an example of Comparable interface first, later we can see the advantages of implementing Comparable interface.

Example: Sort employees by id
Employee.java
public class Employee implements Comparable<Employee> {

 private String firstName, lastName;
 private Integer id;

 Employee(String firstName, String lastName, int id) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.id = id;
 }

 @Override
 public int compareTo(Employee o) {
  if (o == null)
   throw new NullPointerException();
  return this.id.compareTo(o.id);
 }

 @Override
 public String toString() {
  return id + ". " + firstName + " " + lastName;
 }

}

EmployeeTest.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class EmployeeTest {
 public static void main(String args[]) {
  List<Employee> myList = new ArrayList<>();

  myList.add(new Employee("Joel", "Abc", 5));
  myList.add(new Employee("Murali", "Krishna", 3));
  myList.add(new Employee("Gopi", "battu", 4));
  myList.add(new Employee("Rama", "Krishna", 2));

  System.out.println("Before Sorting");
  Iterator<Employee> iter1 = myList.iterator();
  while (iter1.hasNext()) {
   System.out.println(iter1.next());
  }

  Collections.sort(myList);

  System.out.println("\nAfter Sorting");
  Iterator<Employee> iter2 = myList.iterator();
  while (iter2.hasNext()) {
   System.out.println(iter2.next());
  }

 }
}

Output
Before Sorting
5. Joel Abc
3. Murali Krishna
4. Gopi battu
2. Rama Krishna

After Sorting
2. Rama Krishna
3. Murali Krishna
4. Gopi battu
5. Joel Abc

By implementing Comparable interface, you can provide implementation to generic algorithms. For example, you can implement quick sort once and it can be used with all the data types that implement Comparable.

Following are some of the examples of generic algorithms that implement Comparable interface.


Collections like TreeSet, PriorityBlockingQueue stores elements in their natural ordering. You can specify the natural ordering by implementing Comparable interface.

By implementing Comparable interface, you can use the utility classes provided by Java like Collections.sort, Arrays.sort, PriorityBlockingQueue

If you would like to know about the difference between Comparable, Comparator you can go through following post.


You may like




SWT: Key listener

KeyListener is used to capture key pressed and key released events. You can add keyListener to a widget using addkeyListener mehtod. You can remove the key listener using removeKeyListener method.

KeyListener interface provides following methods.

Method
Description
public void keyPressed(KeyEvent e)
Sent when a key is pressed on the system keyboard.
public void keyReleased(KeyEvent e)
Sent when a key is released on the system keyboard.

Ex:
Text text = new Text(shell, SWT.MULTI | SWT.BORDER);
text.setBounds(10, 10, 300, 100);

text.addKeyListener(new KeyListener() {

 @Override
 public void keyPressed(KeyEvent e) {
  
 }

 @Override
 public void keyReleased(KeyEvent e) {
  
 }

});

Following is the complete working application.
package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class Test {

 private static int shellWidth = 400;
 private static int shellHeight = 400;

 private static void addWidgetsToShell(Display display, Shell shell) {

  Text text = new Text(shell, SWT.MULTI | SWT.BORDER);
  text.setBounds(10, 10, 300, 100);

  text.addKeyListener(new KeyListener() {

   @Override
   public void keyPressed(KeyEvent e) {
    String result = "";
    switch (e.character) {
    case 0:
     result += " '\\0'";
     break;
    case SWT.BS:
     result += " '\\b'";
     break;
    case SWT.CR:
     result += " '\\r'";
     break;
    case SWT.DEL:
     result += " DEL";
     break;
    case SWT.ESC:
     result += " ESC";
     break;
    case SWT.LF:
     result += " '\\n'";
     break;
    default:
     result += " '" + e.character + "'";
     break;
    }
    System.out.println(result);
   }

   @Override
   public void keyReleased(KeyEvent e) {
    if (e.stateMask == SWT.CTRL && e.keyCode != SWT.CTRL)
     System.out.println("Command can execute here");
   }

  });
 }

 public static void main(String[] args) {

  /* Instantiate Display object, it represents SWT session */
  Display display = new Display();

  /*
   * Define Shell, it represent a window, You can add more than one shell
   * to Display
   */
  Shell shell = new Shell(display);
  shell.setSize(shellWidth, shellHeight);

  addWidgetsToShell(display, shell);

  /* Open shell window */
  shell.open();

  /*
   * Run the event dispatching loop until an exit condition occurs, which
   * is typically when the main shell window is closed by the user.
   */

  while (!shell.isDisposed()) {
   if (!display.readAndDispatch())
    display.sleep();
  }

  /* Dispose the display */
  display.dispose();
 }
}




Previous                                                 Next                                                 Home

Saturday, 3 December 2016

SWT: SelectionListener

SelectionListener provides methods to handle the events, when the widget is selected like button clicks. SelectionListener interface provides following methods.

Method
Description
public void widgetSelected(SelectionEvent e)
Method is called, when selectio event occurred on given SWR widget. For example, button clicks, item selects in list etc.,
public void widgetDefaultSelected(SelectionEvent e)
Sent when default selection occurs in the control.


Example
button1.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(SelectionEvent e) {
                 int countryIndex = countryCombo.getSelectionIndex();
                 int hobbyIndex = hobbyCombo.getSelectionIndex();

                 String country = "No Country Selected";
                 String hobby = "No Hobby Selected";

                 country = (countryIndex > -1) ? countries[countryIndex] : country;
                 hobby = (hobbyIndex > -1) ? hobbies[hobbyIndex] : hobby;

                 System.out.println("Country selected : " + country);
                 System.out.println("Hobby selected : " + hobby);

         }
});

package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class Test {

 private static int xPosition = 30;
 private static int yPosition = 50;

 private static int shellWidth = 400;
 private static int shellHeight = 400;

 private static String[] countries = { "India", "Germany", "Canada", "Japan", "Sri Lanka", "Singpore", "Russia" };
 private static String[] hobbies = { "Trekking", "Movies", "Games", "Painting", "Singing", "Dancing" };

 private static void addWidgetsToShell(Display display, Shell shell) {

  Combo countryCombo = new Combo(shell, SWT.DROP_DOWN);
  countryCombo.setItems(countries);
  countryCombo.setBounds(xPosition, yPosition, 150, 100);
  countryCombo.setText("Select Country");

  yPosition += 50;

  Combo hobbyCombo = new Combo(shell, SWT.DROP_DOWN);
  hobbyCombo.setItems(hobbies);
  hobbyCombo.setBounds(xPosition, yPosition, 150, 100);
  hobbyCombo.setText("Select hobbies");

  yPosition += 50;

  Button button1 = new Button(shell, SWT.PUSH);
  button1.setText("Submit");
  button1.setLocation(xPosition + 100, yPosition);
  button1.setSize(100, 20);

  button1.addSelectionListener(new SelectionAdapter() {
   public void widgetSelected(SelectionEvent e) {
    int countryIndex = countryCombo.getSelectionIndex();
    int hobbyIndex = hobbyCombo.getSelectionIndex();

    String country = "No Country Selected";
    String hobby = "No Hobby Selected";

    country = (countryIndex > -1) ? countries[countryIndex] : country;
    hobby = (hobbyIndex > -1) ? hobbies[hobbyIndex] : hobby;

    System.out.println("Country selected : " + country);
    System.out.println("Hobby selected : " + hobby);

   }
  });

 }

 public static void main(String[] args) {

  /* Instantiate Display object, it represents SWT session */
  Display display = new Display();

  /*
   * Define Shell, it represent a window, You can add more than one shell
   * to Display
   */
  Shell shell = new Shell(display);
  shell.setSize(shellWidth, shellHeight);

  addWidgetsToShell(display, shell);

  /* Open shell window */
  shell.open();

  /*
   * Run the event dispatching loop until an exit condition occurs, which
   * is typically when the main shell window is closed by the user.
   */

  while (!shell.isDisposed()) {
   if (!display.readAndDispatch())
    display.sleep();
  }

  /* Dispose the display */
  display.dispose();
 }
}



SelectionAdapter is an adpater class that implements SelectionListener interface. Adapter classes provide default (often empty) implementation of interface or abstract class. With the use of adapter class, you can provide only the implementation of methods you needed.


Previous                                                 Next                                                 Home

SWT: Event Handling

In my previous posts, I explained about different kinds of SWT widgets, Widgets themselves are not sufficient enough to develop an application, unless you add event handling mechanism to them.

In this and subsequent posts, I am going to explain different event handling mechanisms.

How to get notified about an event?
By adding listeners to SWT widget, you will get notified about the events occurred on given widget.

button1.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(SelectionEvent e) {
                 System.out.println("Clicked me ");
         }
});

In the above snippet, I added SelectionListener to the button1. Whenever the button1 is clicked the widgetSelected method is called and the message is printed to console.

I am going to explain about most common event listeners in subsequent posts.

a.   Selection Listener
b.   Key Listener
c.    Mouse Listener
d.   Mouse Move Listener
e.   Mouse Track Listener
f.    Text Listeners

g.   Focus listeners


Previous                                                 Next                                                 Home

Why should we avoid finalize method?

‘finalize’ method is defined in Object class, it is executed by JVM (java Virtual Machine) just before the object is being garbage collected. Sub classes can override this method and perform some relevant operation like cleaning up native resources. First let me explain an example of finalize method, after that we can discuss, why shouldn’t we use finalize method in our applications.

Connection.java
public class Connection {

 public Connection() {

 }

 public void close() {
  System.out.println("Connection is getting closed");
 }

 @Override
 public void finalize() throws Throwable {
  this.close();
  super.finalize();
 }

}

ConnectionTest.java
public class ConnectionTest {
 public static void main(String args[]) throws InterruptedException {
  Connection conn = new Connection();

  conn = null;
  Runtime.getRuntime().gc();
  
  Thread.sleep(3000);
 }
}

Output
Connection is getting closed


Why shouldn’t we use finalize method?
a.   One problem with finalizers is that, Java specification doesn't guarantees immediate execution of finalize method on object unreachable.

b.   The Java programming language does not specify which thread will invoke the finalizer for any given object. So it is completely dependent on implementation of specific java vendor. Some vendors may implement it as part of garbage collection thread (or) some may implement it as separate thread. Because of this, behavior of finalize method may change from one implementation to other.

c.    Finalizers can be called in any order. It is not necessary that they will be called in the order that objects are unreachable. The Java programming language imposes no ordering on finalize method calls.

d.   If an uncaught exception is thrown during the finalization, the exception is ignored and finalization of that object terminates.

Example
    @Override
    public void finalize() throws Throwable {
             this.close();
             String s = null;
             s.toCharArray();
             super.finalize();
    }

Notify above snippet, In ideal scenarios, Java run time throws NullPointerException while executing the statement 's.toCharArray();'. Since this statement is inside the finalize method, it will be ignored.

e.   "finalizer chaining" is not performed automatically. If a sub class overrides finalize method of super class, then the subclass finalizer must invoke the superclass finalizer manually.

f.    Don't close critical resources in finalize method. For example, if you are developing an application that works with files, always close the file handles after their usage. If you closed the file handles in finalize method. It is not guaranteed that they will be closed immediately. Even though you are done with the file usage, the handle still be in use, since finalize is not executed yet.

Is there any way that I can control the execution of finalize method?
System class provide 'runFinalization' method, when you call this method, Java Virtual Machine expend effort toward running the finalize methods of objects that have been found to be discarded but whose finalize methods have not yet been run.

You may like