It's all about Java: abt java
Showing posts with label abt java. Show all posts
Showing posts with label abt java. Show all posts

Sunday, 11 April 2021

Agile Methodology with SCRUM Framework Basics

Software development activities can be managed and taken care with different life cycle models. These life cycle models has became legacy since few years. Few of the available Software Development Life Cycle Models in short SDLC are Win-Win Model and Waterfall Model etc.

These traditional models has different phases of development. 
       1. Requirements 
       2. Analysis 
       3. Design 
       4. Implementation 
       5. Test 
       6. Documentation 
and 7. Maintenance 

In SDLC, the above stages are freezed one after the other. If developer is in Design phase and realized that there could be a possibility of change in requirements, then it is not possible to go back one phase and fix in Requirement phase. 
These scenarios and use cases has brought Agility in to existence in software development activities.  


Agility in English: 


Agility means "able to move quickly and easily".  Being agile in software development makes the development move or progressed quick enough and flexible to go back and forth through out the development phases and complete the activities on time.


Agile Methodology:



"Agility is the ability that gives better productivity..."


Agile is the ability to create and respond to change. It is a way of dealing with and ultimately succesing in an uncertain environment. Agile methodology has different subsets also called as frameworks. 
SCRUM and Kanban are few among others. These frameworks can be adapted as process solutions based upon different development needs.


SCRUM Framework:

Scrum is a process framework used to manage product development and other knowledge work.

SCRUM framework manages the development activities biweekly, 3 weeks or 4 weeks. This duration is called as Sprint. Usually it is not recommended to have more than 6 members or developers in a team.


Sprint:

Sprint is a duration of time where few backlogs are realized as tasks and completed by development team. Once the Sprint is completed these software changesets goes into release version of the application software.
Based on the need Sprint duration can be 2 or 3 or 4 weeks. But most of the Scrum experts suggest Biweekly sprints.


SCRUM and Meetings:


    1. Standup call
    2. Review Meeting
    3. Grooming Session
    4. Retrospective

Standup calls are held everyday morning that lasts for 15 minutes. And following are discussed:

    1. What is done yesterday?
    2. What is planned today?
    3. Any Roadblocks?

NOTE: It is not recommended to consider more than 15 minutes for Standup meeting

Review Meeting is held at the end of the Sprint showing different works and demos of Sprint's development activites.

Grooming Session lasts for one and half hours. During this session tasks are pulled from backlogs and discussed the following:

    1. Estimations for the Tasks
    2. Deciding the priorities
    3. Severity levels
    4. Assignments


Retrospective meetings are held after the end of Sprint and discussed about:

    What went correct..?
    What went wrong..?
And Appreciations if any...
     

Scrum framework and few notable points:

  1. All requirements are consolidated as backlogs along with its descriptions and other details.
  2. Estimations of backlogs are done with the Poker Cards
  3. Poker cards are numbered in a Fibonacci order
  4. SCRUM is managed by Certified SCRUM Master or SCRUM Coach
  5. If Standups are not held with in 15 minutes, can be considered as limitation.
  6. Virtual Boards are considered over Physical boards, if members are in remote locations 

SCRUM and Agile Supporting Tools:

  1. Microsoft Azure Boards
  2. Atlassian JIRA
  3. IBM - Rational Team Concert 


SCRUM Limitations:

  • Geographically if team members are located in different places, Agile may not be effective


Tuesday, 15 September 2020

Coding and best practices

 Write code or write code in right way...

Writing a coding solution to a problem can be done in many ways. If the solution can be obtained with less number of code lines, then it is easy to understand and maintain.

But what if code is large with having millions of lines. Moreover maintenance and readability becomes difficult as the code base grows... Right? 

In this blog I want to share my views and experiences on writing code efficiently and effectively with less maintenance efforts.

Aspects to consider while coding:

  • Naming convention
  • Cyclomatic Complexity
  • SOLID principles
  • DRY Principle
  • Managing dead code
  • Comments


Naming conventions:

Every programming language mandates few norms in order to name variables, classes and functions etc. For ex: Java uses class names first letter to be a alphabet and rest to be lower case letters. 

But if we dig little bit more, naming conventions are not limited to only upper case or lower case letters and using alphanumeric letters etc.

Naming a variable must be enough concise as naming your first child's name...

Few bad names for variables and constants:

          int final static TWO = 2;  [wrong]

          int final static MAX_LENGHT = 2; [Correct] 

  

Cyclomatic Complexity:

Cyclomatic complexity is a measure or metric to estimate complexity level of a snippet or block of code. 

Cyclomatic complexity and best practices:

  • Never put more than three conditional checks (&& operator and || operator etc.) in one if condition
  • Never exceed more than thirty lines in one function or method.
  • Never exceed more than 1000 lines in one class or one file.

SOLID principles:

Usually developing a large and scalable application, requires better design. Adhering to SOLID principles yields better scalable and easily maintainable applications.

There are five SOLID principles. They are:

  1. Single Responsibility Principle
  2. Open/Closed Principle
  3. Liskov's Substitution Principle
  4. Interface Segregation Principle
  5. Dependency Inversion Principle

DRY Principle:  

DRY stands for Do Not Repeat Yourself. Sometimes, There could be a need to use same or similar set of lines of code to be used multiple times in the same application. For ex. String utilities, DB connections or updating records in database etc.

Writing frequently used code snippets multiple times is not a good practice. Instead move this code to a function or method and use this method in places where ever required.

Simple use cases are:

  • DB Connections
  • File IO Operations
  • String Utilities etc. 

Managing Dead Code:

