Aug 15

Replication aware JDBC connection in java and MySQL


recently I was reviewing the code a project which was having some database issues, while the review I found that the project environment was setup with the MySQL with one master node and two slave node, and I was surprised that in the code they have used the default JDBC driver for database connectivity which actually uses on single node for all read/write operations.

When asked to developer about the reason of using the default driver for database connectivity, he actually don’t knows that the default JDBC connector does not support replication aware connection. So I’ve realised that many of the developers actually don’t know about the replication aware JDBC connection driver, and I’ve decided to write this post.

There are very little difference between default JDBC connector which support single node mysql connection and ReplicationAware JDBC Connector which is used to create Replication aware JDBC connection using multi node mysql setup.

1) The DriverClass

As you all know that for different type of connection we need to load different driver class. The default JDBC Connector class uses com.mysql.jdbc.Driver driver class and ReplicationAware driver uses com.mysql.jdbc.ReplicationDriver driver class for connection.

2) The connection string

As in default JDBC connection we have only single node and in replication environment we can have n number of nodes, so our connection string will also be different for both connections.

while using default jdbc connector we use connection string as

jdbc:mysql://[database host][:port]/[database_name][?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]

and for replication aware jdbc connector we have to provide all server’s ip including master and slaves

jdbc:mysql:replication://[master host][:port],[slave host 1][:port][,[slave host 2][:port]]...[/[database_name]][?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]

thats it :)

you have done it. its the only difference between default JDBC connector and ReplicationAware JDBC connector.

See MySQL documentation here for list of configuration properties that can be appended to the JDBC URL.

One more thing that how to ensure that your operations redirecting to master and slave correctly:

1) Standalone Application:

if you are using standalone application then just call connection.setReadOnly(false) before any transaction and your all read/write operations will execute on master node and set readOnly flag to true if you want to execute queries from slave. ReplicationDriver will take care of your transactions and pick a slave from the list to execute query on a slave node. (Read configuring load balancing with connector/J)

2) Spring transactions:

If you are working with Spring, just add @Transactional annotation to the method with readOnly flag.

For read/write operations on master node, use @Transactional(readOnly = false) and all the database operations will go to the master only.
For read only operations with slave node, use @Transactional(readOnly = true) and all the database operations will go to the slave.



MySQL Replication with Connector/J

MySQL Configuration Properties for Connector/J


Feb 12

How to enable garbage collection logging (GC logs) in Apache tomcat

In this article I’ll provide information about how to enable garbage collection logging (GC logs) in Apache tomcat.

GC logs are very important when you are debugging an application. GC logs helps to analyse how your program uses the memory.

GC logs also helps to find how often garbage collector cleans the memory for unused objects.

So, you can enable garbage collection logging in few simple steps, that are as follows:

for this you need a file named in the $TOMCAT_HOME/bin directory. Create one if it doesn’t exists. is executed when Apache Tomcat is started and sets the JVM options needed to enable garbage collection logging.


how to enable garbage collection logging

Add these lines to
export CATALINA_OPTS=” \
-XX:+PrintGCTimeStamps \
-XX:+PrintGCDetails \
-XX:+PrintGCApplicationStoppedTime \
-XX:+PrintGCApplicationConcurrentTime \
-XX:+PrintHeapAtGC \


Restart Apache Tomcat to enable the changes.

look into tomcat’s logs directory you will find gc.log file, and you can analyse your GC logs :)


Java VM Options


May 08

Send error logs through email using log4j SMTP appender

recently I was reading about Apache log4j appenders. and found log4j SMTPAppender which sends an e-mail when a specific logging event occurs, typically on errors or fatal errors. That time I got idea to write this post to send error logs through email using log4j SMTP appender.

for a developer error logs are very important. and it is very helpful for any developer to deliver error logs directly in their inbox.

So, you can add a simple SMTP appender entry in log4j configuration file and get error logs directly in your inbox.


for users using log4j.xml

<appender name=”mail” class=””>

<param name=”BufferSize” value=”512″ />
<param name=”SMTPHost” value=”” />
<param name=”SMTPUsername” value=”” />
<param name=”SMTPPassword” value=”password” />
<param name=”From” value=”” />
<param name=”To” value=”” />
<param name=”Subject” value=”Error detected on server” />

<layout class=”org.apache.log4j.PatternLayout”>

<param name=”ConversionPattern” value=”%d [%t] %-5p %c %x – %m%n” />


<filter class=”org.apache.log4j.varia.LevelRangeFilter”>

<param name=”LevelMin” value=”error” />
<param name=”LevelMax” value=”fatal” />






for users using
log4j.appender.mail.Subject=Error detected on server
log4j.appender.mail.layout.ConversionPattern=%d [%t] %-5p %c %x – %m%n


Log4j SMTPAppender

Official log4j Homepage


Apr 25

[Maven – Build Error] Unsupported WTP Version


recently I was working on a project and I found a build error while I tried to execute mvn -eclipse:eclipse command to build eclipse project settings for my maven project.


[ERROR] Failed to execute goal org.apache.maven.plugins:maven-eclipse-plugin:2.3:eclipse (default-cli) on project my-web-proj: Unsupported WTP version: 2.0. This plugin currently supports only the following versions: 1.0 1.5 R7 none. -> [Help 1]

