If there are static queries and once you hit the database , next time you dont need to hit the DB again , whereas you store it (caching) and get the values back
I have implemented this using three classes - class1,class2 and class3
class3 invoking the class1 object
public class class3 {
public static void main(String args[]) throws InterruptedException{
class1 obj1= new class1();
Thread t1 = new Thread(obj1,"Thread1");
t1.start();
t1.join();
Thread t2 = new Thread(obj1,"Thread2");
t2.start();
}
}
class 2 has many variables which are mapped to database
public class class2 {
int x;
/*
many variables mapped to database
*/
}
class1 implements cache. class 1 stores the object of the class2 and next time it will not hit the database ,it will get the object from the map and calls the variables
import java.util.*;
import org.apache.naming.java.javaURLContextFactory;
public class class1 implements Runnable {
int i;
Map map = new WeakHashMap();
class2 obj = new class2();
public void run(){
if(i==0){
// database connection code;
obj.x=10;// assign the field values to the class2 obj
map.put(obj.getClass(), obj); // save the object in the hashMap
System.out.println(Thread.currentThread().getName()+" "+obj.x);
i++; //increment the integer.
}
else{
class2 x =(class2)map.get(obj.getClass());
System.out.println("i am in else part");
System.out.println(Thread.currentThread().getName()+" "+x.x);
}
}
}
No comments:
Post a Comment