Latest Event Updates

Java Thread states

Posted on

Different states of Thread:-

Thread.State – This is a static nested class of the Thread class. This is one of the additions of Java 5 and this class actually inherits the abstract class Enum.

Thread.State enumeration contains the possible states (also depends on Operating System):-

  • NEW – this state represents a new thread which is not yet started.
  • RUNNABLE – this state represents a thread which is executing in the underlying JVM. Here executing in JVM doesn’t mean that the thread is always executing in the OS as well – it may wait for a resource from the Operating system like the processor while being in this state.
  • BLOCKED – this state represents a thread which has been blocked and is waiting for a moniotor to enter/re-enter a synchronized block/method. A thread gets into this state after calling Object.wait method.
  • WAITING – this state represnts a thread in the waiting state and this wait is over only when some other thread performs some appropriate action. A thread can get into this state either by calling – Object.wait (without timeout), Thread.join(without timeout), or LockSupport.park methods.
  • TIMED_WAITING – this state represents a thread which is required to wait at max for a specified time limit. A thread can get into this state by calling either of these methods: Thread.sleep, Object.wait (with timeout specified),Thread.join (with timeout specified), LockSupport.parkNanos,LockSupport.parkUntil
  • TERMINATED – this state reprents a thread which has completed its execution either by returning from the run() method after completing the execution OR by throwing an exception which propagated from the run() method and hence caused the termination of the thread.

Story of Java Threads – basics

Posted on Updated on

public class MyRunnable implements Runnable {

	@Override
	public void run() {
		for (int i = 0; i < 30; i++) {
			System.out.println("Runnale Called");
			Thread thread = Thread.currentThread();
			System.out.println("RunnableJob is being run by " + thread.getName() + " (" + thread.getId() + ") Thread State: " + thread.getState());
		}
	}

}


public class DemoRunnableMain {

	public static void main(String[] aa) throws InterruptedException {
		MyRunnable myTask = new MyRunnable();
		Thread firstThread = new Thread(myTask);
		firstThread.setName("First Thread");
		Thread secondThread = new Thread(myTask);
		secondThread.setPriority(10);
		secondThread.setName("Second Thread");
		firstThread.start();
		//secondThread state would be NEW
		System.out.println("Before calling start() " + secondThread.getName() + " (" + secondThread.getId() + ") Thread State: " + secondThread.getState());
		secondThread.start();
		Thread.sleep(2000);
		System.out.println("After start() is complete " + secondThread.getName() + " (" + secondThread.getId() + ") Thread State: " + secondThread.getState());
		//Above secondThread state would be TERMINATED
	}
	
}


Java – notes

Posted on Updated on

To print list of values in ArrayList –

Arrays.toString(listNames.toArray()) //where listNames is the ArrayList containing values.

Collection’s retainAll() method is to retain only the similar values which are common between two lists.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CollectionBulkOperations {

	public static void main(String[] args) {
		List<String> listNames = new ArrayList<String>();
		List<String> listNames1 = new ArrayList<String>();

		listNames.add("A");
		listNames.add("AA");
		listNames.add("BA");
		listNames1.add("CA");
		listNames1.add("A");
		listNames1.add("BA");
	listNames.retainAll(listNames1);
	System.out.println(Arrays.toString(listNames.toArray()));

	}

}

Difference between Parent reference vs Child reference Type objects.

Parent {
}
Child extends Parent {
}

Parent P = new Child(); // will allow to call only methods present in the parent object but not in the child object.
Threads –
Overloading of run method is always possible. But Thread class start() method can invoke no-argument run method. Other overloaded method should be called explicitly like a normal/any other method call. as below example –

If you override the start method of the Thread class then the Thread .start() gets executed as a normal method. run() method does not get called.


public class FirstThreadProgram {

	public static void main(String[] arg) {
		FirstThread myFirstThread = new FirstThread();
		myFirstThread.start();
		myFirstThread.run(10);
	}

}

 class FirstThread extends Thread {

	 //Start method calls this method.
	public void run() {
		for (int i = 0; i <30; i++) {
			System.out.println("First Thread");
		}
	}

	//Though you can overload this method - this will be called as normal method.
	//Start method does not call this method.
	public void run(int inputVal) {
		for (int i = 0; i <inputVal; i++) {
			System.out.println("First Thread" + i + " inputValue "+ inputVal);
		}
	}

}

Java String vs StringBuffer and StringBuilder

Posted on Updated on

When to use  String vs StringBuffer and StringBuilder –

If content is fix value then use String type.

StringBuffer – if we require thread saftey(only one thread is allowed to work on) and content is not fixed (meaning Mutable).

StringBuilder – more than one thread is allowed to work on and content is not fixed. Introduced in JDK 1.5.

Java Generics Basics

Posted on Updated on

Generics was introduced in Java 1.5. The primary purpose of generic is to provide type saftey and resolve type casting.

Type saftey

Example –

List namesList = new ArrayList();

namesList.add("Gorge");

namesList.add("John");

namesList.add(new Integer(20)); // the problem here is ArrayList will allow any object type. This is the type saftey problem which can only be detected at runtime when reading the data as below.

name1 = (String) namesList.get(0); // would return "George"

name2 = (String) namesList.get(1); // would return "John"

name3 = (String) namesList.get(2); // would throw run-time exception as Integer object cannot be cast to String type.

First basic generic example –

public class FirstGenericExample {

public static void main(String[] aa) {
BasicGeneric basGen = new BasicGeneric("Hello! - This is basic generic test");
basGen.printGenericVal();
}

}

class BasicGeneric {
T refValue;
BasicGeneric(T inputValue){
refValue = inputValue;
}

public void printGenericVal(){
System.out.println(refValue);
}
}

Type Casting – In the case of collections during compile time – it would be mandatory to type cast if we do not use Generics this was before JDK1.5. After Generics was introduced in JDK 1.5 – Generics would take care of force type casting.

Sub sections with in generics.

  • Generic Bound Types – “extends” is the key word used in this type
  • Generic Wildcard characters
  • Generic methods
  • Generic to Non-Generic Object manipulation
  • Issues with Generics

Sample Code for Generic Bound Types –

public class BoundedTypeExample {

public static void main(String[] aa) {
System.out.println("Printing Values..");

Integer[] inputValues = { 1, 4, 7, 20 };

AverageCalcular intAvgCalc = new AverageCalcular&lt;&gt;(inputValues);
System.out.println("Integer Average Returned is :" + intAvgCalc.getAverage());
System.out.println("End of Program");

Double[] inputValues2 = { 5.0, 4.0, 7.0, 20.0 };

AverageCalcular doubleAvgCalc = new AverageCalcular&lt;&gt;(inputValues2);
System.out.println("Double Average Returned is :" + doubleAvgCalc.getAverage());
System.out.println("End of Program");

}
}

//Bounded Type Class which uses 'extends'
class AverageCalcular {
T[] numValues;

AverageCalcular(T[] o) {
numValues = o;
}

double getAverage() {
double sum = 0.0;
for (T inputValue : numValues) {
sum += inputValue.doubleValue();
}
return sum / numValues.length;
}
}

Java 7 Type reference – In the below example ArrayList has “<>” which is empty and it means it uses the parameterType which is String from the handle List<String>
List strings = new ArrayList<>();

I found this video on Generics – precise to the point on Java Generics.  Hope you like this.

Generic Method Example:

public class GenericMethodExample {

	public static void main(String[] args) {
	Integer[] intValues = {1,2,3,4};
	Character[] charValues = {'a','b','c','d'};
	printMe(intValues);
	printMe(charValues);

	}

	//Generic method
	private static <T> void printMe(T[] values) {
		for(T value : values) {
			System.out.println(value);
		}
	}

}

Video – More on Generics: presented by Venkat Subramaniam

2012 in review

Posted on

The WordPress.com stats helper monkeys prepared a 2012 annual report for this blog.

Here’s an excerpt:

600 people reached the top of Mt. Everest in 2012. This blog got about 9,200 views in 2012. If every person who reached the top of Mt. Everest viewed this blog, it would have taken 15 years to get that many views.

Click here to see the complete report.