Sunday, November 2, 2008

can a lock be acquired on a class ? reply : Yes, we can.

By using synchronize block on obj.here, a ClassName.class can return an object


package com.test;

/**
*
* @author thanooj
*/

public class Emp {

private int eno;
private String ename;
private double sal;
public Emp(int eno,String ename,double sal){
this.eno=eno;
this.ename=ename;
this.sal=sal;
}
public int getEno(){
return eno;
}
public String getEname(){
return ename;
}
public double getSal(){
return sal;
}
}
``````````````````````````````````````````````````
package com.test;

/**
*
* @author thanooj
*/

public class Dept {
private int dno;
private String dname;
private Emp emp;
public Dept(int dno,String dname){
this.dno=dno;
this.dname=dname;
}
public int getDno(){
return dno;
}
public String getDname(){
return dname;
}
public Emp getEmp(){
return emp;
}

public void addEmp(Emp emp){
synchronized(Emp.class){
this.emp=emp;

// our Complex Operations

}


}
}
```````````````````````````````````````````````````

package com.test;

/**
*
* @author thanooj
*/

public class TestLockAClass {
public static void main(String a[]){

Emp emp=new Emp(1,"rama",50000.01);
System.out.print(emp.getEno()+" "+emp.getEname()+" "+emp.getSal());
Dept dept =new Dept(10,"developer");
dept.addEmp(emp);
System.out.println();
System.out.print(dept.getDno()+" "+dept.getDname());
System.out.println();
System.out.println(dept.getEmp().getEno()+" "+dept.getEmp().getEname()+" "+dept.getEmp().getSal());
}
}

output
--------
1 rama 50000.01
10 developer
1 rama 50000.01

No comments: