日期:2014-05-18  浏览次数:20661 次

求教牛人两段代码为什么不合理?

      近日完成了一个项目,然后把代码交给总公司进行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的 第一个好像是说返回的对象的clone,
英文不好不知道说的对不对
------解决方案--------------------
第二个控制synchronized 粒度在细些!
------解决方案--------------------
在第二个类里成名个static 类型的属性,用这个属性做锁旗标,用来锁类(个人理解)
------解决方案--------------------
import java.lang.Runnable;

public class TestFrame{
public static void main(String[] args){
synchronized (name){
TestRunnable test1 = new TestRunnable();