Skip to main content

23 posts tagged with "Java"

View All Tags

Create Custom Lock In Java

· One min read
Sandeep Bhardwaj

Lock.java

public class Lock {

private boolean isLocked = false;

public synchronized void lock() throws InterruptedException {
while (isLocked) {
wait();
}
isLocked = true;
}

public synchronized void unlock() {
isLocked = false;
notify();
}
}

Usage

lock.lock();
try {
// ... method body
} finally {
lock.unlock();
}

Double Checked Locking - Singleton Pattern

· One min read
Sandeep Bhardwaj

Singleton.java

public class Singleton {
private static volatile Singleton _instance; // volatile variable
private Singleton(){} //private constructor

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

CyclicBarrier In Java

· One min read
Sandeep Bhardwaj

CyclicBarrierExample.java

import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierExample {

public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(3, new BarrierAction());

new Thread(new Party(barrier)).start();
new Thread(new Party(barrier)).start();
new Thread(new Party(barrier)).start();

try {
// sleep to avoid BrokenBarrierException
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("\nReset the barrier....\n");
// reset the barrier
barrier.reset();

new Thread(new Party(barrier)).start();
new Thread(new Party(barrier)).start();
new Thread(new Party(barrier)).start();
}

}

BarrierAction.java

public class BarrierAction implements Runnable {

@Override
public void run() {
System.out.println("Barrier Action Executes !!!");
}

}

Party.java

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class Party implements Runnable {
CyclicBarrier barrier;

public Party(CyclicBarrier barrier) {
this.barrier = barrier;
}

@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + " waiting at barrier.");
this.barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}

}

Output

Thread-2 waiting at barrier.
Thread-1 waiting at barrier.
Thread-0 waiting at barrier.
Barrier Action Executes !!!

Reset the barrier....

Thread-3 waiting at barrier.
Thread-4 waiting at barrier.
Thread-5 waiting at barrier.
Barrier Action Executes !!!

Semaphore In Java

· One min read
Sandeep Bhardwaj

SemaphoreExample.java

import java.util.concurrent.Semaphore;

public class SemaphoreExample {

public static void main(String[] args) {
Semaphore semaphore = new Semaphore(2);

new Thread(new Task(semaphore)).start();
new Thread(new Task(semaphore)).start();
new Thread(new Task(semaphore)).start();
new Thread(new Task(semaphore)).start();
}

}

class Task implements Runnable {

Semaphore semaphore;

public Task(Semaphore semaphore) {
this.semaphore = semaphore;
}

@Override
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + " acquired");

Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
System.out.println(Thread.currentThread().getName() + " released");
}
}
}

Output

Thread-0 acquired
Thread-1 acquired
Thread-1 released
Thread-0 released
Thread-2 acquired
Thread-3 acquired
Thread-2 released
Thread-3 released

Create Custom ThreadPool In Java

· 2 min read
Sandeep Bhardwaj

ThreadPool.java

Custom ThreadPool class with using the LinkedBlockingQueue for holding the incoming threads.

import java.util.concurrent.LinkedBlockingQueue;

public class ThreadPool
{
volatile boolean isRunning;
private LinkedBlockingQueue<Runnable> blockingQueue;
private WorkerThread[] workerThreads;

public ThreadPool(int poolSize)
{
blockingQueue = new LinkedBlockingQueue<>(4);
workerThreads = new WorkerThread[poolSize];

// create worker threads
for (int i = 0; i < poolSize; i++)
{
workerThreads[i] = new WorkerThread(i + "", blockingQueue);
}

// start all threads
for (WorkerThread workerThread : workerThreads)
{
workerThread.start();
}
}

public void execute(Runnable task)
{
synchronized (blockingQueue)
{

while (blockingQueue.size() == 4)
{
try
{
blockingQueue.wait();
} catch (InterruptedException e)
{
System.out.println("An error occurred while queue is waiting: " + e.getMessage());
}
}

blockingQueue.add(task);

// notify all worker threads waiting for new task
blockingQueue.notifyAll();
}
}
}

WorkerThread.java

import java.util.concurrent.LinkedBlockingQueue;

public class WorkerThread extends Thread
{
private LinkedBlockingQueue<Runnable> queue;

public WorkerThread(String name, LinkedBlockingQueue<Runnable> queue)
{
super(name);
this.queue = queue;
}

@Override
public void run()
{

while (true)
{
synchronized (queue)
{
while (queue.isEmpty())
{
try
{
queue.wait();
} catch (InterruptedException e)
{
System.out.println("An error occurred while queue is waiting: " + e.getMessage());
}
}

try
{
Runnable runnable = this.queue.poll();
System.out.println(
"worker " + Thread.currentThread().getName() + " executing thread " + runnable.toString());
runnable.run();
Thread.sleep(1000);

// notify threads waiting to put task in queue
queue.notifyAll();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}

}

ThreadPoolTester.java

public class ThreadPoolTester
{

public static void main(String[] args)
{
ThreadPool pool = new ThreadPool(2);

for (int i = 0; i < 10; i++)
{
pool.execute(new Task(i + ""));
}
}

}

class Task implements Runnable
{
String name;

public Task(String name)
{
this.name = name;
}

@Override
public void run()
{
System.out.println("Task " + this.name + " is running");
}

@Override
public String toString()
{
return this.name;
}
}

Output

worker 1 executing thread 0
Task 0 is running
worker 1 executing thread 1
Task 1 is running
worker 0 executing thread 2
Task 2 is running
worker 0 executing thread 3
Task 3 is running
worker 0 executing thread 4
Task 4 is running
worker 1 executing thread 5
Task 5 is running
worker 0 executing thread 6
Task 6 is running
worker 0 executing thread 7
Task 7 is running
worker 1 executing thread 8
Task 8 is running
worker 1 executing thread 9
Task 9 is running

Create Custom CountDownLatch In Java

· One min read
Sandeep Bhardwaj
CustomCountDownLatch.java
/**
* Custom CoundDownLach implementation
* @author sandeep
*
*/
public class CustomCountDownLatch
{
int counter;

public CustomCountDownLatch(int counter)
{
this.counter = counter;
}

public synchronized void await() throws InterruptedException
{
if (counter > 0)
{
wait();
}
}

/**
* method will decrement the counter by 1 each time
*/
public synchronized void countDown()
{
counter--;
if (counter == 0)
{
notifyAll();
}
}
}

Install Gradle on Ubuntu

· One min read
Sandeep Bhardwaj
  1. Download the latest Gradle version from Gradle Download page.

  2. Extract the binaries to the desired location.

  3. Set the GRADLE_HOME environment variable.

Setting the environment variable in Ubuntu in really easy, just need to edit the /etc/profile. Just add your gradle installation directory as below.

Open the /etc/profile file in your favorite editor.

sudo gedit /etc/profile

Add below lines in end.

GRADLE_HOME=/data/dev/tools/gradle-2.10
PATH=$PATH:$GRADLE_HOME/bin
export GRADLE_HOME
export PATH
Verify the GRADLE_HOME
echo $GRADLE_HOME
Verify the Gradle version
gradle -v
Output
------------------------------------------------------------
Gradle 2.10
------------------------------------------------------------

Build time: 2015-12-21 21:15:04 UTC
Build number: none
Revision: 276bdcded730f53aa8c11b479986aafa58e124a6

Groovy: 2.4.4
Ant: Apache Ant(TM) version 1.9.3 compiled on December 23 2013
JVM: 1.8.0_60 (Oracle Corporation 25.60-b23)
OS: Linux 3.19.0-47-generic amd64

Set GRADLE_USER_HOME on Ubuntu

Next if you wants to override the default location of gradle local repository.

Again edit the /etc/profile like we did it above and add below line in the end.

export GRADLE_USER_HOME=/data/dev/repository/gradle

Set Maven Home on Ubuntu

· One min read

Setting the environment variable in Ubuntu in really easy, just need to edit the /etc/profile. Just add your maven installation directory as below.

Open the /etc/profile file in your favorite editor.

sudo gedit /etc/profile

Add following lines in end

M2_HOME=/data/dev/tools/apache-maven-3.3.9
PATH=$PATH:$M2_HOME/bin
export M2_HOME
export PATH

Verify the M2_HOME

echo $M2_HOME

Check the maven version

mvn -v

Output

Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T22:11:47+05:30)
Maven home: /data/dev/tools/apache-maven-3.3.9
Java version: 1.8.0_60, vendor: Oracle Corporation
Java home: /usr/local/java/jdk1.8.0_60/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.19.0-47-generic", arch: "amd64", family: "unix"

Custom Annotation for validating a Bean

· 2 min read
Sandeep Bhardwaj

Custom annotation for validating all the field of a class. If fields are null then display a message containing field name with error message.

Annotation

package com;  

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNullAndNotEmpty {

}

Validator class

package com;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class NotNullAndNotEmptyValidator {
public static List<String> validate(Object obj) {
List<String> errors = new ArrayList<String>();

NotNullAndNotEmpty annotations = (NotNullAndNotEmpty) obj.getClass().getAnnotation(NotNullAndNotEmpty.class);

// if annotation not found on class then return empty list
if (annotations != null) {

Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
if (field.get(obj) == null) {
errors.add(field.getName() + " is null or empty");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return errors;
}
}

Usage :- Model

package com;

@NotNullAndNotEmpty
public class Employee {
private String name;
private String address;

public Employee() {

}

public Employee(String name, String address) {
super();
this.name = name;
this.address = address;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

}

Run the test

package com;

import java.util.List;

public class Test {

public static void main(String[] args) {
Employee emp = new Employee("Sandeep", null);

List<String> errors = NotNullAndNotEmptyValidator.validate(emp);

for (String error : errors) {
System.out.println(error);
}

}
}

Output

address is null or empty  

Set Java Home on Ubuntu

· One min read

Setting the environment variable in Ubuntu in really easy, just need to edit the /etc/profile. Just add your java installation directory as below.

Open the /etc/profile file in your favorite editor.

sudo gedit /etc/profile

Add following lines in end

JAVA_HOME=/usr/local/java/jdk1.8.0_60
PATH=$PATH:$JAVA_HOME/bin
export JAVA_HOME
export JRE_HOME
export PATH

Note: For Installing Java on Ubuntu follow the