Category Archives: object

Breaking singleton pattern


Singleton pattern in java can be implemented by the approaches explained here

Now here is the code to break it using reflection


public class NormalClass{

 private NormalClass(){ //having private constructor
 }

 private void print(){
 System.out.println("broken");
 }

}

/////////////////////////////////

public class Main{

 public static void main(String[] args) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {

 Class c = NormalClass.class;
 final Constructor con = c.getDeclaredConstructor();
 System.out.println(con);

 final Method meth = c.getDeclaredMethod("print", null);

//---- You will get IllegalAccessException without this ---
AccessController.doPrivileged(new PrivilegedAction() {

public Object run() {
 con.setAccessible(true);// turning off the access check
 meth.setAccessible(true);// turning off the access check
return null;
 }

});

 NormalClass n = (NormalClass)con.newInstance(null);
 meth.invoke(n,null);
 }

}

Advertisements

Producer and Consumer Problem


Self explanatory Producer and Consumer problem

Producer.java

package com.producer;

import java.util.ArrayList;

import java.util.Random;

public class Producer implements Runnable{

//Engine Batch ID reference

ArrayList engineList;

//Engine No is stored here

String str;

//Assigning the BATCH ID reference

public Producer(ArrayList engineList) {

this.engineList = engineList;

}

/*

* Produce Engines

*/

public void produce(){

//Random number for engine number

str = ""+Math.abs(new Random(System.currentTimeMillis()).nextLong());

//Only one thread can enter the BATCH for any operation

synchronized (engineList) {

//Add the Engine to the batch

engineList.add(str);

//Notify all other threads that the new engine is added to the BATCH

engineList.notifyAll();

}

//Print Engine Number

System.out.println("Produced :: ENGINE CHASIS NO ["+ str + "]");

}

@Override

public void run() {

System.out.println("Production started");

//10 Engine is to be produced

for(int i=0;i<10;i++){

try {

//Produce the engine

this.produce();

//Sleep for 2 seconds for the next operation

Thread.sleep(2000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

Consumer.java


package com.producer;

import java.util.ArrayList;

public class Consumer extends Thread{

//Engine Batch ID reference

ArrayList<String> engineList;

//Engine No is stored here

String str;

//Assigning the BATCH ID reference

public Consumer(ArrayList<String> engineList) {

this.engineList = engineList;

}

/*

* Consume Engines from the BATCH

*/

public  void consume(int index) throws InterruptedException{

//Only one thread can enter the BATCH for any operation

synchronized (engineList) {

//if the Batch has no engines

while(engineList.size() == 0){

//then wait for some time until you get a new engine to consume

engineList.wait();

}

//If the engine is deployed to the BATCH

if(engineList.size() >= 0){

//The consume the engine from the respective position

str = engineList.get(index);

}

}

//Print Engine Number that it has been consumed

System.out.println("Consumed :: -------> ENGINE CHASIS NO ["+ str + "]" );

}

@Override

public void run() {

//10 Engine has to be consumed

for(int i=0;i<10;i++){

try {

//Produce the engine

this.consume(i);

//Sleep for 3 seconds for the next operation

Thread.sleep(3000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

Main.java


package com.producer;

import java.util.ArrayList;

public class Main {

public static void main(String[] args) throws InterruptedException {

//ArrayList to store the produced engines - BATCH

ArrayList<String> engine = new ArrayList<String>();

//Producer taking the engine BATCH ID Reference

Producer producer = new Producer(engine);

//Consumer taking the reference of the engine BATCH ID Reference

Consumer consumer = new Consumer(engine);

//Threads

Thread prodThread = new Thread(producer);

Thread conThread = new Thread(consumer);

//Starting the production

prodThread.start();

//Start Consumption

conThread.start();

}

}


Thoughts on Java that works


Disclaimer: This is just to get an idea of the implementation, please do not copy the source code

The problem reads like

SALES TAXES
Basic sales tax is applicable at a rate of 10% on all goods, except books,
food, and medical products that are exempt. Import duty is an additional
sales tax applicable on all imported goods at a rate of 5%, with no
exemptions.
When I purchase items I receive a receipt which lists the name of all the
items and their price (including tax), finishing with the total cost of the
items, and the total amounts of sales taxes paid.  The rounding rules for
sales tax are that for a tax rate of n%, a shelf price of p contains
(np/100 rounded up to the nearest 0.05) amount of sales tax.
Write an application that prints out the receipt details for these shopping
baskets…

Find the complete solved solution here

MARS ROVERS
A squad of robotic rovers are to be landed by NASA on a plateau on Mars.
This plateau, which is curiously rectangular, must be navigated by the
rovers so that their on-board cameras can get a complete view of the
surrounding terrain to send back to Earth.

A rover’s position and location is represented by a combination of x and y
co-ordinates and a letter representing one of the four cardinal compass
points. The plateau is divided up into a grid to simplify navigation. An
example position might be 0, 0, N, which means the rover is in the bottom
left corner and facing North.

In order to control a rover, NASA sends a simple string of letters. The
possible letters are ‘L’, ‘R’ and ‘M’. ‘L’ and ‘R’ makes the rover spin 90
degrees left or right respectively, without moving from its current spot.
‘M’ means move forward one grid point, and maintain the same heading.

Assume that the square directly North from (x, y) is (x, y+1).

Find the complete solved solution here

Single object for Singleton pattern


I have explained the basics of singleton pattern here https://vtkrishn.wordpress.com/2010/03/26/singleton-pattern-revisited/

The design goes like this

1) private constructor
2) static method to return the single objects

In this post I am going to explain some additional restrictions on this pattern

1) Lazy initialization with double lock mechanism

2) Early initialization

3) Serialization

4) ClassLoaders

5) Restrict Cloning

Lazy instantiation using double locking mechanism

The standard implementation shown in the code above is a thread safe implementation, but it’s not the best thread-safe implementation because synchronization is very expensive when we are talking about the performance. We can see that the synchronized method getInstance does not need to be checked for synchronization after the object is initialized. If we see that the singleton object is already created we just have to return it without using any synchronized block. This optimization consist in checking in an un-synchronized block if the object is null and if not to check again and create it in an synchronized block. This is called double locking mechanism.

In this case case the singleton instance is created when the getInstance() method is called for the first time. This is called lazy instantiation and it ensures that the singleton instance is created only when it is needed.

//Lazy instantiation using double locking mechanism.
class Singleton
{
 private static Singleton m_instance;

 private Singleton()
 {
 System.out.println("Singleton(): Initializing Instance");
 }

 public static Singleton getInstance()
 {
 if (m_instance == null)
 {
 synchronized(Singleton.class)
 {
 if (m_instance == null)
 {
 System.out.println("getInstance(): First time getInstance was invoked!");
 m_instance = new Singleton();
 }
 }
 }

 return m_instance;
 }

 public void doSomething()
 {
 System.out.println("doSomething(): Singleton does something!");
 }
}

Early instantiation using implementation with static field

In the following implementattion the singleton object is instantiated when the class is loaded and not when it is first used, due to the fact that the m_instance member is declared static. This is why in this implementation we don’t need to syncronize any portion of the code. The class is loaded once this guarantee the unicity of the object

//Early instantiation using implementation with static field.
class Singleton
{
 private static Singleton m_instance = new Singleton();

 private Singleton()
 {
 System.out.println("Singleton(): Initializing Instance");
 }

 public static Singleton getInstance()
 {
 return m_instance;
 }

 public void doSomething()
 {
 System.out.println("doSomething(): Singleton does something!");
 }
}

Serialization

If the Singleton class implements the java.io.Serializable interface, when a singleton is serialized and then deserialized more than once, there will be multiple instances of Singleton created. In order to avoid this the readResolve method should be implemented. See Serializable () and readResolve Method () in javadocs.

 public class Singleton implements Serializable {
 ...

 // This method is called immediately after an object of this class is deserialized.
 // This method returns the singleton instance.
 protected Object readResolve() {
 return getInstance();
 }
 }

ClassLoaders

If you have multiple classloaders(possibilities in case of servlet container) then the patterns will allow for multiple instances to be created which is not expected
To overcome this you have to have the custom implementation like

private static Class getClass(String classname)
 throws ClassNotFoundException {
 ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
 if(classLoader == null)
 classLoader = Singleton.class.getClassLoader();
 return (classLoader.loadClass(classname));
 }
}

Restrict Cloning

You can overcome cloning of the singleton object by explicitly throwing cloneNotSupportedException

public Object clone() throws CloneNotSupportedException {
 throw new CloneNotSupportedException();
 }

If we try to access the above singleton object using reflection then you will get

Exception in thread "Main Thread" java.lang.IllegalAccessException: Class com.example.thread.Main can not access a member of class com.simple.NormalClass with modifiers "private"
 at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
 at java.lang.Class.newInstance0(Class.java:349)
 at java.lang.Class.newInstance(Class.java:308)
 at com.example.thread.Main.main(Main.java:10)

if you are using java 1.5 and above you can use enum type which takes care of all the above


public enum Singleton{
INSTANCE;

public static void print(){
System.out.println("hi");
}

public class Main{

public static void main(String[] args) {
Singleton.INSTANCE.print();
}
}
}

OODesign concepts


Some of the main oodesign principles are available here
I hope this will help developers understand the oo concept more efficiently.

http://www.oodesign.com/design-principles.html

Refactoring the code


I suggest this link for those who wanted to refactor their code without any side effects

http://www.refactoring.com/catalog/index.html

Solving NumberFormatException


Often we tend to parse the integer value from a String object using Integer.valueOf(strValue) or Integer.parseInt(strValue). This will work as far as we pass the string like ‘1234567’ without any grouping.. The problme arises only if we have grouping on the string which is parsed..

Bump..

parseInt() and valueOf() method throws NumberFormatException for this.

So how to resolve this,

rewrite the code and make use of parse() method in java.text.NumberFormat class

String str = "123,456";
 int i = 0;
 try {
 i = NumberFormat.getNumberInstance().parse(str).intValue();
 } catch (ParseException e) {
 e.printStackTrace();
 }
 System.out.println(i);