Sometimes there are some lines or instructions in code base, which are completely not executed in all cases at all. This is considered as dead code. 

Dead code reduces the quality with respect to the readability.  


Comments:

Comments increases the readability of the program for programmers. Comments are written at class level, method level and variable level [Constants, instance variables and class variables] differently. 

The reason for this difference is, the pattern of comments is identified by API document generator tools and generates API documents.


Conclusion:

What all I tried to share through this post is, writing code for a specific problem can be done in different ways. But making sure that the program is more readable, maintenance free and easily scalable is also very important. 

The above few solutions or hacks will definitely help in developing better applications. 

Hope you enjoyed reading the post. Comments are welcomed. Thank you!! 

Happy coding!...

Sunday, 9 August 2020

Exception handling and java keywords

Exception:

Exception in a programming language and in English language is pretty similar. Exception means being different from or not following the rules. And in programming language like Java, exception is  an event which occurs during the execution of a program that disturbs the complete flow of application or program.

When something beyond expected happens while executing a program is considered as an error. handling these errors or abnormality is called as Exception handling.


Exception Handling:

Exception handling in java is managed with the help of java keywords and java API support.. 

            1. Java Keywords

            2. Java API support


Java Keywords: 

There are 5 keywords in Java.

          1. Try

          2. catch

          3. finally

          4. throw

   and 5. throws

These five keywords used all together or combination of few keywords are used on need basis.

1. Try:

The code or set of instructions which are prone to errors or exceptions are enclosed in try block.

For example dividing a five or some number with zero [5/0]. The result of 5/0 is undefined and in Java,  this scenario is considered as exception.

2. Catch:

Usually try block is followed by a catch block. If some exception is occurred in try block, the execution control is moved to catch block instead of  continuing the execution of  try block's code. 

The purpose of catch block is, handling the exceptions that are raised in try.

There is a possibility of handling multiple scenarios in multiple catches. 

NOTE: Multiple catches can be written for single try.

Java code example:

           try{

                   ---                     // code

                } catch(OtherException e) {

                   ---                    // code

               }catch(AnotherException e) {

                }      

3. Finally:

Usually if there is an exception in try block, the rest of the lines in try are not executed and control moves on to catch block. And if there is no exception at all in try block control never moves to catch block. Then catch block is considered to be dead code. 

Then where must we write mandatory code? 

So, finally block is written after try and catch which gets executed always. 

Java code example:

            try{

                  ---

                } catch (Exception e) {

                  ---

                } finally{

                  ---              // mandatory code for execution

                } 


NOTE: Always put mandatory code in finally block. For example: closing IO resources connections like network and database connections etc

4. Throws and Throw:

Throws and throw keywords works along with Java API support. I will explain the Java API support for Exception handling in next subsequent articles. 

For now, we can understand that for every exception scenario there is one Java class(Java API). Example: Number divided by zero. [5/0]. The result is ArithmeticException

Java code example:

     try{

               int result = 5/0;

                ---        // other code

         }catch(ArithmeticException e) {

                ---        // exception of try block is handled here   

         }  

  Why there is no "throws" keyword here....?

The alternative solution for above snippet with throws and throw for checking election voting age eligibility exception is:

void votingAgeNumber() throws ArithmeticException{

                int age = 12; 

                if(age <=18) {

                           throw new ArithmeticException("Age is not sufficient to vote");

                 }

                 ---       // other code              

           }

NOTE: Sometimes "throws" keyword works as an alternative solution for try and catch blocks. The throws keyword is used instead of try and catch.

Example:

Solution with throws:

void divideNumber() throws ArithmeticException{

         int result = 5/0;

 } 

 And snippet with try and catch:        

void divideNumber(){

   try{

      int result = 5/0;

    }catch(ArithmeticException e){

     ----      // handle exception

    }

} // method end                      

         

The above both solutions are same, but with different keywords.


 Some key points:

1. There can be one try with multiple catch blocks.

2. Try block can be followed by either catch or finally block.

3. Or both can be followed

4. Throws is like warning that exception can be thrown and throw keyword is real accident took place.


I wrote here  https://www.allabtjava.com/2021/01/java-api-support-for-exception-handling.html on checked exceptions and runtime or unchecked exceptions.



Happy coding... :)





   

Sunday, 29 April 2018

Java and OOPS concepts

Java is an object oriented programming language which can be downloaded and installed in your local Machine from java.com


To explain java binaries and tools requires block diagram which gives clear picture. For now I brief few important tools.

  • JDK - java development toolkit
  • JVM - Java virtual machine
  • JRE - Java Run time environment
From oracle site we can download JDK which is shipped along with JVM and JRM. Mostly java programmers need the JDK. For end users JRE alone is enough.

Basic OOPS characteristics are

Inheritance

Encapsulation

Abstraction

and Polymorphism

The above concepts collectively makes application software extendable and changeable with less effort.
Also helps in Developing design patterns. Design patterns gives solutions for common challenges usually a programmer faces while development applications.
Factory design pattern, Abstract design pattern, Builder pattern etc. I explain these Design patterns in another article.

Inheritance:
Inheritance is all about reusing one class behavior and members in it's child class. In java terminology these classes are called as super class and sub class. If class B extends class A then, class A becomes super class and class B becomes class A's sub class.

public class A{
  public A(){
 }
   -------
}
public class B extends A{
   public B(){
    } 
    -------
}   
Encapsulation:
Encapsulation is a technique of putting the source code all together within a unit. Java uses class and interface as keywords to represent unit. Data Hiding is one of the buzzwords which is possible only with implementation of Encapsulation in the program.

