Compare hotel prices and find the best deal - HotelsCombined.com

Tuesday, January 6, 2015

Java Enum and Singleton Pattern

Java Enum and Singleton Pattern

Enum Singleton pattern in JavaFollowing are some reasons which make sense to me for using Enum to implement Singleton pattern in Java. By the way If you like articles on design pattern than you can also check my post on Builder design pattern and Decorator design pattern .

1) Enum Singletons are easy to write
This is by far biggest advantage, if you have been writing Singletons prior ot Java 5 than you know that even with double checked locking you can have more than one instances. though that issue is fixed with Java memory model improvement and gurantee provided by volatile variables from Java 5 onwards but it still tricky to write for many beginners. compared to double checked locking with synchronization Enum singletons are cake walk. If you don't believe than just compare below code for conventional singleton with double checked locking and Enum Singletons:

Singleton using Enum in Java
This is the way we generally declare Enum Singleton , it may contain instace variable and instance method but for sake of simplicity I haven’t used any, just beware that if you are using any instance method than you need to ensure thread-safety of that method if at all it affect the state of object. By default creation of Enum instance is thread safe but any other method on Enum is programmers responsibility.

/**
* Singleton pattern example using Java Enumj
*/
public enum EasySingleton{
    INSTANCE;
}

You can acess it by EasySingleton.INSTANCE, much easier than calling getInstance() method on Singleton.

Singleton example with double checked locking
Below code is an example of double checked locking in Singleton pattern, here getInstance() method checks two times to see whether INSTANCE is null or not and that’s why it’s called double checked locking pattern, remember that double checked locking is broker before Java 5 but with the guranteed of volatile variable in Java 5 memory model, it should work perfectly.

/**
* Singleton pattern example with Double checked Locking
*/
public class DoubleCheckedLockingSingleton{
     
private volatile DoubleCheckedLockingSingleton INSTANCE;
 
     
private DoubleCheckedLockingSingleton(){}
 
     
public DoubleCheckedLockingSingleton getInstance(){
         
if(INSTANCE == null){
            
synchronized(DoubleCheckedLockingSingleton.class){
                
//double checking Singleton instance
                
if(INSTANCE == null){
                    INSTANCE 
= new DoubleCheckedLockingSingleton();
                
}
            
}
         
}
         
return INSTANCE;
     
}
}

You can call DoubleCheckedLockingSingleton.getInstance() to get access of this Singleton class.

Now Just look at amount of code needed to create a lazy loaded thread-safe Singleton. With Enum Singleton pattern you can have that in one line because creation of Enum instance is thread-safe and guranteed by JVM.

People may argue that there are better way to write Singleton instead of Double checked locking approach but every approach has there own advantages and disadvantages like I mostly prefer static field Singleton intialized during classloading as shwon in below example, but keep in mind that is not a lazy loaded Singleton:

Singleton pattern with static factory method
This is one of my favorite method to impelemnt Singleton pattern in Java, Since Singleton instance is static and final variable it initialized when class is first loaded into memeory so creation of instance is inherently thread-safe.

/**
* Singleton pattern example with static factory method
*/


public class Singleton{
    //initailzed during class loading
    private static final Singleton INSTANCE = new Singleton();
 
    //to prevent creating another instance of Singleton
    private Singleton(){}

    public static Singleton getSingleton(){
        return INSTANCE;
    }
}

You can call Singleton.getSingleton() to get access of this class.


2) Enum Singletons handled Serialization by themselves
Another problem with conventional Singletons are that once you implement serializable interface they are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singeton as shwon in below example :

    //readResolve to prevent another instance of Singleton
    
private Object readResolve(){
        
return INSTANCE;
    
}

This can become even more complex if your Singleton Class maintain state, as you need to make them transient, but witn Enum Singleton, Serialization is guarnateed by JVM.

3) Creation of Enum instance is thread-safe
As stated in point 1 since creatino of Enum instance is thread-safe by default you don't need to worry about double checked locking.

In summary, given the Serialzation and thraead-safety guaranteed and with couple of line of code enum Singleton pattern is best way to create Singleton in Java 5 world. you can still use other popular methods if you feel so but I still have to find a convincing reason not to use Enum as Singleton, let me know if you got any.


Understanding Non Functional Requirements

This is a short and crisp article that takes you through some of the most important non functional requirements that an architect should never loose track of. The article shall help you understand each of these non functional requirement from SCEA exam point of view as well. 

Non functional requirements also referred to as system level requirements or qualities of a system are one of the most important things that an architect should never loose focus on during inception and elaboration faces of the project. Of-course they come after the functional requirement as even the most robust, scalable and high performance system is useless if it not able to deliver the required behavior and functionality that is expected out of it. 

In addition to the functional requirement of the system, it is the responsibility of the architect to work with the stakeholders of the system to define and baseline a quality of service measurement for each of the service level requirements. The architecture must address all the non functional requirements.

Depending upon the system domain and various other factors, an architect might have to make trade-offs between these non-functional requirements. This is perfectly fine, provided the stakeholders are kept informed and involved in decision making in this regard.

Following sections of the article briefly describe most of these non-functional requirements that you should address in your architecture. 

Performance

The performance requirement is usually measured in terms of response time for a given screen transaction per user. In addition to response time, performance can also be measured in transaction throughput, which is the number of transactions in a given time period, usually one second. For example, you could have a performance measurement that could be no more than three seconds for each screen form or a transaction throughput of one hundred transactions in one second. Regardless of the measurement, you need to create an architecture that allows the designers and developers to complete the system without considering the performance measurement.

Scalability

Scalability is the ability to support the required quality of service as the system load increases without changing the system. A system can be considered scalable if, as the load increases, the system still responds within the acceptable limits. It might be that you have a performance measurement of a response time between two and five seconds. If the system load increases and the system can maintain the performance quality of service of less than a five second response time, then your system is scalable. To understand scalability, you must first understand the capacity of a system, which is defined as the maximum number of processes or users a system can handle and still maintain the quality of service. If a system is running at capacity and can no longer respond within an acceptable time frame, then it has reached its maximum scalability. To scale a system that has met capacity, you must add additional hardware. This additional hardware can be added vertically or horizontally. Vertical scaling involves adding additional processors, memory, or disks to the current machine(s). Horizontal scaling involves adding more machines to the environment, thus increasing the overall system capacity. The architecture you create must be able to handle the vertical or horizontal scaling of the hardware. Vertical scaling of a software architecture is easier than the horizontal scaling. Why? Adding more processors or memory typically does not have an impact on your architecture, but having your architecture run on multiple machines and still appear to be one system is more
difficult.

Reliability

Reliability ensures the integrity and consistency of the application and all its transactions. As the load increases on your system, your system must continue to process requests and handle transactions as accurately as it did before the load increased. Reliability can have a negative impact on scalability. If the system cannot maintain the reliability as the load increases, then the system is really not scalable. So, for a system to truly scale it must be reliable.

Availability

Availability ensures that a service/resource is always accessible. Reliability can contribute to availability, but availability can be achieved even if components fail. By setting up an environment of redundant components and failover, an individual component can fail and have a negative impact on reliability, but the service is still available due to the redundancy.

Extensibility

Extensibility is the ability to add additional functionality or modify existing functionality without impacting existing system functionality. You cannot measure extensibility when the system is deployed, but it shows up the first time you must extend the functionality of the system. You should consider the following when you create the architecture and design to help ensure extensibility: low coupling, interfaces, and encapsulation.

Maintainability

Maintainability is the ability to correct flaws in the existing functionality without impacting other components of the system. This is another of those systemic qualities that you cannot measure at the time of deployment. When creating an architecture and design, you should consider the following to enhance the maintainability of a system: low coupling, modularity, and documentation.

Manageability

Manageability is the ability to manage the system to ensure the continued health of a system with respect to scalability, reliability, availability, performance, and security. Manageability deals with system monitoring of the QoS requirements and the ability to change the system configuration to improve the QoS dynamically without changing the system. Your architecture must have the ability to monitor the system and allow for dynamic system configuration.

Security

Security is the ability to ensure that the system cannot be compromised. Security is by far the most difficult systemic quality to address. Security includes not only issues of confidentiality and integrity, but also relates to Denial-of-Service (DoS) attacks that impact availability. Creating an architecture that is separated into functional components makes it easier to secure the system because you can build security zones around the components. If a component is compromised, then it is easier to contain the security violation to that component.

Design Principles

Introduction

While designing an application of any size or complexity, the most important thing that an architect should never loose track of are these design principles which are being discussed in the following section. Design principles are the backbone and inspiration behind all design patterns that exist today. If an architect understands these design patterns thoroughly and religiously practice them in his designs then he will mostly get it right no matter whether he knows all design patterns by heart or not. No no, I am not advocating that you don't need to learn design patterns, all I am trying to convey here is that if one understands these design principles it will be a lot easier for one to understand the details and philosophy of design patterns. Knowledge of these design principles in-fact complements one's understanding of design patterns. Following are the core design principles:

The Open Closed Principle

A module should be open for extension but closed for modification. Of all the principles of object oriented design, this is the most important. It originated from the work of Bertrand Meyer2. It means simply this: We should write our modules so that they can be extended, without requiring them to be modified. In other words, we want to be able to change what the modules do, without changing the source code of the modules.

The Liskov Substitution Principle

Subclasses should be substitutable for their base classes. Derived classes should be substitutable for their base classes. That is, a user of a base class should continue to function properly if a derivative of that base class is passed to it.

The Dependency Inversion Principle

Depend upon Abstractions. Do not depend upon concretions. If the the Open Closed Principle states the goal of OO architecture, the DIP states the primary mechanism. Dependency Inversion is the strategy of depending upon interfaces or abstract functions and classes, rather than upon concrete functions and classes. This principle is the enabling force behind component design, COM, CORBA, EJB, etc.

The Interface Segregation Principle

Many client specific interfaces are better than one general purpose interface. The essence of the principle is quite simple. If you have a class that has several clients, rather than loading the class with all the methods that the clients need, create specific interfaces for each client and multiply inherit them into the class.

The Release Reuse Equivalency Principle

The granule of reuse is the granule of release. A reusable element, be it a component, a class, or a cluster of classes, cannot be reused unless it is managed by a release system of some kind. Users will be unwilling to use the element if they are forced to upgrade every time the author changes it. Thus. even though the author has released a new version of his reusable element, he must be willing to support and maintain older versions while his customers go about the slow business of getting ready to upgrade. Thus, clients will refuse to reuse an element unless the author promises to keep track of version numbers, and maintain old versions for a while. Therefore, one criterion for grouping classes into packages is reuse. Since packages are the unit of release, they are also the unit of reuse. Therefore architects would do well to group reusable classes together into packages.

The Common Closure Principle

Classes that change together, belong together. A large development project is subdivided into a large network of interelated packages. The work to manage, test, and release those packages is non-trivial. The more packages that change in any given release, the greater the work to rebuild, test, and deploy the release. Therefore we would like to minimze the number of packages that are changed in any given release cycle of the product. To achieve this, we group together classes that we think will change together. This requires a certain amount of precience since we must anticipate the kinds of changes that are likely. Still, when we group classes that change together into the same packages, then the package impact from release to release will be minimized.

The Common Reuse Principle

Classes that aren’t reused together should not be grouped together. A dependency upon a package is a dependency upon everything within the package. When a package changes, and its release number is bumped, all clients of that package must verify that they work with the new package -- even if nothing they used within the package actually changed. We frequently experience this when our OS vendor releases a new operating system. We have to upgrade sooner or later, because the vendor will not support the old version forever. So even though nothing of interest to us changed in the new release, we must go through the effort of upgrading and revalidating. The same can happen with packages if classes that are not used together are grouped together. Changes to a class that I don’t care about will still force a new release of the package, and still cause me to go through the effort of upgrading and revalidating.

The Acyclic Dependencies Principle

The dependencies betwen packages must not form cycles. Since packages are the granule of release, they also tend to focus manpower. Engineers will typically work inside a single package rather than working on dozens. This tendency is amplified by the package cohesion principles, since they tend to group together those classes that are related. Thus, engineers will find that their changes are directed into just a few package. Once those changes are made, they can release those packages to the rest of the project. Before they can do this release, however, they must test that the package works. To do that, they must compile and build it with all the packages that it depends upon. Hopefully this number is small.

The Stable Dependencies Principle

Depend in the direction of stability.

Information hiding and encapsulation

Information hiding is the principle of segregation of design decisions in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decision is changed. The protection involves providing a stable interface which protects the remainder of the program from the implementation (the details that are most likely to change). 

Low coupling

Coupling is a measure of how strongly one element is connected to, has knowledge of, or relies on other elements. An element with low (or weak) coupling is not dependent on too many other elements. A class, for example, with high (or strong) coupling relies on many other classes. Such classes may be undesirable.

High Cohesion

High Cohesion attempts to keep objects appropriately focused, manageable and understandable. High cohesion is generally used in support of Low Coupling. High cohesion means that the responsibilities of a given element are strongly related and highly focused. Breaking programs into classes and subsystems is an example of activities that increase the cohesive properties of a system. 

Don't forget the network! Minimize round-trips, minimize data transfer

Strategy Pattern in Java with Example

Strategy pattern is one of the useful pattern you can mention while answering such question. It's very popular and there are lots of real world scenario where Strategy pattern is very handy. Many programmer ask me what is the best way to learn design pattern, I say you first need to find how other people use it and for that you need to look at the open source libraries you use in your daily task. JDK API is one such library I use on daily basis and that's why when I explore new algorithms, design pattern, I first search JDK for their usage. Strategy has found its place in JDK, and you know what I mean if you have sorted ArrayList in Java. Yes, combination of ComparatorComparable andCollections.sort() method are one of the best real world example of Strategy design pattern. To understand it more, let's first find out what is Strategy pattern? First clue is in the name itself.  The strategy pattern defines a family of related algorithms e.g. sorting algorithms like bubble sort,quicksortinsertion sort  and merge sort, or compression algorithm e.g. zip, gzip, tar, jar, encryption algorithm e.g. MD 5, AES etc and lets the algorithm vary independently from clients that use it. For example, you can use Strategy pattern to implement a method which sort numbers and allows client to choose any sorting algorithm at run time, without modifying client's code. So essentially Strategy pattern provides flexibility, extensible and choice. You should consider using this pattern when you need to select an algorithm at runtime. In Java, strategy is usually implemented by creating a hierarchy of classes that extend from a base interface known as Strategy. In this tutorial, we will learn some interesting things about Strategy pattern by writing a Java program and demonstrating how it add value to your code.




What is Intent of Strategy Pattern

While learning a new pattern, most important thing to understand is intent, motivation. Why? because two design pattern can have same structure but their intent could be totally different. Even, one of the good example of this theory is State and Strategy pattern. If you look at UML diagram of these two pattern they look identical but intent of State pattern is to facilitate state transition while intent of Strategy pattern is to change the behavior of a class by changing internal algorithm at runtime without modifying the class itself.  That's why Strategy pattern is part of behavioral patterns in GOF's original list. You can correlate Strategy pattern with how people use different strategy to deal with different situation, for example if you are confronted with a situation then you will either deal with it or run away, two different strategy.


Terminology and Structure of Strategy Pattern

This pattern has two main component, Strategy interface and Context class. Strategy interface declares the type of algorithm, it can be abstract class or interface. For example, you can define a Strategy interface with method move(), now this move becomes strategy and different pieces in a game of chess can implement this method to define their moving strategy. For example, Rook will move only horizontal or vertical, Bishop will move diagonally, Pawn will move one cell at a time and Queen can move horizontal, vertical and diagonally.  Different strategy employed by different pieces for movement are implementation of Strategy interface and the code which moves pieces is our Context class. When we change piece, we don't need to change Context class. If a new piece is added, then also your code which take care of moving pieces will not required to be modified. here is UML diagram of Strategy pattern :
Strategy Design Pattern Implementation in Java


Pros and Cons of Strategy Pattern

Every algorithm or pattern has some advantage and disadvantage and this pattern is also no different. Main benefit of using Strategy pattern is flexibility. Client can choose any algorithm at run time, you can easily add new Strategy without modifying classes which uses strategies e.g. Context. This becomes possible because Strategy pattern is based upon Open Closed design principle, which says that new behavior is added by writing new code not by modifying tried and tested old code. If you use Strategy pattern, you will be adding a new Strategy by writing a new class which just need to implement Strategy interface. Because of open closed principle violation, we cannot use Enum to implement Strategy pattern. Though it has some advantage and suits well if you know major algorithm well in advance but you need to modify your Enum class to add new algorithms which is violation of open closed principle. To learn more see here.


Real World Examples of Strategy Design Pattern

JDK has couple of examples of this pattern, first is Collection.sort(List, Comparator)method, where Comparator is Strategy and Collections.sort() is Context. Because of this pattern your sort method can sort any object, the object which doesn't exists when this method was written. As long as, Object will implement Comparator interface (Strategy interface), Collections.sort() method will sort it. Another example is  java.util.Arrays#sort(T[], Comparator < ? super T > c) method which similar to Collections.sort() method, except need array in place of List.


Strategy Pattern Implementation in Java

Here is simple Java program which implements Strategy design pattern. You can use this sample code to learn and experiment with this pattern. The example is very simple, all it does is define a strategy interface for sorting algorithms and use that interface on a method called arrange. This method can arrange object in increasing or decreasing order, depending upon how you implement. In order to arrange object, you need sorting and this is provided by Strategy pattern. This allows you to choose any algorithm to sort your object.


/**
 * Java Program to implement Strategy design pattern in Java. 
 * Strategy pattern allows you to supply different strategy without
 * changing the Context class, which uses that strategy. You can
 * also introduce new sorting strategy any time. Similar example
 * is Collections.sort() method, which accept Comparator or Comparable
 * which is actually a Strategy to compare objects in Java.
 * 
 * @author WINDOWS 8
 */

public class Test {

    public static void main(String args[]) throws InterruptedException {
        
        // we can provide any strategy to do the sorting 
        int[] var = {1, 2, 3, 4, 5 };
        Context ctx = new Context(new BubbleSort());
        ctx.arrange(var);
        
        // we can change the strategy without changing Context class
        ctx = new Context(new QuickSort());
        ctx.arrange(var);
    }

}

interface Strategy {
    public void sort(int[] numbers);
}

class BubbleSort implements Strategy {

    @Override
    public void sort(int[] numbers) {
        System.out.println("sorting array using bubble sort strategy");

    }

}

class InsertionSort implements Strategy {

    @Override
    public void sort(int[] numbers) {
        System.out.println("sorting array using insertion sort strategy");

    }
}

class QuickSort implements Strategy {

    @Override
    public void sort(int[] numbers) {
        System.out.println("sorting array using quick sort strategy");

    }
}

class MergeSort implements Strategy {

    @Override
    public void sort(int[] numbers) {
        System.out.println("sorting array using merge sort strategy");

    }
}

class Context {
    private final Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void arrange(int[] input) {
        strategy.sort(input);
    }
}

Output
sorting array using bubble sort strategy
sorting array using quick sort strategy




Things to Remember about Strategy Pattern in Java

Now let's revise what you have learn in this tutorial about strategy design pattern  :

1) This pattern defines a set of related algorithm and encapsulate them in separated classes, and allows client to choose any algorithm at run time.

2) It allows to add new algorithm without modifying existing algorithms or context class, which uses algorithm or strategies.

3) Strategy is a behavioral pattern in GOF list.

4) Strategy pattern is based upon Open Closed design principle of SOLID.

5) Collections.sort() and Comparator interface is real world example of Strategy pattern.


That's all about how to implement Strategy pattern in Java. For your practice write a Java program to implement encoding and allow client to choose between different encoding algorithm e.g. base 64. This pattern is also very useful when you have situation where you need to behave differently depending upon type e.g. writing a method to process trades, if trades is of type NEW,  it will be processed differently, if it is CANCEL then it will be processed differently and if its AMEND then also it will be handled differently, but remember each time we need to process trade

How to avoid deadlock in Java Threads

 How to avoid deadlock in Java is one of the question which is flavor of the season for multithreading , asked more at a senior level and with lots of follow up questions , though question looks very basic but most of developer get stuck once you start going deep.

questions starts with "What is deadlock ?"
answer is simple , when two or more threads waiting for each other to release lock and get stuck for infinite time , situation is called deadlock . it will only happen in case of multitasking.


How do you detect deadlock in Java ?
though this could have many answers , my version is first I would look the code if I see nested synchronized block or calling one synchronized method from other or trying to get lock on different object then there is good chance of deadlock if developer is not very careful.

other way is to find it when you actually get locked while running the application , try to take thread dump , in Linux you can do this by command "kill -3" , this will print status of all the thread in application log file and you can see which thread is locked on which object.

other way is to use jconsole , jconsole will show you exactly which threads are get locked and on which object.

once you answer this , they may ask you to write code which will result in deadlock ?
here is one of my version

public void method1(){
synchronized(String.class){
System.out.println("Aquired lock on String.class object");

synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
}
}
}

public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");

synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}


If method1() and method2() both will be called by two or many threads , there is a good chance of deadlock because if thead 1 aquires lock on Sting object while executing method1() and thread 2 acquires lock on Integer object while executing method2() both will be waiting for each other to release lock on Integer and String to proceed further which will never happen.

now interviewer comes to final part , one of the most important in my view , How to fix deadlock ? or How to avoid deadlock in Java ?

if you have looked above code carefully you may have figured out that real reason for deadlock is not multiple threads but the way they access lock , if you provide an ordered access then problem will be resolved , here is
the fixed version.





public void method1(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");

synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}

public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");

synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}


 

Now there would not be any deadlock because both method is accessing lock on Integer and String object in same order . so if thread A acquires lock on Integer object , thread B will not proceed until thread A releases Integer lock , same way thread A will not be blocked even if thread B holds String lock because now thread B will not expect thread A to release Integer lock to proceed further.

What is Blocking methods in Java

What is Blocking methods in Java

Example of blocking method in JavaAs I said Blocking methods are those which blocks the current executing thread from further operation until function returns. So if you have just one thread in your program e.g. main thread and you call any blocking method e.g. reading from InputStream, your program will be blocked until reading of file finished. Javadoc clearly mention whether an API call is blocking or not but most of  java IO methods are blocking. If you are doing GUI programming in Java using Swing than knowledge of blocking methods becomes even more important for you, because no body likes freezing or non responsive GUI. methods like invokeAndWait are blocking in nature and should be used only when you are performing some operation on which user should wait for result. In most simple terms blocking means your code in next line will not be executed because Thread which is executing blocking function is waiting for method to return. here is a code example which help you
to understand blocking calls:
public class BlcokingCallTest {
    public static void main(String args[]) throws FileNotFoundException, IOException  {
      System.out.println("Calling blocking method in Java");
      int input = System.in.read();
      System.out.println("Blocking method is finished");
    }  
}
In this code example after executing first print statement your program will be blocked and will not execute second print statement until you enter some characters in console and press enter because read() method blocks until some input is available for reading.

Examples of blocking methods in Java:

There are lots of blocking methods in Java API and good thing is that javadoc clearly informs about it and always mention whether a method call is blocking or not. In General methods related to reading or writing file, opening network connection, reading from Socket, updating GUI synchronously uses blocking call. here are some of most common methods in Java which are blocking in nature:
1) InputStream.read() which blocks until input data is available, an exception is thrown or end of Stream is detected.
2) ServerSocket.accept() which listens for incoming socket connection in Java and blocks until a connection is made.
3) InvokeAndWait() wait until code is executed from Event Dispatcher thread.

Disadvantages of blocking method:

Blocking methods poses significant threat to scalability of System. Imagine you are writing a client server application and you can only serve one client at a time because your code blocks. there is no way you can make use of that System and its not even using resources properly because you might have high speed CPU sitting idle waiting for something. Yes there are ways to mitigate blocking and using multiple threads for serving multiple clients is a classical solution of blocking call. Though most important aspect is design because a poorly designed system even if its multi-threaded can not scale beyond a point, if you are relying solely of number of Threads for scalability means it can not be more than few hundred or thousands since there is limit on number of thread JVM can support. Java5 addresses this issue by adding non blocking and asynchronous alternative of blocking IO calls and those utility can be used to write high performance
servers application in core Java.

Best practices while calling blocking method in Java:

Blocking methods are for a purpose or may be due to limitation of API but there are guidelines available in terms of common and best practices to deal with them. here I am listing some standard ways which I employ while using blocking method in Java
1) If you are writing GUI application may be in Swing never call blocking method in Event dispatcher thread or
in the event handler. for example if you are reading a file or opening a network connection when a button is clicked
don't do that on actionPerformed() method, instead just create another worker thread to do that job and return from
actionPerformed(). this will keep your GUI responsive, but again it depends upon design if the operation is something which requires user to wait than consider using invokeAndWait() for synchronous update.
2) Always let separate worker thread handles time consuming operations e.g. reading and writing to file, database or
socket.
3) Use timeout while calling blocking method. so if your blocking call doesn't return in specified time period, consider
aborting it and returning back but again this depends upon scenario. if you are using Executor Framework for managing
your worker threads, which is by the way recommended way than you can use Future object whose get() methods support timeout, but ensure that you properly terminate a blocking call.
4) Extension of first practices, don't call blocking methods on keyPressed() or paint() method which are supposed to
return as quickly as possible.
5) Use call-back functions to process result of a blocking call.

A word of caution:

Though multi-threading is a workaround of blocking method it poses its own risk like thread-safety and race condition.
Java 5 also provides better alternatives of blocking IO methods wrapped in java.nio package.
That's all on Blocking methods in Java and some of best practices to use while calling blocking functions. let's know
what is your experience while using blocking IO methods and what standard code practices you follow while using these
methods.


Important points:

1. If a Thread is blocked in a blocking method it remain in any of blocking state e.g. WAITING, BLOCKED or TIMED_WAITING.
2. Some of the blocking method throws checked InterrupptedException which indicates that they may allow cancel the task and return before completion like Thread.sleep() or BlockingQueue.put() or take() throws InterruptedException.
3. interupt() method of Thread class can be used to interuupt a thread blocked inside blocking operation, but this is mere
a request not guarantee and works most of the time.