How to Solve Database Deadlock on Microsoft SQL Server

Today, I was helping a team that was getting a database deadlock in their Java Spring Boot application using Microsoft SQL Server. The stacktrace of the error was as shown below.

Exception is org.springframework.dao.CannotAcquireLockException: could not execute query; SQL ; nested exception is org.hibernate.exception.LockAcquisitionException: could not execute query] with root cause Transaction (Process ID 132) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

The database deadlock was caused when user uploads a file that was being written to the database. While the file was being uploaded user navigated to another page where data from the same table was queried.

When we debugged SQL Server traces we discovered that row-level lock was escalated to table lock. This was causing SQL Server to stop other transactions from accessing the table.

To solve this issue we enabled READ_COMMITTED_SNAPSHOT option for the database so that it uses READ_COMMITTED with row versioning isolation strategy. The default database isolation level in SQL Server is READ_COMMITTED which means a query in the current transaction cannot read data modified by another transaction that has not yet committed, thus preventing dirty reads. The isolation level uses shared locking or row versioning to prevent dirty reads, depending on whether the READ_COMMITTED_SNAPSHOT database option is enabled. Since wee enabled READ_COMMITTED_SNAPSHOT SQL Server will use versioning instead of locks.

ALTER DATABASE <database name>

Useful Resources

  1. Cause of a process being a deadlock victim – Link
  2. Database deadlock on Microsoft SQL Server – Link
  3. Transaction (Process ID) was deadlocked on lock resources with another process and has been chosen as the deadlock victim – Link

Upgrading Docker Compose to latest version

If you use Docker for Mac or something similar, Docker Compose will be installed along with it. Docker Compose has a different release timeline for Docker for Mac so you will not be able to try latest version of Docker compose until you upgrade Docker for Mac. This is limiting. You should be able to install Docker compose independently. To achieve that, you can run following command

$ composeVersion=1.13.0
$ curl -L$composeVersion/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose$ chmod +x /usr/local/bin/docker-compose

In the above commands, $ signify bash prompt. You don’t have to type it. Now, you can check Compose version using the command shown below.

$ docker-compose version

MongoDB Query Tip : Find All The Documents Where Array Length is Greater Than N

Suppose we have blog document in blogs collection as shown below.

> db.blogs.insert({author : "Shekhar Gulati","title":"Hello World","text":"Hello World!!","tags":["mongodb","openshift"]})
> db.blogs.insert({author : "Shekhar Gulati","title":"Hello World","text":"Hello World!!","tags":["mongodb","openshift","nosql"]})

Now you want to find out all those blogs which have more than 2 tags then query is shown below.

> db.blogs.find({$where : "this.tags.length > 2"}).pretty()
	"_id" : ObjectId("51011037bf779459a978f96f"),
	"author" : "Shekhar Gulati",
	"title" : "Hello World",
	"text" : "Hello World!!",
	"tags" : [

Spring Test Failing with A ServletContext is required to configure default servlet handling

If you are getting exception shown below in your Spring test

Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.util.Assert.notNull(
at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.(
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerByCGLIB$$c733f512.CGLIB$defaultServletHandlerMapping$22()
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerByCGLIB$$c733f512$$FastClassByCGLIB$$b76778f9.invoke()
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerByCGLIB$$c733f512.defaultServletHandlerMapping()
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(
at sun.reflect.DelegatingMethodAccessorImpl.invoke(
at java.lang.reflect.Method.invoke(

Then to fix this error migrate to Spring 3.2 release. Change the maven dependency as shown below


Quick Tip on Mockito — Mocking Iterator

Today I was writing unit test for a piece of code which required me to mock a iterator. My requirement was that I wanted to return true first time when hasNext() method and return false in the second iteration. It took me sometime to figure out how to write such a test case. My class for which I was writing test looks like as shown below.

import java.util.Iterator;

public class ResultFetcher {

	private ResultStore store;
	private ResultProcessor processor;

	public void fetchResults() {
		Iterator<String> iterator = store.resultIterator();
		while (iterator.hasNext()) {
			String result =;

The unit test code is shown below. The important line in the test is Mockito.when(iterator.hasNext()).thenReturn(true,false); which will return true first time and false second time.

import java.util.Iterator;

import org.junit.Test;
import org.mockito.Mockito;

public class ResultFetcherTest {

public void testFetchResults() {
ResultFetcher fetcher = new ResultFetcher();

ResultStore store = Mockito.mock(ResultStore.class);
ResultProcessor processor = Mockito.mock(ResultProcessor.class); = store;
fetcher.processor = processor;

Iteratoriterator = Mockito.mock(Iterator.class);


Logging JAXWS SOAP Request and Response using a Java Property

Today I was faced with the situation that I needed to log the SOAP requests and responses going in and out from a Java client. I just had the client jar no source code so I can’t any any log or change any other configuration. I needed to log the request and response because I was getting some weird exceptions which I was not able to understand. I got the hold of the SOAP request by passing a Java property

java -jar client.jar

Fixing Exception — Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)

If you are working with Spring Roo and suddenly start getting exception “Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)” then make sure you have _Configurable.aj ITD in your project. This ITD makes the sure that your entity classes have all the required dependencies like EntityManager injected in them. Configurable ITD  looks like as shown below

privileged aspect Movie_Roo_Configurable {

    declare @type: Movie: @Configurable;


Adding Third Party Jars To An OSGI Bundle

Few days back I was writing a Spring Roo add-on(an OSGI bundle) which required me to add some external 3rd party jars to the OSGI bundle pom.xml file. I am not very well verse with OSGI so it took me some time to figure out how to add 3rd party jars to an OSGI bundle. In this short blog post I am sharing the recipe to add third part jars.

The exception that you get when OSGI bundle is not able to find the dependency is like this.

org.osgi.framework.BundleException: Unresolved constraint com.shekhar.roo.addon [66]: Unable to resolve 66.0: missing requirement [66.0] package; (package=com.shekhar.utils)

To solve this error you need to add Embed-Dependency tag to your maven bundle plugin as shown below. The example shows that I need to add commons-io and utils jar to my OSGI bundle. To get more information about Embed-Dependency tag and maven bundle plugin please refer to the documentation.

		<Bundle-Copyright>Copyright Shekhar Gulati. All Rights Reserved.</Bundle-Copyright>

SCP command for Copying files from remote linux machine to local machine

I just faced a requirement that I needed to copy a zip file containing logs from a remote server to my local machine for some analysis.
I googled around and found at that you can use scp command to that for you.

scp -r <username of remote machine>:<remote location> <location of local directory>

scp -r /home/shekhar/tmp

Java Puzzler : They just find me !!

Couple of days back I wrote a piece of code which was behaving in an unexpected manner. I was confused what was happening. Take a look at the sample code below and predict its behavior

package com.shekhar;

public class JavaPuzzler {

	public static void main(String[] args) {
		JavaPuzzler javaPuzzler = new JavaPuzzler();

	public void doSth() {
		float f = 1.2f;
		if (f >= 1.0) {
			f = 0.9999999999999f;
		InnerClass innerClass = new InnerClass(f);

	private class InnerClass {

		private float value;

		public InnerClass(float value) {
			if (value >= 1.0f) {
				throw new IllegalArgumentException(
						"Value can't be greater than 1.0f");

			this.value = value;

		public float getValue() {
			return value;

My initial expectation was that I would get value 0.9999999999999f as answer.Try it and find the answer. Share your answer and reasoning in comments.