转换为JSON时出现堆栈溢出问题

时间:2018-10-29 05:50:21

标签: java thread-safety fasterxml

这是我的代码段。我必须使用ForkJoin进行并行调用,但是我的抛出堆栈溢出甚至没有到达服务调用。

请求:

@NoArgsConstructor
@Getter
@Setter
public class Request{

    @JsonProperty("id")
    private String id;

    public Request id(String id){
      this.id=id;
      return this;
    }

    public static Request getRequest(AnotherRequest anotherReq){
        return new Request().id(anotherReq.identity);
    }

    public String getJson() throws Exception {
     return new ObjectMapper().writeValueasString(this);
    }

}

MyCallable:

@AllargsConstructor
MyCallable implements Callable<Response> {
  private Service service;
  private Request request;
  public Response call () throws Exception{
     return service.callWebservice(this.request.getJson());
  }

}

主要方法:

@Autowired
private Service service;
List<MyCallable> jobs = new ArrayList<MyCallable>()
anotherRequestSS.forEach(anotherRequest->{
  jobs.add(new MyCallable(Request.getRequest(anotherRequest),service);
}

ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());

pool.invokeAll(jobs);

此代码进入无限循环,这意味着getJson被称为无限时间,导致堆栈溢出。它甚至没有达到invokeAll()的地步。可能是什么原因造成的?

列表大小anotherRequestSS为2。

1 个答案:

答案 0 :(得分:0)

问题在于,fasterxml将方法“ getJson()”解释为必须包含在生成的JSON中的属性。

将您的班级改写为

@NoArgsConstructor
@Getter
@Setter
public class Request{

  @JsonProperty("id")
  private String id;

  public Request id(String id){
    this.id=id;
    return this;
  }

  public static Request getRequest(AnotherRequest anotherReq){
    return new Request().id(anotherReq.identity);
  }

  public String asJson() throws Exception {
    return new ObjectMapper().writeValueAsString(this);
  }
}

和您的MyCallable相应地

@AllargsConstructor
MyCallable implements Callable<Response> {
  private Service service;
  private Request request;
  public Response call () throws Exception{
     return service.callWebservice(this.request.asJson());
  }
}