帮我解决我的简单问题。
这是我的简单例外。
public class MyException extends RuntimeException {
private MyErrors error;
public MyException() {
}
public MyException(String message) {
super(message);
}
public MyException(MyErrors error) {
super(error.getMessage());
this.error = error;
}
}
public class MyService {
...
public String someMethod(String id){
Optional<Prizes> prize = Optional.ofNullable(prizesRepository.findById(id));
if(prize.isPresent()){
return prize.get().getPrize();
}
throw new MyException(ThanksGivenErrors.BadRequest);
}
}
这是 MyController 使用的 MyService
public class MyController{
...
@PostMapping("/prize")
public ResponseEntity findPrize(@RequestParam String id) {
try {
return new ResponseEntity<>(MyService.someMethod(id), HttpStatus.OK);
} catch (MyException e) {
return new ResponseEntity<>(e.getError().getMessage(), HttpStatus.BAD_REQUEST);
}
}
}
MyService 是一个 Spring bean 和单例。
我认为如果在多线程环境中使用 MyService 并且发生许多 MyException,则 MyException 中 'error' 字段的值可能会发生变化。
“MyException(extends RuntimeException)”的字段值是“线程安全”吗?
我不认为这会是安全的。谢谢你的教导。
紫衣仙女
富国沪深
相关分类