the solution for the above error message is specify maven-eclipse-plugin setting in your project’s pom file.


its all done :) now you will be able to create eclipse project from your maven project.


Jul 16

Download/Attach source-code/java-docs with maven dependencies

I am using Maven in my projects from last couple of years, and the automatically downloading the Jars from repository feature of maven is really helpful for developers. But If you are using Eclipse and want to read/analyse Source Code or Java Doc of API then you need the jar file that contains the Source code and java doc of the API, but unfortunately maven does not download and attach the source code and java doc of the APIs automatically.

Maven provides some different ways to download and attach that source code and Java Doc:

  • Using maven eclipse plugin
  • Using maven dependency plugin

Note: The sources and javadocs of the libraries must exist in the repository so that the plugin can download it and attach it.

1. Maven eclipse plugin:

Maven dependencies that are deployed with the source and javadocs can be downloaded and attached to the Eclipse library by using maven-eclipse-plugin. It can be done by:

  • passing command-line argument to the maven-eclipse-plugin, or
  • by declaring in the pom.xml

1.1 passing command-line argument to maven-eclipse-plugin:

This example shows that how to do this by passing command line argument to the maven-eclipse-plugin:

mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true

1.2 declaring in the pom.xml

This sample pom shows that how to declare downloadSources and downloadJavadocs configuration in pom.xml















2. Maven dependency plugin:

maven-dependency-plugin provides a goal named sources that resolves the project source dependencies from the repository.


mvn dependency:sources

This is useful when you want the source attachments downloaded to your local repository and you don’t want to use the eclipse plugin to do this since the eclipse plugin creates/overwrites the eclipse files.

Jun 21

Accessing Private Members of a Java class using Reflection

Somebody asked me that, “Is there any way of accessing private members of a Java Class?

Then I got the idea to write this article, because Java Reflection API provides a feature for accessing private members of a Java Class.

java.lang.reflect package provides the AccessibleObject class that is parent class of Constructor, Method, and Field class. Using the AccessibleObject class, we can change the access control flags of a Reflection Object (Reflection is a feature in the Java programming language. It allows an executing Java program to examine or “introspect” upon itself, and manipulate internal properties of the program. For example, it’s possible for a Java class to obtain the names of all its members and display them.), and the setAccessible(boolean) method is used to change the access control flag of an Object.

package test;


  • @author girish.gaurav



class DemoClass {

private int privateInt = 10;

private String privateString = “temp String”;

private long privateLong = 1234567890L;

private void resetFields(int i, String s, long l) {

privateInt = i;

privateString = s;

privateLong = l;


public void display() {

System.out.println(“Int = ” + privateInt);

System.out.println(“String = ” + privateString);

System.out.println(“Long = ” + privateLong);



class Test {


* @param args


public static void main(String[] args) {

DemoClass obj = new DemoClass();


Class clazz = obj.getClass();

try {

Field intField = clazz.getDeclaredField(“privateInt”);

Field strField = clazz.getDeclaredField(“privateString”);

Field longField = clazz.getDeclaredField(“privateLong”);




System.out.println(“value of privateInt field is : ” + intField.get(obj));

System.out.println(“value of privateString field is : ” + strField.get(obj));

System.out.println(“value of privateLong field is : ” + longField.get(obj));

intField.set(obj, 100);

strField.set(obj, “this is new string”);

longField.set(obj, 55555L);


} catch (SecurityException e) {


} catch (NoSuchFieldException e) {


} catch (IllegalArgumentException e) {


} catch (IllegalAccessException e) {



try {

Method method = clazz.getDeclaredMethod(“resetFields”, int.class, String.class, long.class);


method.invoke(obj, 25, “new String from resetField method.”, 987654321L);


} catch (SecurityException e) {


} catch (NoSuchMethodException e) {


} catch (IllegalArgumentException e) {


} catch (IllegalAccessException e) {


} catch (InvocationTargetException e) {






Java Reflection API


Jun 14

Introduction to Nonblocking Sockets

Here, I am going to explain what non-blocking sockets are, how it works, and where it can be useful, everything in details.


Non-blocking sockets are introduced in Java 2 Standard Edition 1.4. It allows network communication between applications without blocking processes using the sockets.

A nonblocking socket allows input/output operation on a channel without blocking the processes using it. I’m talking about asynchronous high-performance read/write operations that, as you will see, turn upside-down the techniques for designing and developing socked-based applications.

Java developers who already working or worked on sockets might ask that, “Why we use a new technology to work on Sockets while we already have an old one that working fine? Or whats wrong with the traditional (Java 1.3.x) socket programming? and What are the advantage with new non-blocking socket API?”

Suppose we are going to implement a server application that accepts huge number of client connections and as well as, we want the server that can be able to process multiple requests simultaneously. If we use older socket programming to achieve this requirement we have two ways:

1. Implement a multithread server that manually handles a thread for each connection.
2. By using an external third-party module.

Both the given solution can work fine, but if we adopt first solution then the whole thread-management solution will be developed by the programmer and all the concurrency related issues will also be considered by the programmer. and the second solution may cost money. And by using Non-blocking sockets, you can implement a nonblocking server without directly managing threads or resorting to external modules.

%d bloggers like this: