首页 > 代码库 > 类的相互依赖导致StackOverflowError

类的相互依赖导致StackOverflowError

public class SchoolServiceImpl {
	private static SchoolServiceImpl instance = new SchoolServiceImpl();
	private static ClassServiceImpl classServiceImpl = ClassServiceImpl.getInstanse();	
	public static SchoolServiceImpl getInstanse() {
		if (instance == null)
			return instance = new SchoolServiceImpl();
		return instance;
	}

	public int getSchoolCount() {		
		return classServiceImpl.getClassesCount();
	}
    
	public static void main(String[] args) {
		System.out.println(classServiceImpl.getClassesCount());
	}
}

public class ClassServiceImpl {

	/**
	 * @param args
	 */	
	private static ClassServiceImpl instance = new ClassServiceImpl();
	public static  ClassServiceImpl getInstanse() {
	if (instance == null)
			return instance = new ClassServiceImpl();
		return instance;
	}
	private static SchoolServiceImpl schoolServiceImpl=SchoolServiceImpl.getInstanse();
	
	public int getClassesCount()
	{   
		System.out.println(classServiceImpl.toString());
		return schoolServiceImpl.getSchoolCount();
	}
}

如上两个类彼此依赖其中的方法,导致死循环,最终导致内存溢出。

从中得到的教训:尽可能减少类的彼此依赖,做到单向依赖。