JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Your Guide to the 4 Best GUI for Managing MongoDB

August 10, 2016 by Krishna Srinivasan Leave a Comment

MongoDB is an open source, NoSQL database that is incredibly dynamic. For some users, MongoDB databases and their content can be best accessed using a GUI (graphical user interface), which is essentially like a dashboard to manage the database and manipulate the data. There are many free MongoDB graphical user interfaces out there, and some are better than others. Here’s a list of some of the best MongoDB GUIs:

1. MongoChef

GUI

MongoChef is a multi-platform desktop GUI with full support for MongoDB. It allows for in-place data editing, and features a drag and drop search query builder.

2. MongoBooster

GUI

MongoBooster is a free MongoDB GUI that offers a query builder, in-place editing, and an IntelliSense feature that knows all completions, methods, ids, variables, etc.

3. MongoVue

GUI

This GUI is only for Windows, but it offers the same great features as the GUIs listed above and is a good option for someone who would like a MongoDB manager built specifically for Windows OS.

4. RoboMongo

GUI

RoboMongo is a cross-platform MongoDB GUI. RoboMongo sets itself apart from the other MongoDB managers because it’s the first and only MongoDB GUI that embeds the real MongoDB shell.

Filed Under: Java Tagged With: MongoBooster, MongoChef, MongoVue, RoboMongo

5 Ways to Streamline Your Node.js Applications

July 28, 2016 by Krishna Srinivasan Leave a Comment

5 Ways to Streamline Your Node.js Applications
Photo credit to Hacker Noon

Node.js is already a really efficient way to build quick web applications, but there’s always room for improvement. Think about implementing any of these tips into your Node.js app if you’re looking to speed up or clean up your applications.

 

  1. Use Caching

Caching is such a simple way to improve the performance of your Node.js apps. Use it to fetch frequently used data that doesn’t run or change often. Set a variable once to grab the data in question and then re-use it throughout every request.

2. Use NginX

NginX
Photo credit to Nginx

NginX is a lightweight server that you can use in conjunction with Node.js to serve static content to your server. Because Node.js isn’t intended to serve static content, using NginX to for this purpose will prevent Node.js from doing any unnecessary work, which in turn will make your app faster and more efficient.

3. Remove Unnecessary Processes 

If you’re using a pre-built application, chances are there are modules and middleware within the app that you don’t need or won’t use for your site. Go through and remove anything that isn’t essential, OR sees if you can find more lightweight solutions for any modules that you might want to keep.

4. Enable gzip Compression

When you use gzip compression it allows for the server to compress requests before sending them to the browser (if the browser is gzipped compatible). This can significantly speed up the amount it times for a browser to fetch certain files and is definitely worth enabling on your Node.js apps.

5. Minify and Concatenate your CSS/JS files

This one might seem obvious because really it applies to any sort of app,  including one built using Node.js. Minifying and combining all of your CSS and your JS files into one (one for CSS, one for JS) makes things so much quicker and because there will be significantly fewer HTTP requests to be made.

Filed Under: Java, NodeJS Tagged With: Caching, CSS/JS files, HTTP requests, NginX, Node.js

Array Vs ArrayList in Java

March 3, 2016 by Krishna Srinivasan Leave a Comment

What is the difference between Array and ArrayList is the quite common question for the Java interview and for the beginners who are learning Java programming. I have started writing the Java best practices series, this is one of the post for clearing the air on misconception about popular Java classes Array and ArrayList.

Array vs ArrayList
Array vs ArrayList

1. Flexible Storage

One of the major difference between Array and ArrayList is that, Array has the fixed length and it can not be extended once it is initialized. Here is the simple construct for initializing the arrays which I have taken from Java Arrays Example:

[code lang=”java”]
int weight[ ]= new int[5];
weight[0]=36;
weight[1]=42;
weight[2]=24;
weight[3]=10;
weight[4]=50;
[/code]

