Category Archives: Java

Understanding wait, notify and notifyAll using producer-consumer problem

In last post I mentioned about some of the Java Thread’s utility methods. Here I will try to explain wait and notify concept in Threads using classic producer – consumer problem.

Wait: It tells current thread to wait till some notifies it to resume execution, myThread.wait(). There is another version of wait which takes milliseconds as input, wait(2000), it basically tells the thread to wait till someone notifies or a max of 2 seconds.

Notify: Notify statement wakes up one of the threads (randomly chosen in case multiple threads are waiting) waiting on object, to resume execution.

Notifyall: The only difference between notify and notifyAll is that later one notifies all the threads waiting on the object.

Producer- Consumer problem: This is a classic problem where producer and consumer are 2 independent entities. As the name suggests, producer is producing something which is consumed by consumer. The challenge is that one of the entities can be faster than other, for example consumer is consuming faster than producer is producing, in this case the error condition will occur when consumer has nothing to consume (as producer is slow). Vice-versa can be that producer is producing too fast for consumer to consume, so that the storage area is overflowing (as consumer is not able to consume at same speed).

To solve the problem, wait and notify operations come to rescue. So if one entity reaches error state, say consumer has run out of objects to consume, it will wait till a new object is available.

Here is an example of case two where producer is producing faster, so evetually will need to wait at a stage where queue is full till consumer has consumed objects.

The second case (consumer is faster than producer) can be simulated by reversing the sleep time.

package com.kamalmeet;

public class ProducerConsumer {
	public static void main(String s[]) {
		Queue q = new Queue();
		Producer p = new Producer(q);
		Consumer c = new Consumer(q);
		Thread t1 = new Thread(p);
		Thread t2 = new Thread(c);
		t1.start();
		t2.start();
		System.out.println("Exiting main thread now");
	}
}

class Queue {
	int arr[] = new int[10];
	int index = 0;
	final int MAX = 9;

	public synchronized int remove() {
		if (index == 0) {
			try {
				System.out.println("waiting to remove");
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		index--;
		int num = arr[index];
		notify();
		return num;
	}

	public synchronized void add(int num) {
		if (index == MAX) {
			try {
				System.out.println("waiting to add");
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		notify();
		arr[index] = num;
		index++;
	}
}

class Producer implements Runnable {
	Queue q;
	int num = 0;

	Producer(Queue q) {
		this.q = q;
	}

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("adding:" + num);
			q.add(num++);
		}
	}
}

class Consumer implements Runnable {
	Queue q;
	int num = 0;

	Consumer(Queue q) {
		this.q = q;
	}

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("removing:" + q.remove());
		}
	}
}

Thread Basics: Sleep, Join and Yield

When dealing with Java threads, some basic concepts can come handy in order to manage control among threads.

Sleep: A simple command which will tell the thread to go to sleep for given milliseconds. e.g. Thread.sleep(1000), tells current thread to wait for one second.

Join: This command tells program to wait till my current thread is done (killed). It has two versions. t1.join(), tells current thread to wait till thread T1 is killed before moving to next statement. A second verion takes milliseconds as input, t1.join(2000) tells current thread to wait till t1 is killed or 2 seconds which ever occurs first.

Yield: Yield is used by a thread to voluntarily give up control in favor of other threads. Though this is not guranteed- read more – http://www.javamex.com/tutorials/threads/yield.shtml

An example depicting sleep and join operations.

package com.kamalmeet;

public class TestThread {
	public static void main(String s[]) {
		RunnableTest r = new RunnableTest();
		Thread t1 = new Thread(r);
		t1.setName("t1");
		t1.start();

		Thread t2 = new Thread(r);
		t2.setName("t2");
		t2.start();

		try {
			t1.join();
			t2.join(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Exiting main thread now");
	}
}

class RunnableTest implements Runnable {
	int count = 0;
	public synchronized void test() {
		try {
			count++;
			Thread.sleep(4000); // This will just introduce some delay
			System.out.println(Thread.currentThread().getName() + " says Hello from Runnable:" + count);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	public void run() {
		test();
	}
}

Understanding Thread Priority

Here is a little refresher on concept of threads in Java

http://kamalmeet.com/java/multithreading-runnable-vs-thread/
http://kamalmeet.com/java/handling-multithreading-with-synchronization/
http://kamalmeet.com/java/synchronization-object-vs-class-level/

There can be times where you might want to give priority to one thread over another. Java provides you a way to do that by setting priority of threads.

Thread.setPriority

An Example

package com.kamalmeet;
public class TestThread {
	public static void main(String s[]) {
		RunnableTest r = new RunnableTest();
		for (int i = 0; i < 5; i++) {
			Thread t = new Thread(r);
			t.setName("t:" + i);
			t.setPriority(Thread.NORM_PRIORITY + i);
			t.start();
		}
	}
}

class RunnableTest implements Runnable {
	int count = 0;
	public synchronized void test() {
		try {
			count++;
			System.out.println(Thread.currentThread().getPriority());
			Thread.sleep(1000);
			//This will just introduce some delay 
			System.out.println(Thread.currentThread().getName() + " says Hello from Runnable:" + count);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		test();
	}
}

But there is a catch. Threads are handled at the operating system level, so Java is depending on OS to make sure thread priority is taken care of. Here is a good explanation of thread priority in Java being handled in different OS – http://www.javamex.com/tutorials/threads/priority_what.shtml

Checked vs Unchecked exceptions

Exceptions in Java can be broadly categorized into checked and unchecked exceptions. A checked exception is one for which compiler will force you to handle it (either catch it, or throw it back), whereas for an unchecked exception you are not forced to provide handler. So when you are creating a new exception, you can decide whether it is a checked (extending a checked exception) or unchecked exception (extending unchecked exception).

Now the challenge is, how to decide if an excpetion should be checked or unchecked. That is tricky.

“Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.”

And to sum it up

“Here’s the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.”

Text Source: http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html

Split a String in controlled manner

You must have used String’s split method a lot of time to split based on a regex or a simple character or sub-string. But did you know that you can apply the split function in controlled manner. i.e. you can specify how many time split should occur or number of max sub-strings you can expect.

Example if I have string boo:and:foo and I will control number of splits to 2 like str.split(“:”,2), I will get 2 substrings, “boo” and “and:foo”.

Read more – http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String,%20int%29

JPA- Java Persistence API

From the very beginning of software development and more so with web applications, the need for storing state and details of objects have been there. The most used manner to store information has been databases. And with storing data into database, need for a standardized way to store this data has been felt.

The most common way to persist data into database is JDBC, i.e. Java Database connectivity. JDBC is Java Specific implementation of ODBC (Open Database Connectivity). It allows simple way for Java to execute SQL commands and interact with Database. Though it is easy to use, JDBC has a major challenge of SQL portability across Database vendors. The SQL command which works fine for oracle might now work for mysql or ms-sql.

Another popular approach for data persistence is ORM or object relational mapping. The idea is to map Java objects (POJOs) directly to a table in database. There are many strong players like Toplink (now eclipse link) and hibernate in this space.

Then came another important player EJB- entity beans. With EJB 2.0, support for persistence was good, but at cost of implementing complex EJBs.

There is another specification for persistence, JDO, Java Data Objects, which is mostly used to save Objects directly and hence make a good case for non relational or no-sql database usage.

Because of all the above mentioned options available for persistence in Java, need for standards became very important, which resulted first in JPA 1.0 and later a more complete specification in form of JPA 2.0.

Unicode value for your text

 

Following code demonstrate how to get unicode value for your text

public static String getUnicodeText(String original)
{
String unicode=””;
String temp=””;
//Loop through original string and convert each character to unicode equivalent
for( char c : original.toCharArray() ){
temp=Integer.toHexString(c).toUpperCase();
//We do not want to convert space
if(temp.equals(“20″))
{
unicode+=” “;
}
else
{
//For symmetry we will keep unicodes of length 4
while(temp.length()<4)
{
temp=”0″+temp;
}
//Append \\u to let compiler know it is unicode
unicode+=”\\u”+temp;
}
}
//return final unicode string created
return unicode;
}

Submitting Special characters in your Form

If you will try to submit special characters like chinese or spanish text, you will see some junk boxes being submitted to the server. We need to make sure proper encoding, say UTF-8 is being in place. In your HTML (JSP/PHP etc) page, you will need to let browser know that your page works with UTF-8.

<filter>
<filter-name>SessionFilter</filter-name>
<filter-class>com.mysite.SessionFilter</filter-class>
<init-param>
<param-name>PARAMETER_ENCODING</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

In addition, you might want to enforce the settings onto your server to let it know that you are expecting UTF-8 content in request. For example in JBOSS, we will create a filter and enforce UTF-8 content type

And create the filter class like

public class SessionFilter implements Filter {
private String encoding="";

/**
* destroy method to clean up any activities
*/
public void destroy() {
}

/**
* Override the doFilter method to apply any action, in this case setting request encoding
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,ServletException
{
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}

/**
* Override init method to set parameter encoding as provided by web.xml
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
if (filterConfig.getInitParameter("PARAMETER_ENCODING") != null)
{
encoding= filterConfig.getInitParameter("PARAMETER_ENCODING");
System.out.println("encoding "+encoding);

}
}

}