Sequence generator tasks by Threads

Many times we face scenario where we need to execute two sequential tasks to perform a operation, like Tagging / Stamping serial Coupons , Producing serial Tickets at different Vending Machines. Below code ( generating Odd and Even in sequence) can be used for such requirement.

PS: This is a basic implementation, the same can be done using other Threading concepts.

				
package multithreading;

// print ODD and Even number alternatively

public class SquenceGeneratorTasks {

	public static boolean oddPrinted = false;

	public static void main(String[] args) {
		 Object lock =new Object();
		Thread oddThread = new Thread(new Runnable() {

			@Override
			public void run() {
				int i = 1;
				while (i <= 20) {

					synchronized (lock) {
						if (!oddPrinted) { // make sure printing starting with Odd number and each Odd is followed with a Even number
							System.out.println(i);
							i = i + 2;
							oddPrinted = true;
							lock.notify();
							try {
								lock.wait();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}

				}
			}
		});

		
		Thread evenThread = new Thread(new Runnable() {

			@Override
			public void run() {
				
				System.out.println(" Though you have delayed Odd thread but printing gonna start with Odd number only !!");
				
				int i = 2;
				while (i <= 20) {
					synchronized (lock) {
						if (oddPrinted) {
							System.out.println(i);
							i = i + 2;
							oddPrinted = false;
							lock.notify();
							try {
								lock.wait();
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				}
			}
		});

		evenThread.start();
		
		// even if We apply some delay to Odd thread printing will start with ODD number only and 
		// Sequence of Odd-Even-Odd maintained
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		oddThread.start();

	}

}						
/*
Though you have delayed Odd thread but printing gonna start with Odd number only !!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 */

You can download the same code from : https://github.com/SkilledMinds/easyNuts/tree/master/code-25-09-2015

Go Gradle ! Servlets with Gradle

Gradle is build automation tool which is collection of all good things of ANT and Maven.For more reading on it follow https://gradle.org/

Today I am posting one sample Gradle Servlet project. Gradle easily supports Java web applications through the “war” and “jetty” plugins. My steps will show you how to quickly make a simple Java Servlet web application ( I am using here STS IDE).

Steps :
(1) Add Gradle plugin (easiest way to do it, goto STS dashborad, search and
add gradle plugin).you need to install Gradle and provide the path of its bin in PATH in case you want to run project from command prompt.
(2) Create a project folder “GradleServlet”
(3) create a file “build.gradle”
(4) content of file “build.gradle”

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'jetty'
apply plugin: 'eclipse-wtp'

repositories {
  mavenCentral()
}

dependencies {
  providedCompile 'javax.servlet:servlet-api:2.5'
  runtime 'javax.servlet:jstl:1.1.2'
}

(5) lets create the servlet at GradleServlet\src\main\java\com\HelloWorldServlet.java

package com;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet
{

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        resp.getOutputStream().write("Gradle is build automation tool which is collection of all good things of  ANT and Maven.".getBytes());
    }
}

(6) Finally let’s put web.xml at GradleServlet\src\main\webapp\WEB-INF\web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 <servlet>
 <display-name>HelloWorldServlet</display-name>
 <servlet-name>HelloWorldServlet</servlet-name>
 <servlet-class>com.HelloWorldServlet</servlet-class>
 </servlet>

 <servlet-mapping>
 <servlet-name>HelloWorldServlet</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>

</web-app>

(6) our Project is ready now, lets build and run it. Lets use commands

to build use —> gradle build
to crate .war of Application use —> gradle war
to run it by Jetty ( a light weight container ) use —-> gradle jettyrunwar
you should see similar lines on screen :

C:\sts_workspace\GradleServlet>gradle jettyrunwar
:compileJava
:processResources UP-TO-DATE
:classes
:war
> Building 80% > :jettyRunWar > Running at http://localhost:8080/GradleServlet

You can get the source code from https://github.com/SkilledMinds/easyNuts

Safe Singleton for your multi-core servers

Purpose of a Singleton is to have one copy of an object in JVM. But writing below code without volatile in a multi core environment may result in multiple copies of Singleton if any failover occurs.
In a multi-core server multiple Threads of your code may try to create a Singleton object. If singleton variable ( _instance ) is properly not visible to all Threads in all running conditions then Singleton will appear with multiple copies ( which is never expected ).To avoid such cases _instance variable should be declared volatile to make sure if a Thread is creating Singleton instance and just after creation it lost the CPU, all other threads should be communicated that _instance is not null now.

public class Singleton{

private static volatile Singleton _instance;
public static Singleton getInstance(){
if(_instance == null){
synchronized(Singleton.class){
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
}