If you look at the above example, array variable weight is initialized with the length 5, it can not accommodate more than 5 elements.
Whereas ArrayList can dynamically increase the size when new elements are added. Look at the following code:

[code lang=”java”]
ArrayList<String> list = new ArrayList<String>();
[/code]

When you create the above object, the default size of 10 is internally assigned for storing the values. However, when you add the eleventh element, the ArrayList size will be extended to another 10 elements. This impacts the performance of your programming if it has to increase multiple times for accommodating more elements.

2. Generics

Arrays can not use the Generics programming introduced in Java 5. Array knows the type which it can hold, otherwise it will throw the ArrayStoreException when you try to store the wrong data type.

Whereas one of the great advantages of the collections programming is to use the generics for specifying the type of the objects an ArrayList can store. This provides the type-safety for your code at compile time itself.

3. Length / Size

Arrays provide the method length for accessing the size of an array. Even though you have not stored any elements in the array, this method will always returns the capacity of the array.

ArrayList or any other collections APIs that implements List interface defines the method size accessing the size of the object. Note that size method of ArrayList returns only the number of elements currently stored, to know the maximum elements that can be stored in the ArrayList can be accessed using the method capacity.

4. Primitives and Objects

Arrays can be created for either primitives or objects. It can store primitive types as well as objects.

ArrayList can hold only the objects using the add method. Since the Java 5 version, though you store the primitive types to an ArrayList, it silently converts (autoboxing in Java 5) the primitive value to corresponding wrapper class and stores it. All the collection APIs support only storing of the objects and not the primitive values.

5. Iterator

One of the greatest advantage of storing the objects in the collections API is use of iterator for iterating the elements. But, this feature is not available with the Arrays, we have to do the manual iteration using for loop or while loop constructs.

6. Performance

There is no difference in terms of performance between Array and ArrayList classes. They both offer the similar performance for storing and retrieving the objects. If you are storing the thousands of objects in your application, you can measure the performance difference between Array and ArrayList. ArrayList internally uses the Array for storing the objects.

If you are performing the resize() operation or automatic resizing of the ArrayList, the it will impact the performance.

Best Practice

The recommendation is only my opinion and not to be taken as universal best practice for the use of Array vs ArrayList in your projects. I would recommend using the ArrayList every where because it offers the lot of flexibility for storing the objects. If you want thread safety, choose Vector instead of ArrayList.

 

 

Filed Under: Java Tagged With: Java Basics

Maven : updatePolicy Configuration in Settings XML file

March 2, 2016 by Krishna Srinivasan Leave a Comment

One of the most common thing when working with dependency management is how often our local repository has to sync up with the remote repository. Maven has updatePolicy settings for specifying the frequency to check the updates in the repository. Most of the times this value is left blank in the configuration files, the default value is daily. This tutorial explains the use of this element in the settings.xml (global configuration file used for maven repository) file and what are the possible values that can be used for the updatePolicy element.

Maven updatePolicy Settings
Maven updatePolicy Settings

Here is the sample configuration snippet for setting the updatePolicy value:

[code lang=”xml”]
<pluginRepositories>
<pluginRepository>
<id>Releases</id>
<url>http://<host>:<port>/nexus/content/repositories/releases/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
[/code]

In the above example snippet, the settings tells the Maven that Releases repository (configured in local) has to check the remote repository for the artifacts every day. If it finds any updates to the artifacts, then it will download to the local repository. The timestamps are compared to the local POM’s timestamps (stored in a repository’s maven-metadata file). The possible choices for updatePolicy element are:

  • always
  • daily (this is the default value if you don’t specify any values
  • interval:X (where X is an integer in minutes)
  • never

Note that updatePolicy element itself an optional configuration. If don’t specify anything, it will take the default value. However, it is recommended to use always to download the latest updates available when ever uploaded to the repository. But, you should never use the value never for the updatePolicy. Sometimes, you may get the following error in the maven pom.xml file.

  • Also Read : How to create simple Java project using Maven

updatePolicy also applies to Maven meta data, For example, which versions are available and which one is the most current one. So, if there are any artifact versions already present in your local Maven repository, Maven will never download any version that is not yet present in your local repository. It will not download the newer versions from the remote repository.

[code]
Failure to find org.jfrog.maven.annomojo:maven-plugin-anno:jar:1.4.0 in http://myrepo:80/artifactory/repo was cached in the local repository, resolution will not be reattempted until the update interval of MyRepo has elapsed or updates are forced -> [Help 1]
[/code]

The cause of this issue is that, in the local repository the file is not available. You can solve this problem by forcing the updates like this:

[code]
mvn clean install -U
[/code]

Here -U means force updates.

Also Read : Create Web Application using Maven

I hope this tutorial helped you to understand the concepts of using updatePolicy element in the maven’s settings file. If you have any questions, please write it in the comments section.

 

Filed Under: Java Tagged With: Apache Maven Configurations

Thread Dumps in Java

February 16, 2016 by Krishna Srinivasan Leave a Comment

A thread dump is a collection of active threads running on JVM. In other words, it is snapshot of current state of all the Java threads running on JVM. The threads could be either invoked by your own application or that is managed by the JVM itself. But, all the threads will be captured and stored when you instruct JVM to get the thread dump.

Thread dumps are very helpful when your application has performance issue, by taking the thread dumps, you will be able to analyze if there is any deadlock between two threads or there is insufficient memory to execute all the threads. Deadlocks bring some or all of an application to a complete halt.

It is very simple to take the thread dumps from running JVM. There are several ways to take the thread dump from JVM. It is highly recommended to take more than 1 thread dump. A good practice is to take 5 to 10 thread dumps at a regular interval (eg. 1 thread dump every 10 seconds). This is because, taking multiple thread dumps helps you to see the different state of each thread for certain duration and get more knowledge on each thread activities.

Java Thread Dumps

How to take thread dumps in Windows?

If you are running your server in Windows, then use the following command to take the thread dumps:

[code]
CTRL + BREAK (or)
CTRL + Fn + PAUSE (or)
CTRL + ALT + ESC
[/code]

Sometimes you may not find the right keys in your system to initiate the command, so I have listed some of the possible combinations of keys that are used for taking the thread dumps in Windows operating system.

If you are trying to take the thread dump from Tomcat server when it is running on the command prompt, then directly press the above keys in the command prompt, it will display the details of thread dumps. You just have to copy the information and paste it into a text document for the further analysis. The process of taking the thread dumps could be different for each servers.

Here is a example thread dumps I have taken from the tomcat server:

[code]
– locked <0x29a002f8> (a [Lorg.apache.catalina.Service;)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
– locked <0x29907fb0> (a org.apache.catalina.core.StandardServer)
at org.apache.catalina.startup.Catalina.start(Catalina.java:689)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)
"VM Thread" prio=10 tid=0x01927000 nid=0x32cc runnable
"VM Periodic Task Thread" prio=10 tid=0x0194ec00 nid=0x20e4 waiting on condition
JNI global references: 170
Heap
def new generation total 9792K, used 8850K [0x242f0000, 0x24d80000, 0x2984000
0)
eden space 8768K, 89% used [0x242f0000, 0x24aa1ff8, 0x24b80000)
from space 1024K, 94% used [0x24b80000, 0x24c72b20, 0x24c80000)
to space 1024K, 0% used [0x24c80000, 0x24c80000, 0x24d80000)
tenured generation total 21588K, used 13680K [0x29840000, 0x2ad55000, 0x342f0
000)
the space 21588K, 63% used [0x29840000, 0x2a59c128, 0x2a59c200, 0x2ad55000)
compacting perm gen total 12288K, used 5865K [0x342f0000, 0x34ef0000, 0x382f00
00)
the space 12288K, 47% used [0x342f0000, 0x348aa410, 0x348aa600, 0x34ef0000)
ro space 10240K, 45% used [0x382f0000, 0x38771888, 0x38771a00, 0x38cf0000)
rw space 12288K, 54% used [0x38cf0000, 0x393704f8, 0x39370600, 0x398f0000)
Feb 16, 2016 5:04:10 PM org.apache.catalina.util.SessionIdGenerator createSecure
Random
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRN
G] took [185] milliseconds.
Feb 16, 2016 5:04:11 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive
[/code]

Thread Dumps in Tomcat

How to take thread dumps in Unix/Linux?

Run the following command to take the thread dump in Unix or Linux machines:

[code]
Kill –3 process_id
[/code]

You can use the following command to get the process id for Java:

[code]
ps -ef | grep java
[/code]

When you run the above command, the thread dump will be sent to where ever the standard output is redirected to.
(In tomcat server, by default the thread dump will be sent to TOMCAT_HOME/logs/Catalina.out). QUIT command signal does not actually kill the java process. The thread dump will be sent to the standard output and the process will continue running.

How thread dump request works internally?

When you are invoking the command to request the JVM to send the thread dump, the following steps occurs inside JVM,

  1. The Java process will be paused and all the threads currently running will be halted immediately.
  2. The main Java thread will request all the threads to provide details of what they are doing at the moment.
  3. The thread dump will be sent to standard output either it is a log file or console to print the details.
  4. The Java process will continue the job and all the threads will resume their work.
  5. This task takes only few seconds to accomplish and then resume where they left off.

I hope this tutorial helped you to understand the thread dumps in Java and how to get them using commands in Windows / Unix / Linux operating systems. If you have any questions, please write it in the comments section.

Filed Under: Java Tagged With: Java Performance Tuning

How To Use Source and Target Parameter in Java Compiler

February 15, 2016 by Krishna Srinivasan Leave a Comment

If you are a Java programmer, then one of the common question comes into mind is How do I compile for compatibility with older versions of Java?. When you run your Java  program with an older version of the Java runtime environment, you may get the following Java exception if you have not compiled with the right version of Java language:

[code]
Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version number in .class file
[/code]

In one of my previous example, I have explained about how to check the version number of the Java from the class file. In this tutorial I am going to explain the two parameters, target and source which are used for cross compilation and runtime requirements of your Java application.

If you want to ensure the application has to support the minimum runtim environment, then you have to fully understand how to use the source and target parameter for javac.  Java compiler javac have the option to set the target runtime environment supported for your application by using the command line arguments target while compiling the source code.

Javac Source and Target Parameters

Javac Source and Target Example

Source parameter tells the compiler that the source code will be compiled with the specific version. The official documentation says the source parameter provides source compatibility with specified release. If you are compiling the source code with Java 1.6, but if the code is having some specific features in the Java 7, then compilation fails. In that case you have to set the source parameter as the Java 1.7.

The following are the accepted parameter value for the release:

  • 1.3 – The compiler does not support assertions, generics, or other language features introduced after JDK 1.3.
  • 1.4 – The compiler accepts code containing assertions, which were introduced in JDK 1.4.
  • 1.5 – The compiler accepts code containing generics and other language features introduced in JDK 5.
  • 5 – Synonym for 1.5.
  • 1.6 – This is the default value if you are compiling with JDK 6. No language changes were introduced in Java SE 6. However, encoding errors in source files are now reported as errors, instead of warnings, as previously.
  • 6 – Synonym for 1.6.
  • 1.7 – This is the default value. The compiler accepts code with features introduced in Java SE 7.
  • 7 – Synonym for 1.7.

Target parameter tells the compiler that what is the minimum targeted JVM that can run the class files. If you pass the target parameter as 1.5, then the class files compatible to run 1.5 and above version of JVM. But, it can not run below 1.5 JVM.

