一次ThreadLocal踩坑

1
2
3
private static final MultipartEntityBuilder BUILDER = MultipartEntityBuilder.create().addPart(BIZ, BIZ_VALUE).addPart(CATEGORY, CATEGORY_VALUE);

private static final ThreadLocal<MultipartEntityBuilder> BUILDER_THREAD_LOCAL = ThreadLocal.withInitial(() -> BUILDER);

这样是不行的,作为initial的对象不能是static.
改成下面这样就好了:

1
2
3
4
5
6
private static final ThreadLocal<MultipartEntityBuilder> BUILDER_THREAD_LOCAL = new ThreadLocal<>(){
@Override
protected MultipartEntityBuilder initialValue() {
return MultipartEntityBuilder.create().addPart(BIZ, BIZ_VALUE).addPart(CATEGORY, CATEGORY_VALUE);
}
};
苏ICP备18043672号-1