StackOverflowError
非常少见,今天在业务代码中的一个俄地柜方法报了突然StackOverflowError
错误。
1.场景
数据库有一张表,记录了一个链接的推荐关系,比如A第一次打开链接推荐给B,B又推荐给C,C继续推荐下去。。。
这个数据模型应该是一个树形,现在的一个需求就是输入一个人id能知道他的源头推荐人(或者说他的推荐路径)是什么
- 表结构简化
id | 推荐人id |
---|---|
B | A |
C | B |
D | C |
E | D |
F | E |
2.问题
测试在测试的过程中,伪造数据发生了循环的错误,A推荐B,B推荐C,C又推荐A形成了一个循环,递归一直调用,导致StackOverflowError
的发生。
3.解决
强制声明递归次数,超过这个次数还没有返回直接抛异常或者给别的提示。
附.算法实现
public class Demo {
/**
* 模拟推荐关系
* 第一个Integer -> id
* 第二个Integer -> 推荐人id
*/
static Map<Integer,Integer> a;
/* 获得推荐人id */
static int getTj(int id){
Integer integer = a.get(id);
if (integer == null){
return integer;
}
return getTj(integer);
}
public static void main(String[] args) {
a = new HashMap<>(8);
a.put(1, 2);
a.put(2, 3);
a.put(3, 1);
System.out.println(getTj(1));
}
}