Archive

Archive for the ‘How & Why’ Category

Solved SQL exercise for novice to experts

April 28th, 2012 751 views No comments
database

There is an example , some questions, and corresponding queries. These queries are written in Oracle. But it’ll give you clear logic about how to write SQL queries in any sort of SQL like DB2, TSQL, MySql etc. I constructed this exercise during my training. Although Some questions do not having solution. So those will be an exercise for you. If i get time then will update them later.

First of all you need to create tables in your database. Use above “ready to use” code.

--################ DDL #######################
create table stock
(item_no varchar2(5) primary key,
item_name varchar2(15) not null,
Quoted_price number(6,2),
Category varchar2(5));

create table category
(c_code varchar2(5) primary key,
c_name varchar2(15) not null unique);

 alter table stock
 add constraint s_fk Foreign key(category) references Category(c_code) on  delete cascade ;

create table purchase
(p_no varchar2(5) PRIMARY KEY,
item_no varchar2(5) references stock(item_no),
p_price number(6,2) not null,
p_date date,
p_qty number(3));

 create table sale
 (s_no varchar2(5) PRIMARY KEY,
 item_no varchar2(5) references stock(item_no),
 s_price number(6,2) not null,
 s_date date,
 s_qty number(3),
 cust_name varchar2(15)) ;

Now you need to populate your tables with some dummy but meaningful data. So you can test your queries.

--############### DML #####################
BEGIN
insert into CATEGORY VALUES('C101','FOOD');
insert into CATEGORY VALUES('C102','SPORT');
insert into CATEGORY VALUES('C103','ELEX');
insert into CATEGORY VALUES('C104','CLOTH');
insert into CATEGORY VALUES('C105','OTHER');
END
;

BEGIN
insert into stock values('i101','BREAD',17,'C101');
insert into stock values('i102','BUTTER',67,'C101');
insert into stock values('i103','BISCUIT',87,'C101');
insert into stock values('i104','GEM',56,'C101');
insert into stock values('i105','CHOCOLATE',17,'C101');
insert into stock values('i106','EGG',5,'C101');
insert into stock values('i107','SALT',8,'C101');
insert into stock values('i108','BALL',27,'C102');
insert into stock values('i109','BAT',217,'C102');
insert into stock values('i110','FOOTBALL',117,'C102');
insert into stock values('i111','WICKETS',97,'C102');
insert into stock values('i112','CAP',111,'C102');
insert into stock values('i113','TSHIRT',1011,'C104');
END

BEGIN
insert into PURCHASE values('P101','i101',15,'01-nov-2008',16);
insert into PURCHASE values('P102','i102',65,'01-nov-2008',34);
insert into PURCHASE values('P103','i103',85,'01-nov-2008',12);
insert into PURCHASE values('P104','i104',56,'01-nov-2008',35);
insert into PURCHASE values('P105','i105',17,'01-nov-2008',23);
insert into PURCHASE values('P106','i106',4,'01-nov-2008',34);
insert into PURCHASE values('P107','i107',7,'01-oct-2008',23);
insert into PURCHASE values('P108','i108',25,'01-oct-2008',56);
insert into PURCHASE values('P109','i109',201,'01-sep-2008',67);
insert into PURCHASE values('P110','i110',100,'01-oct-2008',54);
insert into PURCHASE values('P111','i111',90,'01-mar-2008',23);
insert into PURCHASE values('P112','i112',100,'01-feb-2008',12);
insert into PURCHASE values('P113','i113',800,'01-mar-2008',6);
END;

BEGIN
insert into SALE values('S101','i101',19,'01-DEC-2008',6,'AMIT');
insert into SALE values('S102','i102',65,'02-DEC-2008',14,'ROHIT');
insert into SALE values('S103','i103',86,'05-DEC-2008',2,'AMIT');
insert into SALE values('S104','i104',63,'27-nov-2008',12,'SHYAM');
insert into SALE values('S105','i105',21,'16-nov-2008',3,'KAMAL');
insert into SALE values('S106','i106',6,'13-DEC-2008',4,'PREETI');
insert into SALE values('S107','i103',88,'17-nov-2008',2,'RAHUL');
insert into SALE values('S108','i104',57,'19-nov-2008',5,'RAHUL');
insert into SALE values('S109','i105',19,'28-nov-2008',2,'SOHAN');
insert into SALE values('S110','i111',115,'12-DEC-2008',3,'SHAALU');
insert into SALE values('S111','i112',145,'17-NOV-2008',8,'SHAALU');
insert into SALE values('S113','i113',1300,'17-FEB-2008',2,'UMESH');
insert into SALE values('S112','i112',120,'01-MAR-2008',4,'SHYAM');
insert into SALE values('S114','i112',130,'06-OCT-2008',2,'KAMAL');
END;

Now this is the time to practice. See given examples and solved queries. First try all queries given below. Then login to this article-stack to find out their solution.

1) LIST OF ITEMS OF ‘SPORT’ CATEGORY

This area is protected to registered users only.

2) LIST OF ITEMS OF ‘SPORT’ & ‘FOOD’ CATEGORIES
This area is protected to registered users only.

3) LIST OF ITEMS OF ‘SPORT’ CATEGORY, whose PRICE IS greater than average PRICE of all items.
This area is protected to registered users only.

4) LIST OF SOLD ‘SPORT’ ITEMS.
This area is protected to registered users only.

5) LIST OF ITEMS SOLD TO ‘AMIT’.
This area is protected to registered users only.

6) LIST OF ITEMS SOLD IN LAST WEEK.
This area is protected to registered users only.

7) LIST OF ‘FOOD’ ITEMS SOLD IN LAST WEEK.
This area is protected to registered users only.

8 ) LIST OF ITEMS THOSE ARE SOLD TO GAIN MAX PROFIT.
This area is protected to registered users only.

9) LIST OF ‘FOOD’ ITEMS PURCHASED 1 MONTH AGO.
This area is protected to registered users only.

10) LIST OF ‘FOOD’ ITEMS THOSE ARE NOT SOLD IN LAST WEEK.
This area is protected to registered users only.

11) LIST OF CUSTOMERS WHO PURCHASED ‘FOOD’ ITEMS BUT NOT ‘SPORT’ OR ‘CLOTH’ ITEMS.
This area is protected to registered users only.

12) LIST OF CUSTOMERS WHO PURCHASE ITEMS OF SINGLE CATEGORY ONLY.
This area is protected to registered users only.

13) LIST OF SOLD ITEMS WHOESE QUOTED PRICE > 30.
This area is protected to registered users only.

14) LIST OF ITEMS OF ‘SPORT’ CATEGORY, whose PRICE IS greater than average PRICE of all items.
This area is protected to registered users only.

15) LIST OF SOLD ‘SPORT’ ITEMS.
This area is protected to registered users only.

Nice trick to get_the_ID() in wp_head()

March 16th, 2012 30 views No comments

If you call the_ID() or get_the_ID() in wp_head(), you’ll get nothing. Sometimes you require post id to do a specific action like including post id in meta tag or to count number of visits etc.
Well this trick can help you. Let’s see how;

add_action('wp_head', 'doSomethingInHead');
function doSomethingInHead() {
		:
		echo "#amtypostid#;
		:
	}
}

Now use jQuery functions find() & replaceWith() to replace this constant value with post id. But how will you get post id and when will you replace it?

Note: find() search for tag. So echo your constant in some tag. Otherwise create a new dummy tag. replaceWith() will replace all value with post id along with tag.

To get post id of current post:

add_action('the_content', 'getId');
function getId($content) {
	//prepare your jquery script here.
	//use the_ID() or get_the_ID() to get current post id.
	//attach it with your content and return.
	return $content . $myscript;
}

Deadlock detection through YourKit Java Profiler

March 15th, 2012 39 views No comments

Some days ago I wrote an article How Nested Monitor can cause DeadLock and made a tracer to know what i going on in my program.

This was a simple lite-weighted tracer who monitors deadlock and exit from the program if any deadlock detected. It also prints various states of a thread. But since it is again a thread so it prints states whenever it gets proceed by CPU. Hence you miss all states of thread. YourKit Jprofiler solved this problem.

I commented deadlock detection code from tracer and run program through YourKit Profiler. Now see how this tool informed me about dead lock and various states of all running threads & CPU.

YourKit thread states

As you can see in the last, both threads A & B are blocked. YourKit popped up a deadlock message and gave me following information about deadlock.

YourKit deadlock popup

YourKit deadlock popup

It is clearly mentioned in above screen shot that which thread waiting for a lock locked by another thread. It’ll help you to debug your code. Above 2 lines explains, that thread A is taking a lock on some Integer object while thread B is taking lock on DeadLockDemo object. I’ll suggest you to override toString() of class you are locking on. It’l help you to find out exact position where a thread is locking on.

Note:

  • If you are running your program through YourKit, it takes more CPU.
  • YourKit detects deadlock after a while than Tracer. If tracer detects deadlock and exit from the program, yourkit will never know whether deadlock was occurred.


YourKit CPU time & thread overview

If you go through CPU stats, you’ll know that Thread.activeCount() & Thread.getState() takes most CPU. These method are called by tracer to know current state of thread and print it.

CPU stats

Second cycle

I dint call tracer this time and observed that CPU consumption clashed down. Dadlock was still there in the program.

CPU time and thread overview chart

Now you will not notice any Hot Spot. See how CPU consumption slashed down.

CPU time in second cycle

And here how many threads are running after skipping tracer.

Threads runninng in second cycle

Threads runninng in second cycle

Postmortem of notify(), notifyAll(), and wait()

March 10th, 2012 42 views No comments

notify() or notifyAll(), and wait()

notify() or notifyAll(), and wait() must be in a synchronized block for the object you are waiting on. So the following codes are correct;

	public synchronized void method(){
		wait(); //or this.wait();
	}

	public void method(){
		synchronized(this){
			wait(); //or this.wait();
		}
	}

	public void method(){
		synchronized(a){
			a.wait();
		}
	}

	public synchronized void method(){
		synchronized(a){
			wait();
		}
	}
  1. But following code generates run time exception java.lang.IllegalMonitorStateException
  2. 	public void method(){
    		synchronized(a){
    			wait();
    		}
    	}
    
    	public void method(){
    		synchronized(a){
    			synchronized(this){
    				wait(n);
    			}
    		}
    	}
    
    	public synchronized void method(){
    		synchronized(a){
    			wait(n);
    		}
    	}
    
  3. If you change synchronized object inside synchronized block notify() or notifyAll(), and wait() will give run time exception java.lang.IllegalMonitorStateException.
  4. synchronized(a){
    	a = 55;
    	a.wait();
    }
    

    In above example, you are waiting on new copy of a while synchronizing on old copy of a. Below code doesn’t generate exception.

    synchronized(a){
    	a.wait();
    	a = 55;
    }
    

    Because you are waiting on same copy of a, you are synchronizing on. Then you are changing a.

  5. Thread.sleep(1000) asks current thread to wait till specified period. It doesn’t bother about locks and all. So it doesn’t releases lock. On the other hand, wait() releases lock and acquires lock again once notify() or notifyAll() get called on same object or specified time is over.
  6. 		public void acquire(){
    			synchronized(a){
    				print("acquire()");
    				try{
    					a.wait(5000);
    					print("I have awoken");
    					print("" + a);
    				}catch(Exception e){
    					e.printStackTrace();
    				}
    			}
    			print("Leaving acquire()");
    		}
    
    		public void modify(int n){
    			print("Entered in modify");
    			synchronized(a){
    				try{
    					a.wait(5000);
    					this.a=n;
    					print("new value" + a);
    				}catch(Exception e){
    					e.printStackTrace();
    				}
    			}
    		}
    

    Output:
    2012-03-06 19:51:27.969 :: A: acquire()
    2012-03-06 19:51:27.969 :: B: Entered in modify
    2012-03-06 19:51:32.992 :: B: new value97
    2012-03-06 19:51:32.992 :: A: I have awoken
    2012-03-06 19:51:32.992 :: A: 97
    2012-03-06 19:51:32.992 :: A: Leaving acquire()

    Explanation:

    1. Thread A: enters into monitor of a.
    2. Thread B: waits to get entered into monitor of a.
    3. Thread A: meets to a.wait(5000). So it releases lock on a.
    4. Thread B: enters into monitor a. waits and acquires lock on a.
    5. Thread A: try to acquire released lock. But it is already acquired by Thread B. So it waits.
    6. Thread B: changes value of a.
    7. Thread A: acquire lock on a. It prints new value of a.
  7. On the other hand, if I use Thread.sleep(n) in place of wait(n)
  8. public void acquire(){
    			synchronized(a){
    				print("acquire()");
    				try{
    					//a.wait(5000);
    					Thread.sleep(5000);
    					print("I have awoken");
    					print("" + a);
    				}catch(Exception e){
    					e.printStackTrace();
    				}
    			}
    			print("Leaving acquire()");
    		}
    

    Output:
    2012-03-06 20:02:39.395 :: A: acquire()
    2012-03-06 20:02:39.395 :: B: Entered in modify
    2012-03-06 20:02:44.418 :: A: I have awoken
    2012-03-06 20:02:44.418 :: A: 10
    2012-03-06 20:02:44.418 :: A: Leaving acquire()
    2012-03-06 20:02:49.427 :: B: new value97

    Explanation
    When Thread A meets to sleep(n) it doesn’t release lock.

  9. The problem with calling wait() and notify() on the empty string, or any other constant string is, that the JVM/Compiler internally translates constant strings into the same object. That means, that even if you have two different MyWaitNotify instances, they both reference the same empty string instance. This also means that threads calling wait() on the first MyWaitNotify instance risk being awakened by notify() calls on the second MyWaitNotify instance.
  10. If there are multiple threads waiting on same object, notify() can awake any thread randomly. It arises the condition that some threads never get awaken and some always get awaken. This situation is called Starvation. Sometimes some greedy threads don’t release resources (call sleep() instead of wait() etc). It also force other threads to wait. Some threads increase their priority to get served first to CPU, it also force low priority threads to wait for long. These all conditions where any thread need to wait very long is called Starvation.

Read How Nested Monitor can cause DeadLock for a cause of wait().

External Locking vs synchronized

March 10th, 2012 27 views No comments

You must be aware with the need of synchronization after reading Bad synchronization leads program’s death and Synchronization – solve the mystery.

Well! synchronized has some limitations. Lets understand with this example.

public class DummyClass {
	private Integer age = 0;
	public  void display(){
		System.out.println(Thread.currentThread().getName() + ": " + age);
	}
	public  void edit(int n){
		age = n;
	}
}

public class SynchronizedLimitDemo {

	public static void main(String[] args) {
		final DummyClass dcObj = new DummyClass();
		Thread amit = new Thread(new Runnable(){
			@Override
			public void run() {
				try{
					dcObj.edit(27);
					Thread.sleep(1000);
					dcObj.display();
				}catch(InterruptedException ixp){
					System.out.println(ixp.getMessage());
				}
			}
		},"Amit Thread");

		Thread arti = new Thread(new Runnable(){
			@Override
			public void run() {
				try{
					dcObj.edit(29);
					Thread.sleep(1000);
					dcObj.display();
				}catch(InterruptedException ixp){
					System.out.println(ixp.getMessage());
				}
			}
		},"Arti Thread");

		amit.start();
		arti.start();
	}
}

In above stupid example, even if you synchronized display() & edit(), you can’t get proper output. Now see how external locking (since Java 5) can solve it.

public class DummyClass {
	private Integer age = 0;
	private Lock dataLock = new ReentrantLock();
	public  void display(){
		System.out.println(Thread.currentThread().getName() + ": " + age);
		dataLock.unlock();
	}
	public  void edit(int n){
		dataLock.lock();
		age = n;
	}
}

Output:
Arti Thread: 29
Amit Thread: 27

Warning: If a thread tries calling display() directly or before lock was acquired, it’ll generate run time exception. Similarly a thread can call edit() multiple times but can forget calling display(). It’ll lock the object forever.
This example is just to elaborate an advantage of Lock over synchronized.

Problem with synchronized keyword

  1. A synchronized block makes no guarantees about the sequence in which threads waiting to entering it are granted access.
  2. You cannot pass any parameters to the entry of a synchronized block. Thus, having a timeout trying to get access to a synchronized block is not possible.
  3. The synchronized block must be fully contained within a single method. It’s not possible that synchronization starts in one method and ends in another.
  4. If a thread meets synchronized block, where another thread already had entered into it, it is supposed to wait until another thread release the lock.

Java 5 provides another locking mechanism. Where

  1. A thread can request to acquire a lock with timeout period. If lock is not acquired then thread can do something else or can request again.
  2. A Lock can be started in one method and can end in another.
How to

synchronized

	method(
		synchronized(this){
			//critical section
		}
	}

Lock

	Lock lock = new ReentrantLock();

	method(
		lock.lock();
			//critical section
		lock.unlock();
	}

* It is good to call unlock() in finally block.

Methods

The Lock interface has the following primary methods:

  • lock()
  • lockInterruptibly()
  • tryLock()
  • tryLock(long timeout, TimeUnit timeUnit)
  • unlock()

The lock() method locks the Lock instance if possible. If the Lock instance is already locked, the thread calling lock() is blocked until the Lock is unlocked.

The lockInterruptibly() method locks the Lock unless the thread calling the method has been interrupted. Additionally, if a thread is blocked waiting to lock the Lock via this method, and it is interrupted, it exits this method calls.

The tryLock() method attempts to lock the Lock instance immediately. It returns true if the locking succeeds, false if Lock is already locked. This method never blocks.

The tryLock(long timeout, TimeUnit timeUnit) works like the tryLock() method, except it waits up the given timeout before giving up trying to lock the Lock.

The unlock() method unlocks the Lock instance. Typically, a Lock implementation will only allow the thread that has locked the Lock to call this method. Other threads calling this method may result in an unchecked exception (RuntimeException).

Note:
If you have locked an object N times you will have to call unlock() N times.

Synchronization – solve the mystery

March 9th, 2012 11 views No comments

In continuation of need & use of synchronization, I am writing this article to reduce overhead of QA sites to solve basic problems related to multithreading. It’ll also clear the actual picture of synchronized.

Lets start with a small program.

public class SynchoTest {
		private Integer a = 10;

		public void acquire(){
			synchronized(a){
				print("acquire()");
				try{
					Thread.sleep(10000);
					print("I have awoken");
					print("" + a);
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
			print("Leaving acquire()");
		}

		public void modify(int n){
			this.a=n;
			print("new value" + a);
		}

		public void display(){
			print("a=" + a);
		}
		:
}

In above program, I am starting 2 threads. Thread A calls method acquire() and Thread B calls modify(97). Remember it, I’ll use it longer in this article.

Output:

2012-03-06 07:48:10.038 :: A: acquire()
2012-03-06 07:48:10.038 :: B: new value97
2012-03-06 07:48:10.038 :: C: a=97
2012-03-06 07:48:20.054 :: A: I have awoken
2012-03-06 07:48:20.054 :: A: 97
2012-03-06 07:48:20.054 :: A: Leaving acquire()

What have you noticed in above output? yes. When A entered in his critical section, a’s value was 10. But when it went to print it, B already changed a’s value. So A prints new value of a ie 97.

Now do some small changes

		public void modify(int n){
			print("Entered in modfy");
			synchronized(a){
				this.a=n;
				print("new value" + a);
			}
		}

Output:

2012-03-06 07:51:46.19 :: A: acquire()
2012-03-06 07:51:46.19 :: B: Entered in modfy
2012-03-06 07:51:46.19 :: C: a=10
2012-03-06 07:51:56.206 :: A: I have awoken
2012-03-06 07:51:56.206 :: A: 10
2012-03-06 07:51:56.206 :: A: Leaving acquire()
2012-03-06 07:51:56.206 :: B: new value97

This time everything is fine. why so?

  1. If there are many synchronized blocks on same object and any thread has entered into one of the synchronized block then no other thread can enter into any synchronized block on the same object. synchronized checks happens-before condition then either it acquire lock or waits until another thread releases lock or get interrupted.
  2. synchronized blocks on different-2 objects has no interrelation. Any thread can enters into any synchronized block. Synchronized(a) and synchronized(this) are also non-related.

Lets play with some more code:

		public void modify(int n){
			this.a=n;
			print("new value" + a);
		}
		public void display (int n){
			print("a=" + a);
			synchronized(a){
				try{
					Thread.sleep(1000);
					print("a=" + a);
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
		}

Output:

a=34
new value45
a=45

Code Postmortem

Thread 1 inserts into synchronized block of display(). It takes lock on a. Thread 2 insert into modify(). But there is no new synchronized block. So it doesn’t check whether some thread has taken lock on a before. So it allows modification in a. Thus display() prints modified value of a.

If I makes modify() synchronized even, it doesn’t change the output.

		public synchronized void modify(int n){
			this.a=n;
			print("new value" + a);
		}

Because making modify() synchronized ensures that no more than 1 thread can call modify() at a time. It is not related to synchronized(a).

Lets read some more important points about synchronization.

  • If you are starting threads on 2 separate objects then there is no relation between those threads because both objects use different memory address. Hence their synchronized blocks are also not related.
  • synchronized(a) should not contain any statement modifying value of a. You’ll notice it when you’ll read about wait(),notify() etc. However it is allowed.
  • Synchronizing a method or using synchronized(this) everywhere in class is not good practice. Because it blocks all threads to access any synchronized block. Taking lock on necessary field is always a good practice.

Well!! it is not end keep reading of Postmortem of notify(), notifyAll(), and wait()

Multi-Threading, theory aparts

March 9th, 2012 14 views No comments
Very basic

This article is suitable for beginner only who are just starting in multi-threading. I hope you already have read some books and googled a lot. Here I am covering all basic concept without going to very deep in theory. Once the concepts are clear to you, just re-read books you already had read.

To remember multi-threading, remember multiple programs running on your computer like winamp, photoshop, MS word etc at the same time. You can call each program as a single process. Sometimes you do many things at the same time in a program. For example, your word editor. You read a document while printing it. You start searching for some word and importing clips as well.

Each task/job (can run parallel) under single process/program is called as thread.

CPU is 1000 time faster than you blink your eyes.

You might have slow printer for printing. Once your CPU has instructed printer about what to print, why do you need to wait to get printing done? Your CPU switch to another job like searching in your document. Mean while, with regular interval, CPU can check whether printing is finished. This sort of smart but complex working is called multi-threading.

If you be a CPU you will give up soon

Handling multiple jobs, remembering what that job was doing last time, whether a job need some resource to get completed ….. This is something like a father with 10 children who is not good in house work and his wife has gone to office.

Well! you can visit wiki for technical reading because only technical terms can help you in your exam. Here my aim is to clear concepts and explaining how to write simple threading program in java.

How to write java program

Syntax

1. Extends Thread class

     class ConcreteClass extends Thread {
         public void run() {
             :
         }
     }

	ConcreteClass cObj = new ConcreteClass();
	cObj.start();

2. Implement Runnable interface

     class ConcreteClass implements Runnable {
         public void run() {
             :
         }
     }

     ConcreteClass cObj = new ConcreteClass();
     Thread T1 = new Thread(cObj,"my Thread");
     T1.start();

3. Anonymous class

	class ConcreteClass implements Runnable {
         public void method() {
             :
         }
     }

     final ConcreteClass cObj = new ConcreteClass();
     new Thread(new Runnable(){
     	public void run() {
	   cObj.method();
        }

     }).start();

Sample programs

Bad synchronization leads program’s death

March 8th, 2012 29 views No comments

amty husband of arti

Amit, father of 6 children, whose wife Arti has gone to her maternal house for a week, has very less knowledge of housekeeping, cooking, gardening etc. 6 children will definitely prove need of a woman in man’s life.

The same situation occurs in a programmer life when he births creates many threads and doesn’t tell CPU how to handle them. CPU starts handling them in his own way and things get mixed up. Real life situations can be solved somehow. But in computer it ends with abnormal DEATH of a program.


If you don’t want CPU as helpless as Amit is, use proper synchronization.

First identify the problem: threads must not disturb each other even if they are working for same work under one roof.

synchronized

Java provides synchronized keyword to fight such situations. When a thread starts working on some critical work he locks the room (say monitor) using synchronized keyword. So no other thread can enter into the room until the current thread finish his work.

In java, see how a thread locks lines of code.

1. Synchronize an object

public void run() {
	synchronized(target) { // synchronized object
		:
	}
}

2. Synchronize a method

public synchronized void myMethod() {
	:
}
or
public void myMethod() {
	Synchronized(this){
		:
	}
}

Note: It is not necessary that you use synchronized in run() only. It’ll be cleared to you when you’ll see sample program below.

public class DummyClass {
	private Integer age = 0;

	public  void display(){
		System.out.println(Thread.currentThread().getName() + ": " + age);
	}
	public  void edit(int n){
		age = n;
		display();
	}
}

public class Tester {

	public static void main(String[] args) {
		final DummyClass dcObj = new DummyClass();
		Thread amit = new Thread(new Runnable(){
			@Override
			public void run() {
				try{
					Thread.sleep(1000);
					dcObj.edit(27);
				}catch(InterruptedException ixp){
					System.out.println(ixp.getMessage());
				}
			}
		},"Amit Thread");

		Thread arti = new Thread(new Runnable(){
			@Override
			public void run() {
				try{
					Thread.sleep(1000);
					dcObj.edit(29);
				}catch(InterruptedException ixp){
					System.out.println(ixp.getMessage());
				}
			}
		},"Arti Thread");

		amit.start();
		arti.start();
	}

}

Output:
Amit Thread: 29
Arti Thread: 29

[If you feel that the syntax I mentioned above are not matching with code I wrote in sample program, please read basic threading.]

Opps!! what I did. This is like Amit’s younger son asked for lollipop and got cigarette. NOT ACCEPTABLE.

put synchronization;

public class DummyClass {
	private Integer age = 0;

	public  void display(){
		synchronized(age){
			System.out.println(Thread.currentThread().getName() + ": " + age);
		}
	}
	public  void edit(int n){
		synchronized(age){
			age = n;
			display();
		}
	}
}

Output:
Amit Thread: 27
Arti Thread: 29

I did it !!!!!!!!!!!!!!!!!!!!

 

Know more about synchronized:

  1. If you are synchronizing a static method then it’ll take lock over complete class.
  2. If you place synchronized block over the same object on multiple places and one of the thread had already entered into one of them, no other thread can enter into any of the synchronized block until first thread comes out.
  3. blah blah

Well! I am not inking any extra point here which can make you fear from synchronized. I’ll cover all rest points in separate article with spicy examples.

Happy coding :)

How Nested Monitor can cause DeadLock

March 8th, 2012 24 views No comments

I tried to code many programs which can help me to understand race condition, starvation, and deadlock practically. But I failed. Unknowingly I made this program which creates deadlock due improper synchronization.

	public synchronized void acquire() throws Exception{
		Thread.sleep(5000);
		synchronized(lock){
				wait(1);
		}
	}

	public synchronized void modify() throws Exception{
		Thread.sleep(5000);
		synchronized(lock){
				wait(1);
		}
	}

I added a tracer who explained me why both threads were getting blocked. You can integrate separate java thread tracer with your other threading programs.

Refer the output below to understand how improper nested monitoring took lock.

Output:

A:8
B:9
2012-03-07 19:54:57.625 :: [A:RUNNABLE,B:RUNNABLE]
2012-03-07 19:54:57.788 :: [A:RUNNABLE,B:BLOCKED]
2012-03-07 19:54:57.804 :: [A:TIMED_WAITING,B:BLOCKED]
2012-03-07 20:54:59.888 :: [A:RUNNABLE,B:BLOCKED]
2012-03-07 19:55:02.787 :: [A:TIMED_WAITING,B:TIMED_WAITING]
2012-03-07 19:55:02.788 :: [A:BLOCKED,B:TIMED_WAITING]
2012-03-07 19:55:07.787 :: [A:BLOCKED,B:RUNNABLE]
2012-03-07 19:55:07.787 :: [A:BLOCKED,B:BLOCKED]
Both threads are blocked
Deadlock detected in
Thread id: 9
Thread id: 8

Proper synchronization:

	public void acquire() throws Exception{
		Thread.sleep(5000);
		synchronized(lock){
				lock.wait(1);
		}
	}

	public void modify() throws Exception{
		Thread.sleep(5000);
		synchronized(lock){
				lock.wait(1);
		}
	}

You can solve this deadlock in another way as well. Its up to your need.

Write a program for FTP, TelNet, Ping or any other service in a minute

January 23rd, 2012 59 views No comments

I wasted to collect sample code for communicating with FTP then Ping. When I compared both program, I found there is no difference between both program since they are just for connecting to specific service and were not doing anything extra. Only the single difference what i found is their port number.

See your self;

Write a program to communicate with FTP server

:
Socket t = new Socket(hostname, 21);
:

Write a program to ping a server

:
Socket t = new Socket(hostname, 7);
:

Good trick… isn’t it? So there is a list of well known ports which can help you to connect particular service on the server.

Port Number Description
1 TCP Port Service Multiplexer (TCPMUX)
5 Remote Job Entry (RJE)
7 ECHO
18 Message Send Protocol (MSP)
20 FTP — Data
21 FTP — Control
22 SSH Remote Login Protocol
23 Telnet
25 Simple Mail Transfer Protocol (SMTP)
29 MSG ICP
37 Time
42 Host Name Server (Nameserv)
43 WhoIs
49 Login Host Protocol (Login)
53 Domain Name System (DNS)
69 Trivial File Transfer Protocol (TFTP)
70 Gopher Services
79 Finger
80 HTTP
103 X.400 Standard
108 SNA Gateway Access Server
109 POP2
110 POP3
115 Simple File Transfer Protocol (SFTP)
118 SQL Services
119 Newsgroup (NNTP)
137 NetBIOS Name Service
139 NetBIOS Datagram Service
143 Interim Mail Access Protocol (IMAP)
150 NetBIOS Session Service
156 SQL Server
161 SNMP
179 Border Gateway Protocol (BGP)
190 Gateway Access Control Protocol (GACP)
194 Internet Relay Chat (IRC)
197 Directory Location Service (DLS)
389 Lightweight Directory Access Protocol (LDAP)
396 Novell Netware over IP
443 HTTPS
444 Simple Network Paging Protocol (SNPP)
445 Microsoft-DS
458 Apple QuickTime
546 DHCP Client
547 DHCP Server
563 SNEWS
569 MSN
1080 Socks

Besides this list, there is a list of some software which connects to specific port. If the port is not free or busy with another service then either that application will search for alternate port or will stop working.

You can refer the complete list on wikipedia.

Serialization – a Sci Fi comic book story

December 18th, 2011 1060 views No comments

Short story about serialization

Serialization an interesting story of mars and earth scientistAfter hard work of many years, Earth’s scientist developed a robot who can help them in daily work. But this robot was less featured than the robots which were developed by the scientist of Mars planet.

After a meeting between both planet’s scientist, it is decided that mars will send their robots to earth. But a problem occurred. The cost of sending 100 robots to earth was $100 millions. And it takes around 60 days for traveling.

Finally, Mar’s scientist decided to share their secret with Earth’s scientists. This secret was about the structure of class/robot. Earth’s scientists developed the same structure on earth itself. Mar’s scientists serialized the data of each robot and send it to earth. Earth’s scientists deserialized the data and fed it into each robot accordingly.

This process saved the time in communicating mass amount of data.

Some of the robots were being used in some defensive work on Mars. So their scientists marked some crucial properties of those robots as transient before sending their data to Earth. Note that transient property is set to null(in case of reference) or to default value(in case of primitive type) when the object gets deserialized.

One more point which was noticed by Earth’s scientists is that Mars’s scientists ask them to create some static variables to keep environmental detail. This detail is used by some robots. But Mars’s scientists dint share this detail since the environment on earth was different than Mars environment.

Even though knowing about the robot class structure and having serialized data Earth’s scientist were not able to deserialize the data which can make robots working.

Exception in thread "main" java.io.InvalidClassException:
SerializeMe; local class incompatible: stream classdesc
:

Mars’s scientists were waiting for the complete payment. Once the payment was done Mars’s scientists shared the serialVersionUID with Earth’s scientists. Earth’s scientist set it to robot class and everything became fine.

One of the Mar’s Scientist: Earth’s scientists are very slow to deserialize some of our best Robots. They must be using old version of java. They should either switch to new java version or to implement Externalizable.

Terms highlighted in above example are:
a. Serialization
b. Deserialization
c. Transient variables
d. Static variables
e. Externalizable

Technically

Serialization is nothing but storing current state of an object to physical file. So the data can be used later by deserializing it.

When it is required:

a. When a system gets crashed.
b. When a player want to save all played game data so he can continue playing later.
c. When a process need to be stopped by some reason. But it must continue working the next time with the same data.

How to

a. Implements Serializable or Externalizable
b. Serialize:

	ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("fileName"));
	out.writeObject(obj);

c. Deserialize:

	ObjectInputStream in = new ObjectInputStream(new FileInputStream("fileName"));
	in.readObject();

Java serialization all important points through image Image in words

1.       Object of class A can’t be deserialized to the object of class B.

2.       Object of class A can’t be deserialized to the object of class A itself if any of the instance variable changes its nature. For example

  1. Name
  2. Data type
  3. Removed from the class
  4. Make it transient or static

But if serialVersionUID is added to the class of serialized and deserialized object with same value then deserialization will not generate any error (excluding point b). So if variable is not found then its value is not set.

In short, deserialization finds instance variable with the same name they were used to serialize. If variable name is changed or they are removed from the class then it throws error. But if serialVersionUID is same then it skips initialization for not found variables.

In addition, if a variable is found with the same name but its datatype is changed then it generate error of casting even if serialVersionUID is same.

Changing their access level doesn’t impact.

3.       If serialVersionUID is not same for the class of serialized and deserialized object then deserialization throws error even if class structure are exact same.

4.       Methods, transient variables and static variables are not transient.

5.       An object can be serialized only if its class implements either Serializable or Externalizable.

6.       If extra variables found than the variables which are serialized then they are set to their default value at the time deserialization.

7.       Making a class part of inheritance tree is allowed. But moving a class in existing inheritance tree up/down is not allowed since it can affect saved/serialized object tree.


Why Externalizable

  1. It provides control of reading/writing object to/from an output/input stream.
  2. It was very useful till Java 1.2 since reflection was slow
  3. You can decide which object has to left from object tree or what default value has to be set to transient variables while deserialization.

Methods of Externalizable

public void writeExternal(ObjectOutput out) throws IOException {
	out.writeFloat(x);
	out.writeFloat(y);
	out.writeFloat(z);
	out.writeFloat(w);
}

public void readExternal(ObjectInput in) throws IOException {
	x = in.readFloat();
	y = in.readFloat();
	z = in.readFloat();
	w = in.readFloat();
}

Sample Code

I am attaching source code, I practiced on, for serialization and externalization.

This area is protected to registered users only.

Java Queues – when to use what and why

December 17th, 2011 162 views No comments

Pankaj, gifted a mobile to her sister Arti. she recharged mobile with 94 rs for net connection with the upper limit of 3gb and surfing speed of only 12Kbps. She asked her friend Amit to code an application which queues her all mails and send them in bulk whenever she connects to net. She added more conditions in her need.

  1. Mails must be sending in the same order she wrote. Say, if she wrote 1st mail to Shreya, then to Shruti, then to Shilpi, then whenever she connects net mail must be send to Shreya first and so on. So if net gets disconnected by any reason oldest mails must be dispatched first. (Sequence is important)
  2. If there is a mail marked as important then it must be send before any unimportant mail. (Priority is important)
  3. Her mailing application must be password protected so no one else can send mails from her mobile.(Security is important)
  4. Since her mobile has only 26mb internal memory so if she already had wrote mails up to 3mb she must be asked to connect net first. So the old mails can be dispatched to free disk space.
  5. She must be able to delete a mail which is written but not send yet.
  6. There should be a facility to schedule mails to send on particular time or date.(Scheduling is important)

 

From the first point of Arti’s requirement it was clear that Amit was thinking to go for queue data structure since all the mails has to go in FIFIO order. But he had to select appropriate queue type. Amit created 3 storage areas/variable for this.

  1. Draft Collection: A collection which can store draft mails. It can be any bounded collection. Since the sequence doesn’t matter so any special data structure, like queue/stack, is not required. As soon as Arti click on send button, this mail must be moved from this Draft collection to Mails Collection. Since any mail can be sent or discarded any time so random access would be required. So I am going with ArrayList.
  2. Mail Collection: This collection will store all the mails which are ready to send. Since mails have to be send in the same sequence they were written so Queue is only the option for this. Some more points are here to decide which kind of Queue will fit to this application.
    1. Random access is not required from Mails Queue. So ArrayList doesn’t get fit here.
    2. Important mails must queue up. Amit can do this with PriorityQueue easily. Every mail will have some priority. Whichever mail has higher priority will be pulled ahead in the queue.
    3. If internet is connected and there is no mail in Mails Queue then the application must wait if Arti is writing a mail. This sort of requirement can be fulfilled by some kind of BlockingQueue where producer waits if queue is full and consumer waits if queue is empty. For this application PriorityQueue + BlockingQueue = PriorityBlockingQueue.
    4. We also need scheduling of mails. For this I am taking DelayQueue. Elements from DelayQueue can be accessed only if they are expired. For this need I wrote separate utility who take elements from Scheduled queue once their scheduled time is over and put it to Mails Queue.
  1. MailSend Collection: It fetch mail from Mails Queue whenever internet is connected. Since only one mail can be send at a time so a synchronized collection of size 1 is required. SynchronousQueue fit for this need.

 

So finally,

  1. An ArralyList is required to keep draft mails.
  2. A PriorityBlockingQueue keeps mails ready to send
  3. A DelayQueue keeps scheduled mails. These mails move to PriorityBlockingQueue to send once their scheduled time is over.
  4. A SynchronousQueue hold the mail which is being send.

*This article is copyrighted with all examples and images used in this article. Publication of this article to any where without referencing to original article or to hard copy or any modification in original images or example is strictly prohibited.

 

Queue when to use what

Analysis of processing data file

December 17th, 2011 27 views No comments

I am working on a project where I need to read a text file and for every valid record I have to update database. I also have to write a response/log file. This seems very easy. Although I decided to make a generic solution which can be followed in object oriented way in any project easily.

Requirement

1.       Read all files from a folder following some specific naming conventions.

2.       There will max N records in a file and M fix number of columns in a record.

3.       File header will contain specific fields which are required to validate records in a file.

4.       There will be 2 tables in database. One for keeping file processing information like number of successfully proceed records, total records in a file, failed record, start & end time etc. And another for keeping records detail.

5.       Each field in record has to be format validated and then business validated.

6.       Instead of any update to database first the file then the record must be validated.

7.       It should generate a response file which can be sent for monitoring purpose later.

Design:

I made some classes where each class is responsible for their work only.

FileProcessor (IO processing)

1.       Reads Input folder for specific type of file.

2.       Calls ValidateFile() of FileValidator

3.       Moves a file to specific folder as per return value from ValidateFile()

FileValidator (Single file validation)

1.       Reads each line from input file.

2.       Calls

  1. isValidate() of FileHeader for first line
  2. isValidate() of FileFooter for last line
  3. isValidate() of FileRecord for rest lines

3.       It also writes a response/log file. You can make a separate class for response file in case you want formatted output/logs.

4.       It also performs database operation, if required in your project, when isValidate() returns specific message.

Status

1.       This is an enum.

2.       FileOperation class takes multiple decision on the basis of return value from ValidateFile(). Same with FileValidator class. It writes different messages to response file as per return value from isValidate(). This decision can’t be taken on the basis of boolean value. I guess returning enum is better than returning a String.

FileHeader, FileRecord, FileFooter (Single record validation)

1.       Header of a file generally contains meta data of file records like number of records in a file, max & min length of record, number of fields in a record line etc.

2.       All of them are made as bean class. It helps to store values in database and to compare later.

3.       Any change to these classes will not impact other classes but enum Status. To remove this dependency or to make it more independent you can create a separate class or interface. But remember FileProcessor and FileValidator classes take decision on the basis of return enum. So if this value get changed a little bit change in these classes will also be required.

Java data File Processing analysis

*This article is copyrighted with all examples and images used in this article. Publication of this article to any where without referencing to original article or to hard copy or any modification in original images or example is strictly prohibited.

Java Collection Framework Doodle Chart – what to use when and why

November 21st, 2011 361 views 3 comments

I saw most of the people, including me, using ArrayList and HashMap only in their project. I was surprised why the Java provided us so many varieties of collection classes if we are done with only these two.

Since I was not interested to read a whole book for this so I made a doodle chart (cheat sheet, decision chart and short notes) that you can hang to your desk wall or somewhere on your notice board. I have tried to pin up all small aspects related to collection framework. It can help you to decide which class or data structure you should use in your project and why, to maintain high performance.

This is first version of the chart excluding the practical use of Queue interfaces and its classes. I’ll definitely cover them in next article or in next version of this chart.

java,cheat sheet,short notes,class diagram,collection framework,doodle chart

properties,hashtable,hashmap,set,map,sortedset,treemap,treeset,linkedlist,linkedhashmap,linkedhashset,hashset,IdentityHashMap,WeakHashMap,Dictionary,NavigableMap,NavigableSet

java,cheat sheet,short notes,class diagram,flowchart,collection framework,arraylist,hashtable,hashmap,set,map,sortedset,treemap,treeset,linkedlist,linkedhashmap,linkedhashset,hashset,IdentityHashMap,WeakHashMap,NavigableMap,NavigableSet

Above images are not suitable to reference. So you can download PDF version from below link.

This area is protected to registered users only.

*Above contents are copyrighted. You are free to redistribute the PDF or images but the credit to the author or author’s site must not be removed.

Interface vs abstract class – when to use what and why

November 13th, 2011 295 views No comments

After writing an article about practical difference between abstract class and interface, I found myself less practical in that article. So I am writing this revised article with some theoretical difference for your interview and practical differences so you can decide what to use when and why.

As we are aware with the concept of inheritance, child always inherits something from his parent. Sometimes it could be some assets, a child can use. And sometimes they can be some duties, a child is responsible for.

Real time scenario

Mr Gupta was very rich business man. He left 3 factories, 2 houses, 4 cars and a big bank balance to his only son Amit. But as per Gupta bequest, Amit was supposed to be agreed paying 17% of total profit to an organization as charity. He is not liable to change the procedure of charity. He was also supposed to renew some business licenses, insurance policies etc time to time. But he was free to do such payments in his own way.

Lets draw this situation…

abstract class vs interface when to use what example

Above class diagram depicts this real time scenario programmatically. Base class “Mr Gupta” is giving his assets to Amit. donate() is one of the method Amit received in inheritance. Amit will use donate() as it is, as Mr Gupta wanted. So the actual code for donate() will go in base class Mr Gupta. But there are some bequest conditions which must be followed by Amit but his own way. So the above diagram looks perfect for this situation. But the same can be drawn in following manner too.

abstract class vs interface when to use what example

When to use What?

Well it depends completely on your need. Basically, an abstract class is combined form of base class and interface.

Abstract class = Base class + Interface

But what is the base class then? In summary, a base class is a class which has something to give to his child. So the child can use it as it is without putting his own effort. However the child is free to decide his own way.

  • If a base class has no asset to give to his child then there is no sense to make it.
  • Similarly, if a base class has nothing to give but wants his child to implement some procedures then you must go for Interface not a class.
  • And if base class has something to give and something he wants from his child to do mandatory then you must go for an abstract class.

Mathematically


Abstract class = Base class + Interface
Interface = Abstract class – Base class
Base class = Abstract class – Interface

Now there are some thumb rules which can help you to design time confusion. Just follow them.

Rules:

  1. If there are more than one inheritance trees in your application and you want some common functionalities in both tree then use Interface. If these functionalities are closely related to one inheritance tree then go for abstract class.
  2. Make three set of functionalities which must be followed by classes under a single inheritance tree:
    1. Common for all classes
    2. Common for some classes but not all
    3. Separate for each class

    for (a), create abstract class. For (b), create Interface. And for (c), include the functionality in class itself.

  3. Use interface to define the type of any class [Example: Serializable interface, Comparable interface].
  4. Use interface when you wants methods with same name among many classes. It helps you to call such methods without knowing class type using either reflection or a reference object of interface. [Example: Java Comparable, Java Collection, How to force a programmer to implement an interface]
  5. Dynamic proxies. The invaluable java.lang.reflect.Proxy class allows you to make an implementation of any interface at runtime, where calling any of the interface’s methods results in a call to a single invoke method. Read about Proxy Pattern before knowing more about Dynamic proxies.

What to care about

There are points you must keep in your mind before designing your class diagram.

  1. There should be as minimum as possible abstract methods in an abstract class or an interface. Because inclusion or exclusion of any method in the future require the change in all the classes of related inheritance tree.
  2. Since an abstract class is a base class so you can add an implemented method to this.
  3. Since an abstract class is a base class so it must have some implemented methods being used by child classes. So removing an abstract class from an inheritance tree requires changes in all classes beneath the abstract class. But converting it to base class would be an easier deal.
  4. Removing an interface from an inheritance trees is really an easier approach until that interface is not being used as a type of a class. [See this example: player]
  5. Retrofitting an interface to a class is much easier than a class since a class can implement any number of interface but can extent only single class at a time.
  6. Interfaces are designed with the concept of implementing its all methods. Some of them might not be suitable for all classes. But programmers are supposed to implement those useless methods in their class. It results ignoring interface.

*This article is copyrighted under creative common license. You are free to redistribute this article but with credit to original article

How to force a programmer implementing an interface

November 13th, 2011 64 views No comments

Most of the times we want programmer to follow common naming conventions for standard methods through out the all classes. It helps when we need to call a method using reflection or may be with some other purpose. But other developers generally are not aware with these rules. So they starts defining their own methods similar to standard method but not exact same in name.

There is a way to force them to use same naming convention using interface. Implementation of this way could be different as per your project requirement.

Interface

interface Player{
    public void play();
    public void pause();
    public void stop();
}

Classes which are implementing Player Interface;

class AudioPlayer implements Player{...}
class VideoPlayer implements Player{...}

Some extra class. Meaningless but seems relevant

Class PlayList{}

An enum who plays important role;

enum MEDIAPLAYER {
    AUDIO,VIDEO;

    public Player getPlayer() {
        switch (this) {
            case AUDIO:
                return new AudioPlayer();
            case VIDEO:
                return new VideoPlayer();
            default:
                return new AudioPlayer();
        }
    }
}

Using in code

Player testPlayer = MEDIAPLAYER.getPlayer();
:
testPlayer.play();

Now if any new player is added, its entry will go to MEDIAPLAYER which is returning Player type object. So everyone would have to implement Player

Another approach

You can create an abstract class, say MasterPlayer, who is having all the abstract methods Player interface has. In addition, MasterPlayer will have some additional methods like managing PlayList

I hope this example will help you to understand when to use what in interface and abstract class.

End of Java Generic

September 24th, 2011 77 views No comments

No no no no no no no!! don’t mean it wrong. I am just writing last article on Java Generics. I Hope you already had read;

  1. Java Generics – Boys are not allowed in Girls community
  2. Java Generics continue

I’ll continue writing practical problems related to generics, if you guys face any problem or I experience.
After reading above articles you must be clear with what are generics, how to use them, what basic mistakes we generally commit, generics type (remember A,B..E…T…Z) etc etc

You know what, wild card makes me wild everytime. See the below code

public class GenericClass<T> {
	  public void doSomething(Set<T> set) {
	    Set<?> copy = new HashSet<?>(set); //Err
	  }

	  public static void main(String args[]){
		  Object obj = new GenericClass();
		  Object obj2 = new GenericClass<String>();
		  Object obj3 = new GenericClass<?>();//Err:Cannot instantiate
		  GenericClass obj4 = new GenericClass<String>();
		  GenericClass<Number> obj5 = new GenericClass<String>();//Err: Type mismatch: cannot convert
		  GenericClass<String> obj6 = new GenericClass<String>();

		  //Working code
		  //Set<String> set;
		  //Set<String> copy = new HashSet<String>(set);
		  //obj6.doSomething(copy);

		  Set<String> set;
		  Set<?> copy = new HashSet<String>(set);
		  obj6.doSomething(copy);//Err: reason - Set<?> copy can accept any type of Set. But doSomething() can accept only String type of Set.
	  }
}

Above code, problems and reason are self explanatory. And I guess, I had covered most of them in very beginning already. Remember that, ‘T’ doesn’t like ‘?’ and ‘?’ doesn’t like ‘T’ too. So the object og GenericClass will not accept new GenericClass(). Same with the method or with any statement, refer doSomething() in above code.

Remember; Try to avoid wild card as more as possible. Refer below codes for better practice;

interface Collection<E> { public boolean containsAll(Collection<?> c);
	public boolean addAll(Collection<? extends E> c);
}
//Above code is correct but can be rewritten as

interface Collection<E> { public <T> boolean containsAll(Collection<T> c);
	public <T extends E> boolean addAll(Collection<T> c);
}

One more dice..

class Collections {
	public static <T> void copy(List<T> dest, List<? extends T> src){...}
}

//Above code is correct but can be rewritten as (without using wildcard)
class Collections {
	public static <T, S extends T> void copy(List<T> dest, List<S> src){...}
}

Refer below complex Generic method signature just for your reference.

public static <T extends Object & Collection<Integer>> void addToSet(Set<T> s) {...}

Leave your queries, ideas and suggestion.

Java Generics continue

September 24th, 2011 57 views No comments

I don’t have so much time to continue writing interesting points about java generics. So I am summarizing some advanced portion of java generics here with enough practical explanation excluding tedious theory.

If you are missing something or something is unclear or you really need some good examples then drop your comments. I’ll update this article as per your desire. But first go through my first article: Java Generics – Boys are not allowed in Girls community

Review the below code

//--Wrong--
static void fromArrayToCollection(Object[] a, Collection<?> c) {
	for (Object o : a) {
		c.add(o); // compile time error
	}}

let me explain the reason.

  • fromArrayToCollection() says that elements of Object[] a can be added to Collection c.
  • An Object array can have array of String or Number or any other class since it is the parent class of any class.
  • Collection< ? > c can be of ? type ie String or Number etc

It means, below statements must be acceptable

Number[] na = new Number[100];
Collection<String> cs = new ArrayList<String>();
fromArrayToCollection(na, cs);// compile-time error

A Number can not be added to a Collection of String. Correct syntax would be as below;

//--Right--
static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
	for (T o : a) {
		c.add(o); // correct
	}}

Had we discussed A,B,...E...T...Z before? .... OOPs I forgot to tell you. Actually,

This area is protected to registered users only.


Running Multiple Tomcat instances

September 4th, 2011 143 views No comments
  1. Install Tomcat in /opt/tomcat. (You can choose different path as well. You are independent after all)
  2. Create two directories beneath /opt/, say article-stack.com and thinkzarahatke.com, to keep 2 separate instances of Tomcat.
  3. Create required sub-directories in article-stack.com and thinkzarahatke.com.
  4. #cd thinkzarahatke.com
    #mkdir common logs temp server shared webapps work conf
    
  5. Copy all contents of conf directory from installed Tomcat distribution to newly created conf directory in step 3.
  6. #cp -a $CATALINA_HOME/conf conf/.
    

    Tomcat Multiple Instance directory structure Mockup 

  7. Since both Tomcat instance must run from different ports, change port number in both server.xml (/opt/thinkzarahatke.com/conf/server.xml and /opt/article-stack.com/conf/server.xml). Keep port number different in both server.xml.
  8. <Server port="8007" shutdown="SHUTDOWN">
    :
    <!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
    <Connector port="8081" maxHttpHeaderSize="8192"
    maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false" redirectPort="8443" acceptCount="100"
    connectionTimeout="20000" disableUploadTimeout="true" />
    
  9. Now, you must set the CATALINA_HOME environment variable to where you installed the Tomcat binary distribution (ie /opt/tomcat) and you must set the CATALINA_BASE environment variable to a different path where you are storing a JVM instance’s files (ie /opt/article-stack.com and /opt/thinkzarahatke.com)
    1. Create start.sh & stop.sh script to run particular Tomcat instance
    2. Put following contents inside start.sh
    3. #!/bin/sh
       set CATALINA_BASE="/opt/article-stack.com "
       set CATALINA_HOME="/opt/tomcat"
       export CATALINA_BASE CATALINA_HOME
       service tomcat start 	# Standard way to start on Linux
      
    4. Put following contents inside stop.sh
    5. #!/bin/sh
       set CATALINA_BASE="/opt/article-stack.com "
       set CATALINA_HOME="/opt/tomcat"
       export CATALINA_BASE CATALINA_HOME
       service tomcat stop # Standard way to stop on Linux
      
    6. Repeat all 3 steps for another instance. But change the value of CATALINA_BASE to “/opt/thinkzarahatke.com”
  10. #mkdir /opt/article-stack.com/bin
    #cd /opt/article-stack.com/bin
    

Java Generics – Boys are not allowed in Girls community

August 29th, 2011 1488 views No comments

In this article you’ll know How to use, Why to use, Where to use generics. You’ll get the answer for what problem we face while using generics with solution, explanation and examples.
I hope short stories and images, used in this article, will keep your interest alive and will increase your understanding.

Syntax

Old generation – Without Generic

List myIntList = new LinkedList(); // 1
myIntList.add(new Integer(0)); // 2
Integer x = (Integer) myIntList.iterator().next(); // 3

New generation – With Generic

List<Integer> myIntList = new LinkedList<Integer>(); // 1
myIntList.add(new Integer(0)); //2
Integer x = myIntList.iterator().next(); // 3

Purpose:

Generics are invented for type safety and to improve readability. Without generic, you are allowed to add any type of object to a List (collection) which you are supposed to type cast further while accessing. (See old generation syntax block above). It leads “chance of type casting exception” at run time. If a programmer is not aware about what type of elements are expected from the list, he can add any type of element to it. For example;


Mr. Ramesh was accessing employee from Person list. But Mr. Smith was unaware with Ramesh program. So he was adding students to Person list and passing it to Ramesh application.


Java class inheritance - generic

With generics this type of confusions can be averted easily. But if you really require that the Person list must allow employee as well as students but not else, generic has provision for that as well.

How to use

  1. When you create an object of a generic class, or you call a generic method you have to tell him the data type (see new generation syntax block above).
  2. When you define/declare a method/class you have to use generic type or specific data type. We’ll study it later.

Now problem begins….

Generics are not covariant. They are invariant
Arrays in the Java language are covariant — which means that if Integer extends Number (which it does), then not only is an Integer also a Number, but an Integer[] is also a Number[], and you are free to pass or assign an Integer[] where a Number[] is called for. (More formally, if Number is a supertype of Integer, then Number[] is a supertype of Integer[].)
But in generic List is not a supertype of List. You can’t pass a List where a List is expected.

List<Integer> inLi = new ArrayList<Integer>();
List<Number> numLi = inLi; // illegal

Explanation:

 

  1. List says that you can add any type of number (Float,Integer,Long) to the list numLi.
  2. But second statement depicts that numLi; pointing to inLi; can have only Integer type.

Both statements contradict each other. So the compiler itself doesn’t allow any contradict statement which depicts type unsafety. So the second statement is not allowed. Instead

List<Integer> inLi = new ArrayList<Integer>();
List<? extends Number> numLi = inLi; // legal
  1. You can pass any element/variable/object of type Number. Here extends is used for extend & implement both.
  2. ? stands for wildcard. It means any class.

Note that

List does not mean “list of objects of different types, all of which extend Number”. It means “list of objects of a single type which extends Number


java Generic example boy and girl

This area is protected to registered users only.
Well! There is one more keyword super. In summary,

List<String> is a subtype of List<? extends Object>
List<Object> is a subtype of List<? super String>

Another example;
This area is protected to registered users only.
Point to be noticed my loard
This area is protected to registered users only.
Intersting… Isn’t it? Let’s study more.

You cannot instantiate an array of a generic type (new List[3] is illegal). For example, the following example is illegal;

List<String>[] stringList = new List<String>[10]; // illegal

Why so?

As we know that every class is the subtype of Object class. And an array of Object class can have array of any class. And where “any” word comes, generic fails.
Since an array of object can have stringList

Object[] objArr = stringList;  // OK because List<String> is a subtype of Object

It can have list of other class type too. But clever generic never takes a chance. So the above statement is wrong. Instead,

Object[] objArr = new Object[10];

And below statements will work fine then

List<Integer> inLi = new ArrayList<Integer>();
inLi.add(new Integer(3));
objArr [0] = inLi;

Are you still not able to remember it? Ok ok just imagine an Object class as a Cricket Team. You can create team of boys as well as girls. But as per the rule, Boys team will play against boys team only and so on.
This area is protected to registered users only.


Java Generic girls vs boys cricket

Alternate
Even though you are not allowed to instantiate generic array, you can declare them in following manner;

List<String>[] stringList = (List<String>[]) new List<?>[10];
stringList.add(“amit gupta”);


Picture अभी बाकी हे मेरे दोस्त …. wait for my next post

*This article is under copyright. Publishing images, code, examples any where on net or book without permission and credit to original article is strictly prohibited.