Abstraction:
Abstraction is the concept of hiding the irrelevant data from client/user visibility. To implement this feature java uses abstract keyword. this can be be prefixed to a class and methods. Once the class is abstract class then it's object can not be created. And id one or all methods of same class are followed by abstract keyword it can not be implemented.
The point here is java programming language gives implementation freedom to the developers where ever expected.
Sometimes java program is written to a another programmer rather a end user. Usually this code is called Application programming interface in short API. When a programmer writes a program with the intention to be used by another programmer, He/She may not need all the details [line by line] instruction's description is not required. Right?
The punch line is abstraction helps in showing only relevant data to the client of our program.
One of the mostly used design pattern is abstract factory design pattern.

Polymorphism:
In generic terminology poly means many morph means forms. It means many forms of a single method names.
Polymorphism can be achieved within the class or using inheritance i.e extends keyword.

Overloading and overriding:

Overloading rules:
within the class a same method can be duplicated but accepts different arguments and returns different result
  1.       Number of arguments must be different
  2. Or  Sequence of arguments must be different
  3. Or  Type of the arguments must be different.
Uses:
Let us take a method .
     int add(int a, int b){
        return a+b;
     }

Now let us overload this method to add decimal values
 float add(float a, float b){
     return a+b;
 }
Now based on the arguments passed to the add() respect add() method will be invoked.
Overriding:
Overriding is possible only by using inheritance.For an instance super class has add(int a, int b). and sub class also needs add operation but computes differently. Then programmer simply overrides the add() of super class overrides the add() with his new implementation. 
public class SuperClass{

  int add(int a, int b){
       ....
   }
}

public Subclass extends SuperClass{
@Overrides
int add(int a, int b){
// computes his own add operation
}
} 
In next article I write about tools of JDK and JRE and internals of JVM Java Virtual Machine.

Please click the link for more good look and feel and elegant font

Happy Coding. ;-)


Wednesday, 31 January 2018

Core Java: Immutable objects and mutable objects with an example

Immutable objects and mutable objects with an example 


In object oriented programming language in short OOPS, every problem, precisely every requirement is viewed as an object. Understanding the problem in this point of view brings many good things possible in programming like encapsulation, abstraction, polymorphism and inheritance. Anyways this post is not intended for describing benefits of OOPS.

Object could be any thing. Let us take Car for an instance. Basically car is an object and it has name, wheels, metal body, engine, maximum speed,  gear box etc as properties.

Let us consider the car name is Ferrari, maximum speed is 200 km per hr with 6 gears. While driving the car driver can change the speed of the car and change the gear etc.
So while car is running it's current speed, current gear are considered to be state of the object.
The current speed can be changed using accelerator and gear can be changed using gear box. These can be considered as behavior of the car object. Of course car has a name as well.

 Every object has 3 characteristics they are State, Behavior and Name. 

In our example Ferrari is name of the object. Number of gears, current gear, current speed are State and accelerator and gear box decides the behavior of the car object. In java language object's reference name is name of object and methods which decides state are behavior.  

ImmutableObject ferrari = new ImmutableObject("Ferrari", 200, "Red");

             1. new operator creates the object
             2. ferrari is name of object
             3. Ferrari, 200, and Red are State of object

Objects based upon it's behavior can be categorized into two types. They are 
              1. Immutable objects and 
              2. Mutable objects


Mutable and Immutable objects



Mutable object's state can be changed at run time, where as immutable object's state can not be changed. String class is the ideal example for immutable objects. 
    
The state of an object can be decided at it's creation time or at run time or at both times. If state is decided at creation time and it is restricted not be changed at run time, this object is considered to be an  immutable object. If this can be changed at run time, it is called as mutable object.

If car is automatic [no gears] and it's speed can not be changed at any time, then it is immutable car object.  

Below program creates immutable objects:




01  public final class ImmutableObject {
02
03  private String name;
04
05  private int maxSpeed;
06
07  private String color;
08
09  /**
10  * @param name
11  *            holds car name
12  * @param maxSpeed
13  *            holds maximum speed of the car
14  * @param color
15  *            holds color of car
16  */
17  public ImmutableObject(String name, int maxSpeed, String color) {
18  this.name = name;
19  this.maxSpeed = maxSpeed;
20  this.color = color;
21  }
22
23  public String getName() {
24  return name;
25  }
26
27  public int getMaxSpeed() {
28  return maxSpeed;
29  }
30
31  public String getColor() {
32  return color;
33  }
34
35  public static void main(String[] args) {
36  ImmutableObject ferrari = new ImmutableObject("Ferrari", 200, "Red");
37  System.out.println("Car name: " + ferrari.getName());
38  System.out.println("Car color:" + ferrari.getColor());
39  System.out.println("Car maximum speed:" + ferrari.getMaxSpeed());
40  System.out.println();
41
42  ImmutableObject anotherCar = new ImmutableObject("BMW", 180, "White");
43  System.out.println("Car name: " + anotherCar.getName());
44  System.out.println("Car color:" + anotherCar.getColor());
45  System.out.println("Car maximum speed:" + anotherCar.getMaxSpeed());
46  }
47  }
48

Output:

Car name: Ferrari
Car color:Red
Car maximum speed:200

Car name: BMW
Car color:White
Car maximum speed:180

Explanation


Line 1: First and fore most rule is to make your class final class.

Line 3 to Line 7: All variables are private variables. private access modifier restrics usage of members within the class

Note: Do not use other classes as data types of your instance variables which are mutable in behavior. All of our example variables are of String type. String is immutable. See API document of String class for more information.   