The default for -target depends on the value of -source:

  • If -source is not specified, the value of -target is 1.6
  • If -source is 1.2, the value of -target is 1.4
  • If -source is 1.3, the value of -target is 1.4
  • For all other values of -source, the value of -target is the value of -source.

Let’s look at the below example command:

[code]
% javac -source 1.6 -target 1.5
[/code]

The above code conveys the message that, the code base will be compiled with the Java 1.6 version, but the targeted minimum environment support is Java 1.5. In other words, converted class files are compatible to with 1.6 JVM.

Ant – Source and Target

How to use the source and target parameter of javac can be used in the apache ant script?. Let’s look at the below code snippet of ant script:

[code lang=”xml”]
<target name="compile">
<javac source="1.5" target="1.5" srcdir=…/>
</target>
[/code]

Maven – Source and Target

This section provides the sample code snippet for using the source and target parameters of javac in the maven’s pom.xml file.

[code lang=”xml”]
<project>
[…]
<build>
[…]
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
[…]
</build>
[…]
</project>
[/code]

Removing Support for the older versions

There is a JEP 182 which talks about retiring the old version from the support to reduce the cost to maintain multiple versions.

Oracle wants reduce the maintenance costs of javac, so the new JEP 182 defines a policy for retiring old -source and -target options. From JDK 8, use of a source or target of 1.5 or earlier is deprecated and in JDK 9, support for a source or target of 1.5 or earlier will be completely removed.

From JDK 9 and going forward, javac will use a “one + three back” policy of supported source and target options. Under this policy, javac will still be able to recognize and process class files of all previous JDKs, going back to version 45.3 class files generated by JDK 1.0.2, which first shipped in 1996.

Filed Under: Java Tagged With: Java Basics

Difference Between Abstract Class and Interface in Java

February 14, 2016 by Krishna Srinivasan Leave a Comment

One of the basic Java interview question is what is the difference between abstract class and interface. If you are a beginner in Java, you can not avoid this question in any Java interview to test your knowledge on Java OOPs concepts. In this short tutorial I will write down the difference between abstract class and interface in Java. Also there is few simple examples for abstract class and interface.

The below table presents the key differences:

Abstract Class in Java
Interface in Java
1 An abstract class can have instance methods that would have default implementation Interface is implicitly abstract and can not have any default method implementation. But, with Java 8, interfaces can have method implementation using the default keyword.
2 Abstract class doesn’t support multiple inheritance. Interface supports multiple inheritance.
3 Abstract class can have constructors. Interfaces can not declare a constructor.
4  Abstract class can extend only one class or one abstract class at a time  Interface can extend any number of interfaces at a time
5  abstract  class  can extend from a class or from an abstract class  interface can extend only from an interface
6  abstract  class  can  have  both  abstract and concrete methods  interface can  have only abstract methods
7  A class can extend only one abstract class  A class can implement any number of interfaces
8  In abstract class keyword ‘abstract’ is mandatory to declare a method as an abstract  In an interface keyword ‘abstract’ is optional to declare a method as an abstract
9  Abstract  class can have  protected , public and public abstract methods. There is no implicit behavior for the members.  Interface can have only public abstract methods. The members of interface are implicitly public by default. Also interfaces can not have static methods.
10  Abstract class can have  static, final  or static final  variable with any access specifier  Interface members are implicitly static and final by default.

Abstract Class Example

[code lang=”java”]
public abstract class AbstractClass{
public int i = 10;
public void abstract abstractMethod();
public void methodImpl(){
System.out.println("Default Method Implementation");
}
}

class ClassImpl extends AbstractClass{
public void abstractMethod(){
System.out.println("Method Implementation in Sub Class");
}
}
[/code]

Interface Example

[code lang=”java”]
public class InterfaceExample{
public static final i = 10; //public, static, final keywords are optional.
public void abstractMethod(); //This method is implicitly abstract
public void methodImpl(){ // This method is not legal. Method implementation not allowed in interfaces.

}
}
[/code]

Filed Under: Java Tagged With: Java Basics

Top 11 Java Exception Best Practices

February 13, 2016 by Krishna Srinivasan Leave a Comment

In my previous tutorial about Java exceptions, I have covered suppressed exceptions and java exception handling. It is one of the important coding practice to do efficient and foolproof exception handling for your projects. To achieve that, you must have a good knowledge on best practices used for exception. This tutorial will highlight the most significant best practices used by the Java programmers to improve the quality of exception handling. If you have any questions, please write it in the comments section.

Java Exceptions Best Practices

1. Do not suppress / swallow the exception in catch block

[code lang=”java”]
public class ExceptionExample {
public FileInputStream testMethod1(){
File file = new File("test.txt");
FileInputStream fileInputStream = null;
try{
fileInputStream = new FileInputStream(file);
fileInputStream.read();
}catch (IOException e){
return null;
}
return fileInputStream;
}
public static void main(String[] args){
ExceptionExample instance1 = new ExceptionExample();
instance1.testMethod1();
}
}
[/code]

Swallowing the exception is one of the bad practice in the exception handling. In the above example, whatever exception thrown will be ignored completely and there is no clue on where is the problem. It is always best practice to throw the exception back to outer layer or handle the exception and perform some alternative solution.

[code lang=”java”]
public class ExceptionExample {
public FileInputStream testMethod1() throws IOException{
File file = new File("test.txt");
FileInputStream fileInputStream = null;
try{
fileInputStream = new FileInputStream(file);
fileInputStream.read();
}catch (IOException e){
throw e;
}
return fileInputStream;
}
public static void main(String[] args) throws IOException{
ExceptionExample instance1 = new ExceptionExample();
instance1.testMethod1();
}
}
[/code]

2. Declare specific exception in throws clause of method block

Writing like the below throws clause defeat the whole purpose of the checked exceptions:

[code lang=”java”]
public FileInputStream testMethod1() throws Exception{
[/code]

This is not good practice. We must always try to use the most specific exception class that are thrown from the program. The most appropriate throws clause would be:

[code lang=”java”]
public FileInputStream testMethod1() throws IOException{
[/code]

3. Catch specific exception classes

It is always good idea to catch the specific classes that are thrown from the application. If there are multiple exceptions thrown from the application that are falls under the same type, catching only the super class is not an good idea.

For instance, if your code is throwing both FileNotFoundException and IOException, have two catch clauses for both the exceptions on hierarchy instead of writing one catch clause with IOException or in worst cases just writing catch clause for Exception.

Here is the correct way to catch the specific exception class:

[code lang=”java”]
try {
//some statements
catch(FileNotFoundException e){
//handle here
}
catch(IOException e){
//handle here
}
[/code]

You should never catch the exception like this:

[code lang=”java”]
try {
//some statements
catch(Exception e){
//handle here
}
[/code]

4. Release the resources in Finally block

When you are opening a database connection, file operations or any other resources centric operations would be closed properly, otherwise that will lead to a performance issue for your application. For instance, when you have opened a database connection and performing CRUD operations, any exceptions thrown will leave the connection open for ever and it will never be closed.

To avoid the worst scenario, it is always good practice to close the opened resources in the finally block. Here is example code for closing the database connections in the finally block:

[code lang=”java”]
finally {
try {
if (con != null) {
con.close();
}
if (stat != null) {
stat.close();
}
} catch (SQLException sqlee) {
sqlee.printStackTrace();
}
}
[/code]

Next time when you see your team member not using the finally block for closing the resources, pinch him to follow the best practice :).

5. Exceptions Impacts Performance

Java Exceptions Performance

Exceptions are very very expensive. This statement should be remembered by every Java programmer while they are writing the code. Creating an exception is very slow operation and throwing an exception cost you around 1-5 microseconds. When the exceptions are propagated to multiple levels, then it will slow down the entire application.

  • Use the exceptions in the exceptional conditions
  • Use the exceptions when it is recoverable

While exception usage is good you should better avoid capturing too many stack traces in your program. In many cases they are not even necessary to understand the problem – especially if they cover a problem you already expect. The exception message therefore might prove as being enough information.

6. Use Standard Exceptions

Don’t write your custom exceptions if the problem can be dealt with the in-built exceptions. Java API itself provides hundreds of  exceptions for various conditions. First try to use the same exceptions for your application, if that is not sufficient and not providing meaning of your business scenario, then create your own custom exceptions.

If you use the in-built exceptions, then any new developer or outside world also will be able to understand the code. You need not lock your code with your own API.

7. Wrap the exceptions correctly

When you re-throw your applications, it is important to wrap the original exceptions properly, otherwise the origin of the exceptions will be lost. Look at the example:

[code lang=”java”]
import java.io.IOException;
public class HelloWorld{
public static void main(String []args) throws Exception{
try{
throw new IOException("IOException");
}catch (IOException e){
throw new ExampleException1("Example Exception and " + e.getMessage());
}

}
}
class ExampleException1 extends Exception{
public ExampleException1(String s, Throwable t){
super(s,t);
}
public ExampleException1(String s){
super(s);
}
}
[/code]

Output for the above program will be as below:

[code]
Exception in thread "main" ExampleException1: Example Exception and IOException
at HelloWorld.main(HelloWorld.java:8)
[/code]

In the above output, the IOException stack trace is lost because we have not used the correct constructor to wrap the exceptions. Modify the catch block as below, this the proper way of wrapping the exceptions:

[code lang=”java”]
catch (IOException e){
throw new ExampleException1("Example Exception",e);
}
[/code]

The output will be:

[code]
Exception in thread "main" ExampleException1: Example Exception
at HelloWorld.main(HelloWorld.java:8)
Caused by: java.io.IOException: IOException
at HelloWorld.main(HelloWorld.java:6)
[/code]

8. Avoid throwing exception from finally block

[code lang=”java”]
try {
method(); //here throws first exception
} finally {
shutdown(); //If finally blockthrew any exception the first exception will be lost forever
}
[/code]

In the above example snippet, note that there is a possibility of finally block also would thrown an exception. If it throws an exception, then first exception will be lost in case both the exception thrown at the same time. It is good practice to handle the exception in finally block or log the error messages. But, never thrown any exception from the finally block.

9. Don’t use exceptions for flow control

You should never use exception for controlling the flow of your program. For example, instead of using the if condition, using exception to validate a scenario is one of the worst practice that impacts the performance if your application.

10. Don’t catch Throwable class

You should never catch Throwable class in your program. Error also subclass of Throwable class, the errors are not even recoverable by the JVM itself.

11. Document the exceptions

Make it a habit to document all the exceptions in your application. When you write a custom exception in your application, no one else in the world other than you know the cause for that exception :). So, you must do a favor to your team by writing a good explanation about the cause of that exception and how to handle it. Trust me, that will be a great help when needed.

 

Filed Under: Java Tagged With: Java Exceptions

java.net.ConnectException Example

February 12, 2016 by Krishna Srinivasan Leave a Comment

java.net.ConnectException is thrown when client socket is not able to connect to the server socket. java.net.ConnectException is subclass of java.net.SocketException. In this short tutorial, I am going to write a simple program for client socket that sends message to the server socket. Then server socket process the message and prints it. When there is a issue in client for connecting to the server socket, java.net.ConnectException will be thrown. Please read our previous article on WebSocket Support in Java EE 7.

Following are the most common scenarios when this exception is thrown:

  • When server is not started and client is trying to connect to the server
  • When client is trying to connect to the wrong port number
  • When client is trying to connect to the wrong host name or IP address
  • When server and client is located remotely. But, they are in the different network where connection is not allowed.

java.net.ConnectException Example

Here is the simple example that demonstrates the ConnectException.

[code lang=”java”]

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ConnectExceptionExample {
public static void main(String[] args) {
new Thread(new ExampleServer()).start();
new Thread(new ExampleClient()).start();
}
}

class ExampleServer implements Runnable {
@Override
public void run() {
ServerSocket serverSocket = null;
while (true) {
try {
serverSocket = new ServerSocket(1111);
Socket clientSocket = serverSocket.accept();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Message Received :" + inputReader.readLine());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

class ExampleClient implements Runnable {
@Override
public void run() {
Socket socket = null;
try {
Thread.sleep(1000);
socket = new Socket("localhost", 1111);
PrintWriter outWriter = new PrintWriter(socket.getOutputStream(), true);
outWriter.println("Message from Client!");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {

try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
[/code]

When you run the above program, you will get the following output:

[code]
Message Received :Message from Client!
[/code]

Now, change the port number to something like this for server and then run the application.

[code lang=”java”]
serverSocket = new ServerSocket(1112);
[/code]

You will get the java.net.ConnectException as below:

[code]
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:337)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at infy.org.ExampleClient.run(ConnectExceptionExample.java:47)
at java.lang.Thread.run(Thread.java:722)
Exception in thread "Thread-1" java.lang.NullPointerException
at infy.org.ExampleClient.run(ConnectExceptionExample.java:59)
at java.lang.Thread.run(Thread.java:722)
[/code]

I hope this example will help you to understand when java.net.ConnectException is thrown from your application. If you have any questions, please write it in the comments section.

Filed Under: Java Tagged With: Java Exceptions

Difference Between Load Testing and Stress Testing

February 10, 2016 by Krishna Srinivasan Leave a Comment

Load testing and stress testing are different testing activity that are often confused among the developers. Both are measuring the performance of the application but the difference is that they measure at different conditions. In simple words, load testing tests with large amount of users but stress testing tests with too many users, too much data, too little time and too little resources. In this short tutorial, I would explain the key differences between load testing and stress testing with simple examples. If you have any questions, please write it in the comments section.

Load Testing vs Stress Testing

What is Load Testing?

Load testing is conducted to a system to test the behavior of the system under the specific amount of load. Most commonly load test refers to the number of concurrent users accessing the system. The output for this testing is the response time for the requests under a specific load as mentioned in the requirements.

Example: The requirement would say that system has to respond with in 5 seconds for every request with the maximum concurrent users of 10000. In this scenario, you will have to simulate the behavior of system so that 10000 users accessing the system simultaneously and test the response time if that meets the system’s performance requirements.

  • Read : JMeter Tutorial

What is Stress Testing?

Stress testing is super set of a load testing. Load testing is checks only the specific load but stress test would goes beyond that requirements. Stress testing is kind of negative testing, it checks if the load of the system goes well beyond the limit set by the load testing and at what point of time the system will fail.

Also stress testing would check the unexpected situations like reducing the system resources, one of the server goes down and observe how the system is recover the unexpected failures of the system.

  • Read : Testing support in Spring Framework

Example: In the above example for load testing we have learnt that it checks for the specified number of users whether it responds within stipulated time period, but stress testing would checks what is the maximum number of users that can be responded till server’s resources are exhausted and finally server can not respond.

Load Testing Tools

There are many popular load testing tools available in the market. Here I am listing down few of the well tools for performing the load testing.

  • Apache JMeter
  • Load Runner
  • Web Load
  • Rational Performance Tester

 

Filed Under: Java Tagged With: Java Performance Testing

  • « Previous Page
  • 1
  • …
  • 3
  • 4
  • 5
  • 6
  • 7
  • …
  • 48
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved