Atomic Integer handles concurrency smartly & efficiently

Atomic integer is used to handle concurrency of increment and decrement operation smartly using a non-blocking algorithm.

Also it improves the execution time when compared to synchronized way of handling concurrency.

import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerTest {
 public static void main(String[] args) {
  AtomicInteger counter = new AtomicInteger(0);
  for(int i=0; i<50; i++) {
   Runnable runnable = new WorkerThread(counter);
   Thread t = new Thread(runnable);
   t.start();
  }
 }
}
class WorkerThread implements Runnable {
 AtomicInteger count = null;
 WorkerThread(AtomicInteger counter) {
  this.count = counter;
 }
 public void run() {
  int value = this.count.incrementAndGet();
  System.out.println(value);
 }
}

 Above problem spans 50 threads and does increment operation.

You can notice that it prints number between 1 and 50 without a duplicate value which ensures the concurrency.

Advertisements

JAD Eclipse plugin

1. Download the Jad executable file.

http://www.varaneckas.com/jad
http://www.softpedia.com/get/Programming/Debuggers-Decompilers-Dissasemblers/JAD.shtml

2. Download Jad Eclipse plugin
http://sourceforge.net/projects/jadclipse/

3. Copy the downloaded Jad Eclipse plugin – Jabclipse(jadclipse_x.x.x.jar) to Eclipse plugin folder.

4. Restart Eclipse to make the plugin take effect.

5. In Eclipse, Click Window –> Preference –> Java –> Jadclipse , Key in Jad’s path in “Path to Decompiler” field
E.G d:\j2ee\jad\jad.exe

6. In Eclipse, try F3 into any class which does not has the source, Jad will decompile it automatically.

Equals and HashCode in Java

Equals checks for values equality of an object. You can override the equals () method to implement the equality conditions based on your need.

Hashcode represents the memory address where your java object lives. You can get this using System.identityHashCode( anObject ).

package examples;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class EqualsHashCodeTest {
 public static void main( String[] args ) {
  System.out.println( "Checking Equals operations..." );
  Emp emp1 = new Emp( 1, "John" );
  Emp emp2 = new Emp( 1, "John" );

  if ( emp1.equals( emp2 ) ) {
   System.out.println( "Both are equal" );
  } else {
   System.out.println( "Both are not equal" );
  }
  System.out.println( "\nAdding duplicate employees into list..." );
  List<Emp> emps = new ArrayList<Emp>();
  emps.add( new Emp( 1, "John" ) );
  emps.add( new Emp( 2, "David" ) );
  emps.add( new Emp( 1, "John" ) );
  System.out.println( "List Size:" + emps.size() );

  System.out.println( "\nAdding duplicate employees into set..." );
  Set<Emp> empsSet = new HashSet<Emp>( emps );
  System.out.println( "Set Size:" + empsSet.size() );

 }
}

class Emp {
 private int empId;

 private String empName;

 Emp(int empId, String empName) {
  this.empId = empId;
  this.empName = empName;
 }

 @Override
 public int hashCode() {
  System.out.println( "Inside hashCode()" );
  final int prime = 31;
  int result = 1;
  result = prime * result + empId;
  result = prime * result + ( ( empName == null ) ? 0 : empName.hashCode() );
  System.out.println( "EmpId:" + empId + "\t EmpName:" + empName );
  System.out.println( "HashCode value :" + result );
  return result;
 }

 @Override
 public boolean equals( Object obj ) {
  System.out.println( "Inside equals()" );
  if ( this == obj )
   return true;
  if ( obj == null )
   return false;
  if ( getClass() != obj.getClass() )
   return false;
  Emp other = (Emp) obj;
  System.out.println( "this.empId :" + this.empId + "\t Other.empId :" + other.empId );
  System.out.println( "this.empName :" + this.empName + "\t Other.empName :" + other.empName );
  if ( empId != other.empId )
   return false;
  if ( empName == null ) {
   if ( other.empName != null )
    return false;
  } else if ( !empName.equals( other.empName ) )
   return false;
  return true;
 }

}

Output:

Checking Equals operations...
Inside equals()
this.empId :1 Other.empId :1
this.empName :John Other.empName :John
Both are equal

Adding duplicate employees into list...
List Size:3

Adding duplicate employees into set...
Inside hashCode()
EmpId:1 EmpName:John
HashCode value :2315531
Inside hashCode()
EmpId:2 EmpName:David
HashCode value :65806931
Inside hashCode()
EmpId:1 EmpName:John
HashCode value :2315531
Inside equals()
this.empId :1 Other.empId :1
this.empName :John Other.empName :John
Set Size:2

In the above code,

1. We are comparing two objects using equals() method. Hope it is clear.

2. I am adding list of employees having some duplicate employee details. When i get the size, it gives me 3 , not able to find the duplicates in list. No equals() and hashCode() in Emp class are being invoked.

3. I am adding list of employees in the Set collection. For each Object, it calls the hashcode(), Once the hashcode is equals for two objects, it calls the equals() method to check whether the object is having equal values for all member attributes. Ofcourse, you can change the equality check based on your need. Once it is found as equals, those object will not be added into Set. Hence the size of set is 2.

That’s all. Hope you have got the usage of equals() and hashCode()  now.

ThreadLocal Usage

ThreadLocal can be used if you want variable/object to be maintained till the end of thread execution.

 

public class ThreadLocalTest extends Thread {
    // Define/create thread local variable
    static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
    int serialNo;
    public ThreadLocalTest(int serialNo) {
        this.serialNo = serialNo;
    }
    public void run() {
        threadLocal.set( serialNo );
        System.out.println( “Thread name:”+ Thread.currentThread().getName() +“\tSerialNo:” + threadLocal.get() );
    }
    public static void main( String args[] ) {
        for ( int cnt = 0; cnt < 5; cnt++ ) {
            Thread t = new Thread( new ThreadLocalTest( cnt ), “Thread-“ + cnt );
            t.start();
        }
    }
}

 

Output:

Thread name:Thread-1 SerialNo:1

Thread name:Thread-3 SerialNo:3

Thread name:Thread-0 SerialNo:0

Thread name:Thread-2 SerialNo:2

Thread name:Thread-4 SerialNo:4

How to get File Checksum using MD5?

MessageDigest md = MessageDigest.getInstance( "MD5" );
FileInputStream fis = new FileInputStream( fileName ); // D:/export.txt
BufferedInputStream bufferedInputStream = new BufferedInputStream( fis );
byte[] dataBytes = new byte[8 * 1024];
int nread = 0;
while ( ( nread = bufferedInputStream.read( dataBytes ) ) != -1 ) {
	md.update( dataBytes, 0, nread );
}
;
byte[] mdbytes = md.digest();
StringBuffer sb = new StringBuffer();
for ( int i = 0; i < mdbytes.length; i++ ) {
	sb.append( Integer.toString( ( mdbytes[ i ] & 0xff ) + 0x100, 32 ) 
		.substring( 1 ) );
}
bufferedInputStream.close();
fis.close();
System.out.println( "Digest(in hex format):: " + sb.toString() );

How to get the current working directory in JAVA

System.getProperty( "user.dir" );

How to get the current and calling method name in JAVA 5?

To get the current method name

new Throwable().getStackTrace()[ 0 ].getMethodName();

To get the calling method name

new Throwable().getStackTrace()[ 1 ].getMethodName();