近日完成了一个项目,然后把代码交给总公司进行code review时,总公司同事指出下面两段代码存在问题,并给出了修改意见,是用英文描述的,小弟基本上能看懂其意思,但不知如何来修改,特地请教各位大虾. 第一段代码:
public Category getCategory() {
return category;
}
public Category getCategoryRank() {
return categoryRank;
}
同事给出的Error Description:
Directly return the object reference of a mutable object from getter method may violates the loose coupling concept and casue thread interference problem unless it is well thought and written in documents. Suggestion:
Return a duplicated object
第二段代码: public synchronized boolean add() {
boolean result = false;
try {
.........
}catch(Exception ){.....
}finally{
....
}
return result
} 同事给出的Error Description:
Where 2 users add a new category at the same time, the 2 new categories can be with the same name which is not desired.
Suggestion:
Intrinsic locks of class but not object.
英文不好不知道说的对不对
第二个是把方法不能改为static,因为在add()方法里面引用了非静态的对象,会出现"cannot make static reference to the non-static field " 错误.
boolean result = false;
try {
.........
}catch(Exception ){.....
}finally{
....
}
return result;
}
}
public static void main(String[] args){
synchronized (name){
TestRunnable test1 = new TestRunnable();
TestRunnable test2 = new TestRunnable();
Thread t1 = new Thread(test1);
t1.start();
TestRunnable.b = false;
Thread t2 = new Thread(test2);
t2.start();
}
}
}class TestRunnable implements Runnable{
public static boolean b = true;
public static String str = new String("1234");
public void run(){
if(b){
while(true){
this.show1();
}
}else{
while(true){
this.show2();
}
}
}
public void show1(){
synchronized (str){
System.out.println("in test runnable"+Thread.currentThread().getName());
try{
Thread.sleep(10000);
}catch(InterruptedException msg){
}
System.out.println("out test runnable"+Thread.currentThread().getName());
}
}
public void show2(){
synchronized (str){
System.out.println("in test runnable"+Thread.currentThread().getName());
try{
Thread.sleep(1000);
}catch(InterruptedException msg){
}
System.out.println("out test runnable"+Thread.currentThread().getName());
}
}
}
谢谢各位的解答.第一段该如何修改.
return categoryRank;
}返回类型 确定是正确的?
private Category category;
return category;
}
public Category getCategoryRank() {
return category;
}
第二個:
利用內部排他鎖處理就好了,不明白就直接問總公司的人
Category a = getCategory() ;
a.setXXX(b);
这样的话,category的内容也会做相应的修改,他们的建议是你做好能够将category对象里面的内容“复制”一份给局部变量,然后返回局部变量;2、该段代码的同步范围太“大”,只需要在你具体add的地方,进行同步就足够了。
,如果必要的话改成友好,或者保护,另外在Category设置为不可变更,如Integer
在第二段代码中进行了如下修改: public boolean add() {
boolean result = false;
synchronized(adminCategory.class)
{
try {
.........
}catch(Exception ){.....
}finally{
....
}
}
return result
}