Line 17: Creates parameterised constructor with state which can not be changed at run time

Line 23 to Line 33: Create only those methods which shares it's state to the other classes. As we did in our example ImmutableObject. Allows only getter methods and no setter methods at all.


Line 36 to Line 42: Finally, create 2 objects ferrari and another car with different state which can not be changed at run time..

Now, let us change the same class which allows creating mutable objects:

01
02 public class MutableObject {
03
04 private String name;
05
06 private int maxSpeed;
07
08 private String color;
09
10 private int currentGear;
11
12 private int currentSpeed;
13
14 /**
15 * @param name
16 *            holds car name
17 * @param maxSpeed
18 *            holds maximum speed of the car
19 * @param color
20 *            holds color of car
21 */
22 public MutableObject(String name, int maxSpeed, String color) {
23 this.name = name;
24 this.maxSpeed = maxSpeed;
25 this.color = color;
26 }
27
28 public String getName() {
29 return name;
30 }
31
32 public int getMaxSpeed() {
33 return maxSpeed;
34 }
35
36 public int getCurrentGear() {
37 return currentGear;
38 }
39
40 public void setCurrentGear(int currentGear) {
41 this.currentGear = currentGear;
42 }
43
44 public int getCurrentSpeed() {
45 return currentSpeed;
46 }
47
48 public void setCurrentSpeed(int currentSpeed) {
49 this.currentSpeed = currentSpeed;
50 }
51
52 public String getColor() {
53 return color;
54 }
55
56 public static void main(String[] args) {
57 MutableObject ferrari = new MutableObject("Ferrari", 200, "Red");
58 System.out.println("Car name: " + ferrari.getName());
59 System.out.println("Car colo: " + ferrari.getColor());
60 System.out.println("Car maximum speed:" + ferrari.getMaxSpeed());
61
62 ferrari.setCurrentGear(5);
63 ferrari.setCurrentSpeed(150);
64 System.out.println(String.format("Current speed is %s and current gear is %s \n", ferrari.getCurrentSpeed(), ferrari.getCurrentGear()));
65
66
67 ferrari.setCurrentGear(1);
68 ferrari.setCurrentSpeed(10);
69 System.out.println(String.format("Changed state at run time!.. \nCurrent speed is %s and current gear is %s ", ferrari.getCurrentSpeed(), ferrari.getCurrentGear()));
70
71
72 System.out.println();
73
74 }
75}
76

Output:


Car name: Ferrari
Car colo: Red
Car maximum speed:200
Current speed is 150 and current gear is 5 

Changed state at run time!.. 
Current speed is 10 and current gear is 1 


Explanation

  

Line 2: Remove final keyword. This makes the class extendable using extend keyword

Line 10 to Line 12: Introduced new variables which adds new information to the state of object

Line 40 and Line 48: Introduced new setter methods which changes state at run time.

Line 57: Finally, create the ferrari object and change it's state run time by calling different setter methods.

Line 62 to Line 72: Changes the state by calling setters on member variables.  

Few more details about immutable objects:


  • It is always good practice to use immutable objects in our application especially in concurrent apps where ever applicable
  • Immutable objects ensures correct results/output always in all environments like multi threading environment, collection framework.
  • HashMap<key, value> always requires immutable object as key. Otherwise it behaves in undetermined way.
  • Consider cloning when creating immutable classes. I will post another article about importance of deep cloning and shallow copy in details in near future.
  • Cache memory implementation uses immutable objects 
  • java.lang.String is the most used immutable class in java

    .

Monday, 29 January 2018

Swing JLabel demo with example

This article is continuation of previous post JFrame usage demo. Please read it before continuing.

This post uses the same example code shown in JFrame usage demo with JLabel changes and introduces layout manager BorderLayout.

Layout Manager:

Layout manager is responsible to arrange components on containers. Usually every swing container is created with a default layout manager but can be changed with setLayout() api. For example JFrame uses BorderLayout as default layout amanger.

Java program for JLabel


2   import java.awt.BorderLayout;
3   import java.awt.Color;
4   import java.awt.Font;

6   import javax.swing.JFrame;
7   import javax.swing.JLabel;
8   import javax.swing.SwingUtilities;

10  /**
11   *
12   * Simple class to demonstrate JLabel of swing toolkit
13   *
14   * @author Nagasharath
15   *
16   */
17  public class LabelDemo extends JFrame {
18
19  private final String title = "It's all abt java!...  ";
20
21  private JLabel label;
22
23  /**
24  * set properties of the main window. Title, size of frame and position/location
25  */
26  public LabelDemo() {
27  this.setTitle(title);
28  this.setSize(300, 200);
29  this.setLocationRelativeTo(null);
30  initComponents();
31  }
32
33  /**
34  * instantiates controls controls.
35  *
36  */
37  private void initComponents() {
38  BorderLayout layout = new BorderLayout(20, 10);
39  this.setLayout(layout);
40
41  label = new JLabel("java-gui.blogspot.com");
42  label.setForeground(Color.RED);
43  label.setFont(new Font(Font.MONOSPACED, Font.BOLD, 25));
44  this.getContentPane().add(label, BorderLayout.CENTER);
45  }
46
47  public static void main(String[] args) {
48
49  Runnable r = () -> {
50  LabelDemo demo = new LabelDemo();
51  demo.setVisible(true);
52  };
53  SwingUtilities.invokeLater(r);
54  }
55  }
56


Line 21: Introduced new variable of type JLabel

Line 38 and Line 39: Used BorderLayout as layout manager to arrange label component on JFrame container

Line 41: Instantiated label with a text of String type.

Line 42 and Line 43:  label properties like foreground color, font style, size, type and background etc are specified

Line 44:  Finally added this label to the JFrame using add().

Output:


JFrme with JLabel

Swing: JFrame usage demo

This post helps in understanding usage of JFrame class with an example


Swing toolkit categorizes components into 2 types. They are:

  • Containers
  • Controls

Containers allows Controls to be arranged on them. JPanel, JFrame and JDialog are few which are frequently used.

Controls are components like Buttons, labels, tables etc. These controls are arranged on containers using different layout managers.

All Swing class names starts with J stands for Java which symbolizes swing is pure java! 

Layout Managers:

Layout manager is responsible for laying out controls on containers according to the business requirement. Example layout managers are BorderLayout, GridLayout, GridBagLayout and FlowLayout.

Few points about JFrame:
  • JFrame is considered as a main window of the application.for almost all swing based applications
  • All other controls and containers are created as child components of JFrame
  • JFrama holds special components like  Menu bar, Tool bar etc  

Example program

1 import javax.swing.JFrame;
2 import javax.swing.SwingUtilities;
3
4 /**
5  *
6  * Simple class to demonstrate JFrame container of swing toolkit
7  *
8  * @author Nagasharath
9  *
10 */
11public class FrameDemo extends JFrame {
12
13 private final String title = "It's all abt java!...  ";
14
15 /**
16 * set properties of the main window. Title, size of frame and position/location
17 */
18 public FrameDemo() {
19 this.setTitle(title);
20 this.setSize(300, 200);
21 this.setLocationRelativeTo(null);
22 initComponents();
23 }
24
25 /**
26 * It is used in future articles for instantiating controls like buttons etc.
27 * left empty for now.
28 */
29 private void initComponents() {
30 }
31
32 public static void main(String[] args) {
33
34 Runnable r = () -> {
35 FrameDemo demo = new FrameDemo();
36 demo.setVisible(true);
37 };
38 SwingUtilities.invokeLater(r);
39 }
40}
41


Line 1: Our class FrameDemo extends JFrame hence gets all benefits that JFrame possess    

Line 20: Sets the width 300 and height 200. How ever frame is re sizable at run time

Line 21:  Puts the frame at the center of the desktop monitor

Line 36: Unless call to setVisible(true), frame can not be seen at all.

Line 38: It is always good practice to call setVisible(true) in invokeLater().

Output on Win 10:

The look and feel we see below  is default which is same on all platforms 

This Look and feel can be changed using UIManager class. We see it in coming posts.  

      
JFrame with title


Sunday, 28 January 2018

Java Multi threaded programming basics with Reentrant lock

Java Multi threaded programming basics with Reentrant locks

As we have seen in earlier post that implicit locking mechanism achieved using synchronized keyword slows down the application performance. Hence java concurrency api gives explicit locking mechanism to achieve mutual exclusion among shared object.

How using explicit locks are better than implicit lock?


  • Explicit lock acquires lock per Thread basis and not per method invoke basis. It is inverse in the case of implicit lock.  
  • If a method is synchronized then every invocation of that method involves acquiring and releasing of lock. This process really slows down the application performance. 
  • Hence it is always good idea to prefer reentrent lock or explicit lock to implicit lock.
  • ReentrantLock is a class available in java.util.concurrency package
  • lock() and unlock() methods are used used to acquire and release the lock.
  • Condition class is used in place of Object class wait(), notifyAll() and notify().
  • signal() and await() of Condtion are used mostly 
Let's see the  Java Multi threaded programming basics Producer and Consumer Problem's solution with Reentrent lock.


import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * In {@code BufferImpl} we have seen thread safe 
 * buffer implementation using implicit lock/ synchronization block
 * 
 * This {@code BufferImpl_conc} we see same implementation replacing implicit
 * lock with concurrency utility classes Reentrant Locks
 * 
 * Buffer implementation with ArrayList and with Producer consumer 
 * problem implementation
 * 
 * @author Nagasharath
 *
 */
public class BufferImpl_conc {

   private CopyOnWriteArrayList<String> buffer;
   private final short SIZE = 10;
   private boolean isBufferFull = false;
   private ReentrantLock lock;
   private Condition condition;

  public BufferImpl_conc() {
     buffer = new CopyOnWriteArrayList<String>();
     lock = new ReentrantLock();
     condition = lock.newCondition();
  }

 /**
  * @throws InterruptedException
  */
 private void producesFeed() throws InterruptedException {
    lock.lock();
    try {
       while (true) {
         if (isBufferFull) {
             System.out.println("Started Consuming!....\n");
             condition.signal();
             condition.await();
        }
        buffer.add(String.valueOf(System.nanoTime()));
        if (SIZE <= buffer.size()) {
              isBufferFull = true;
              Thread.sleep(10000);
              System.out.println("Buffer full. Production halts...\n");
       }
     }
    } finally {
        lock.unlock();
    }
 }

 /**
  * @throws InterruptedException
  */
 private void consumesFeed() throws InterruptedException {
    lock.lock();
    try {
       while (true) {
          Iterator<String> iter = buffer.iterator();
          while (iter.hasNext()) {
             String next = iter.next();
             System.out.println("Consuming element: " + next);
             buffer.remove(buffer.indexOf(next));
          }
          isBufferFull = false;
          System.out.println("Started producing!....");
          condition.signal();
          condition.await();
      }
   } finally {
      lock.unlock();
   }
 }
 /**
  * @author Nagasharath
  *
  */
 class ProducerThread extends Thread {
     @Override
    public void run() {
      try {
        producesFeed();
      } catch (InterruptedException e) {
      }
  }
 }

 /**
  * @author Nagasharath
  *
  */
 class ConsumerThread extends Thread {
  @Override
  public void run() {
    try {
      consumesFeed();
    } catch (InterruptedException e) {
    }
  }
 }
 public static void main(String[] args) {
   BufferImpl_conc impl = new BufferImpl_conc();
   ProducerThread producerThread = impl.new ProducerThread();
   ConsumerThread consumerThread = impl.new ConsumerThread();
   producerThread.start();
   consumerThread.start();
 }
}

Most parts of the program are same as we used in the post Java Multi threaded programming basics It is advised to read my post  Java Multi threaded programming basics before reading this. I try to explain changes from earlier post program here

  1 private final short SIZE = 10;
  2 private boolean isBufferFull = false;
  3 private ReentrantLock lock;
  4 private Condition condition;

Line 3: Instance of ReentrantLock is similar to synchronized keyword locking but it is more intelligent.
Line 4: Condition instance has methods which replaces Object class wait and notify() methods.

  1  public BufferImpl_conc() {
  2     buffer = new CopyOnWriteArrayList<String>();
  3     lock = new ReentrantLock();
  4     condition = lock.newCondition();
  5  }
Line 3 and Line 4: Instantiates lock and condition Objects

 1 private void producesFeed() throws InterruptedException {
 2   lock.lock();
 3    try {
 4      while (true) {
 5         if (isBufferFull) {
 6             System.out.println("Started Consuming!....\n");
 7             condition.signal();
 8             condition.await();
 9         }
 10         buffer.add(String.valueOf(System.nanoTime()));
 11         if (SIZE <= buffer.size()) {
 12           isBufferFull = true;
 13           Thread.sleep(10000);
 14           System.out.println("Buffer full. Production halts...\n");
 15         }
 16       }
 17     } finally {
 18          lock.unlock();
 19     }
 20 }
Line 1: await() at line 8 throws InterruptedException
Line 2: lock.lock() statement is equal to the synchronized(this)  {  . . .  }
Line 7: condition.signal() notifies the waiting thread on same object to start it's execution
Line 8: condition.await() makes current thread to wait on isBufferFull == true condition check
Line 17 to Line 19: lock.unlock() must be called in finally block always

Output:  


Buffer full. Production halts...

Started Consuming!....

Consuming element: 2838231927112595
Consuming element: 2838231927212435
Consuming element: 2838231927229502
Consuming element: 2838231927238888
Consuming element: 2838231927246995
Consuming element: 2838231927254675
Consuming element: 2838231927261075
Consuming element: 2838231927267902
Consuming element: 2838231927274302
Consuming element: 2838231927281555
Started producing!....
Buffer full. Production halts...

Started Consuming!....

Consuming element: 2838242029132348
Consuming element: 2838242029210428
Consuming element: 2838242029244561
Consuming element: 2838242029271015
Consuming element: 2838242029386215
Consuming element: 2838242029448935
Consuming element: 2838242029479228
Consuming element: 2838242029504401
Consuming element: 2838242029529148
Consuming element: 2838242029553895
Started producing!....
Buffer full. Production halts...

Started Consuming!....

Consuming element: 2838252029524881
Consuming element: 2838252029547921
Consuming element: 2838252029556881
Consuming element: 2838252029563281
Consuming element: 2838252029568401
Consuming element: 2838252029573521
Consuming element: 2838252029578215
Consuming element: 2838252029582908
Consuming element: 2838252029588028
Consuming element: 2838252029593148
Started producing!....
Buffer full. Production halts...

Started Consuming!....

Consuming element: 2838262032106639
Consuming element: 2838262032149732
Consuming element: 2838262032165092
Consuming element: 2838262032193252
Consuming element: 2838262032204772
Consuming element: 2838262032214585
Consuming element: 2838262032223972
Consuming element: 2838262032233359
Consuming element: 2838262032241892
Consuming element: 2838262032251279
Started producing!....
Buffer full. Production halts...

Started Consuming!....

Consuming element: 2838272040024285
Consuming element: 2838272040065245
Consuming element: 2838272040077619
Consuming element: 2838272040086152
Consuming element: 2838272040093832
Consuming element: 2838272040101512
Consuming element: 2838272040108766
Consuming element: 2838272040115592
Consuming element: 2838272040122845
Consuming element: 2838272040130099
Started producing!....

 

Java desktop GUI.

Graphical user interface in short GUI makes computer users easy to understand and use the application software comfortably. Almost all modern programming languages allows application developers to develop GUIs.

Java has AWT/Swing as default API as part of Java Foundation classes in short JFC which are shipped with JDK. Hence these toolkits can be used directly in our applications with out adding external libraries like jars to our application's class path. But there are some other toolkits which found useful and industry endorsed in developing GUI.

    •      SWT 
    •      JFaces [Framework for SWT]
    •      Java FX
    •      Swing
    •      AWT

AWT:

Abstract window toolkit is available since java first version. AWT uses native operating system resources like Fonts, colors and components like table, tree, dialogues, windows etc.

Few notable points about AWT:
  • AWT is heavy weight. It uses OS resources
  • There are limited components in AWT precisely only components which are available in native OS. 
  • We can not have a new component according to our business logic need. ex: Tri state checkbox or treetable  
  • AWT behaves differently on different platforms
  • Hence it violates the java Platform independence rule
  • The program GUI developed with AWT looks differently on different OSs. Means on linux it renders linux graphics look and feel and on windows platform it renders windows graphics look and feel.   
  • Provides event model API which also used by Swing toolkit

Swing:

  • Swing was designed and developed keeping all cons in mind that are caused due to using AWT toolkit.
  • First of all "Swing is pure java hence it is platform independent." This statement made many good things possible:
Few notable points about Swing:
  •  Swing is light weight. It does not depend on native OS resources 
  •  Unlike AWT, it is extensible. New custom components can be developed according to program  requirement. 
   NOTE: See swingx library in it's official site.
  •  Swing has Pluggable look-and-feel support in short PLAF.
  •  Drag and Drop api, 2D api, internationalization are few among other included in Swing toolkit.
  •  Netbeans IDE itself is a good example for swing based application used allot now a days.
  •  Few GUI experts noticed that Swing is slow and not quite professional for commercial applications

SWT:

Standard Widget toolkit in short SWT is another toolkit for developing Java Desktop GUI based applications.
Compared to Swing it is faster and consistent in performance and Eclipse IDE itself is an example for SWT based applications.
Eclipse is industry endorsed IDE specifically for java based software development.
This is not shipped with JDK. Please see eclipse.org [official site] for more details.
And there are Integrated development environments in short IDE which provides Drag and Drop [DAD] palettes also known as GUI Builders for above toolkits for programmer's convenience.
Mostly used IDEs are:
It is advised to code manually to develop the GUI rather using GUI builders provided by different IDEs. And for beginners.  


Wednesday, 24 January 2018

Every Java programmer must read books

Every Java programmer must read and understand the following books.


1. Effective Java

2. Concurrency in practice

Effective Java:


This book is authored by Joshua Bloch. He took the major role in authoring the java.util package which is [collection framework] one of the java core libraries.

He explains the best practices that every programmer should consider while writing java programs.

Some of them are:


  • Contract between hashcode() and equals() of Object class when programmer overrides one of these methods in their classes
  • Exceptions
  • concurrency: Inter thread communication, synchronization etc
  • Immutable Objects
The above points are few among others.

Concurrency in practice:


This book gives complete explanation about how efficient concurrency is achieved in java programs using concurrency utility classes which were introduced in Java 5 version.

This book is authored by:

  • Brian Goetz
  • Tim peierls
  • Joshua Bloch
  • Joseph Bowbeer
  • David Holmes and
  • Doug Lea


You can get them from amazon in form of hard copy or soft copy or both. Get them soon. :)
  

Sunday, 21 January 2018

CHEAT SHEET for java List interface, LinkedList and ArrayList

Consider Below points before choosing List concrete implementations for your use case: 

  • ArrayList is a linear data structure and  re-sizable/dynamic array
 
  • Initial size can be given. and if not given the default size is 10
 
  • It is always good practice to give initial size and advised not to give very large number as size
 
  • Good programmers prefer ArrayList to LinkedList if retrieval operations is done more frequently than insertion and deletions of elements.
 
  • Better choose LinkedList if insertion and deletion operations are done frequently compared to retrieval operations.
 
  • Lists are not sorted. if required use Collections.sort() to sort
 
  • Collections.sort() uses optimized merge sort [tim sort] on ArrayList
 
  • However legacy merge sort also can be used using a switch. But it is going to be deprecated  in near future 

  • The major difference between ArrayList and LinkedList is RandomAccess behavior 

  • ArrayLists uses Random access indexing where as LinkedLists uses
          Sequential access indexing
 
  • LinkedList carries extra overhead in the form of reference to the next and previous elements other than element's data itself

  • LinkedList uses Doubly LinkedList data structure internally

  • Deque is the java DoubleLinkedList data structure implementation

  • Before choosing List implementation ask yourself below questions 
                    a. Are you aware of initial size? 
                    b. Which operations are used more frequently? [insertion, deletion,
                       retrieval, search, sort are few among others]

  • Search Algorithm: 
                  a. Collections class uses binary search if List is ArrayList
                  b. Collections class uses linear search if List is of type LinkedList


  • ArrayList and LinkedList both uses fast fail iterations.

  • If another thread tries to modify list while iterating, java runtime throws ConcurrentModificationException. This can be considered as fast fail behavior  

Saturday, 30 December 2017

Simple program which demonstrates Swing/AWT Grid layout

Simple program which demonstrates Swing/AWT Grid layout:


This post is intended to the beginners of swing/awt.

This below program creates a JFrame with 2 labels, 2 textfields and 2 buttons.


import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

/**
 * @author Nagasharath Kopalle
 *
 * Simple program to demontrate Gridlayout
 *
 */
public class GridLayoutDemo extends JFrame {

private JLabel labelName = null;

private JTextField textFieldName = null;

private JLabel labelPassword = null;

private JPasswordField passwordFieldPassword = null;

private JButton buttonSubmit = null;

private JButton buttonCancel = null;

/**
*
*/
public GridLayoutDemo() {
initComponents();
}

/**
* instantiates components and adds properties.
*/
void initComponents() {

this.setTitle("Grid Layout Demo");
this.setSize(300, 200);
GridLayout layout = new GridLayout(3, 2);
layout.setHgap(10);
layout.setVgap(5);
labelName = new JLabel("User Name: ");
textFieldName = new JTextField();

labelPassword = new JLabel("Password: ");
passwordFieldPassword = new JPasswordField();

buttonSubmit = new JButton("Submit");
buttonCancel = new JButton("Cancel");

this.setLayout(layout);
this.getContentPane().add(labelName);
this.getContentPane().add(textFieldName);

this.getContentPane().add(labelPassword);
this.getContentPane().add(passwordFieldPassword);

this.getContentPane().add(buttonSubmit);
this.getContentPane().add(buttonCancel);
}

public static void main(String[] args) {

GridLayoutDemo demo = new GridLayoutDemo();
demo.setVisible(true);
}
}

Output:


Sunday, 29 October 2017

Eclipse Java Editor Shortcuts

Eclipse Oxygen Java editor Shortcuts helps in editing source code more comfortably. Frequently used default shortcuts are listed below. 




Description
Shortcut
Delete Line
CTRL + D
Copy Line
CTRL + ALT + Down Arrow
Add method level, class level, member level Comments
SHIFT + ALT + J
Format Java Source code
CTRL + SHIFT + F
Make line commented
CTRL + /
Make multiple lines [block] commented  
CTRL + SHIFT + /
Search selected similar word within the source document
CTRL + K
Select line from beginning to end
SHIFT + End key
Select line from end to beginning
SHIFT + Home key
Select Word by word in same line
CTRL + SHIFT + Right Arrow
Move line above
ALT + Up Arrow
Move line below
ALT + Down Arrow

Shortcuts can be customized and new shortcuts can be created through Keys Page in Preferences wizard.


  1.  Window menu > Go To Preferences 
  2.  Type Keys as the "filter text"
  3.  Please find the image below for reference.


Example:
Add new Shortcut for cut whole line command.

  1.  In Keys page type filter text -- Cut line
  2.  Type your convenient key. In my case I added SHIFT + X
  3.  Finally, Click Apply and Click Apply and Close.
  4.  That's it. Now Test your new Shortcut. 

Happy Coding :)

Saturday, 21 October 2017

Launch Swing GUI always in a dedicated Thread



1. Since Swing is not thread safe, it is not at all a good practice to launch a UI Container like JFrame, JDialog etc in main Thread.
2. Doing so leads to incorrect behavior of java GUI.
3. To avoid this, Swing toolkit has predefined API as part of JFC.
4.    a. SwingUtilities.invokeAndWait(Runnable r);
       b. SwingUtilities.invokeLater(Runnable r);

5. Which part of the code must be in UI Thread?
        a. setVisible(true);
        b. show(); [deprecated]
 and c. pack();
     

6. Call to these methods mentioned in 5(a), 5(b), and 5(c) must happen in one of the methods mentioned in point 4(a) and point 4(b). That's enough. :)
         Example :
             
         public static void main(String[] args){
                         
         JFrame frame = new JFrame();
         frame.setSize(100, 200);
         SwingUtilities.invokeAndWait(new Runnable(){
             public void run(){
                     frame.setVisible(true);
                     frame.pack();
             }//run
        });//
       }//main

  7. Difference between invokeAndWait() and invokeLater():
          a. invokeLater() is non blocking and asynchronous, where as invokeAndWait() is blocking and synchronous.
          b. Since invokeLater() is asynchronous, It is more flexible.
                                 
                                   

Friday, 6 October 2017

File Manager/File Explorer with Swing JTree Component

This post is intended to beginners of java swing toolkit programmers.
It is a simple java program which demonstrates the swing based File explorer GUI.





import java.awt.GridLayout;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

/**
 * @author NagasharathK
 *
 */
public class FileExplorer extends JFrame {

private JTree fileManagerTree = null;

public FileExplorer() {
initComponents();
}

/**
* Initializes components
*/
private void initComponents() {
this.getContentPane().add(new JScrollPane(createFileManagerTree()));
this.setSize(500, 500);
this.setResizable(true);
this.setTitle("File Manager..");
}

/**
* @return JPanel object which contains other comp...
*/
private JPanel createFileManagerTree() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout());

fileManagerTree = new JTree();
fileManagerTree.setModel(new FilesContentProvider("C:\\"));
panel.add(fileManagerTree);
return panel;
}

class FilesContentProvider implements TreeModel {

private File node;

public FilesContentProvider(String path) {
node = new File(path);

}

@Override
public void addTreeModelListener(TreeModelListener l) {

}

@Override
public Object getChild(Object parent, int index) {
if (parent == null)
return null;
return ((File) parent).listFiles()[index];
}

@Override
public int getChildCount(Object parent) {
if (parent == null)
return 0;
return (((File) parent).listFiles() != null) ? ((File) parent).listFiles().length : 0;
}

@Override
public int getIndexOfChild(Object parent, Object child) {
List<File> list = Arrays.asList(((File) parent).listFiles());
return list.indexOf(child);
}

@Override
public Object getRoot() {
return node;
}

@Override
public boolean isLeaf(Object node) {
return ((File) node).isFile();
}

@Override
public void removeTreeModelListener(TreeModelListener l) {

}

@Override
public void valueForPathChanged(TreePath path, Object newValue) {

}

}

/**
* @param args
* @throws InvocationTargetException
* @throws InterruptedException
* @throws UnsupportedLookAndFeelException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws InvocationTargetException, InterruptedException,
ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
FileExplorer explorerUI = new FileExplorer();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
explorerUI.setVisible(true);
}
});
}
}
 

The above program has one inner class [FilesContentProvider] which serves as a model to the JTree.

The UI has 4 Components: JFrame, JScrollPane, JPanel and JTree.

To Do:

  1. Add Context menu to node based upon the file type
  2. Add Cell renderer to give proper names to the Nodes
  3. Option to Expand whole tree or selected node etc..  


Popular posts

Atomicity with Java Programming Language

 Atomicity with Java What is Atomicity Atomicity, in computer science, is considered to be a property [ALL-OR-NOTHING], that the state of a ...