understanding @service and race condition
I annotate a class with @service . my @controller class will call @service through @autowired. any race condition that anyone can foresee at the @service class ,method ?
if i have method inside @service
public boolean dosomethinglongtime(){
boolean passed=false;
//write to database...
//do very long task;
//if all task success, passed=true;
return passsed
}
any possibility for 2 different users that call controller and call this method, cause race condition on the boolean passed insid开发者_JAVA技巧e dosomethinglongtime() ?
well, this is just a doubt, no race condition happen so far, i just want to clear the doubt. thank you
No, there won't by any race condition in that code (from a Java point of view), as the boolean is scoped to the method call. If the boolean would be an instance or class attribute, then you could hit concurrency issues. Ideally, your services should be stateless to avoid race conditions, if they are not, you'll need to make the class synchronized or use something esoteric from the concurrent package.
If you want to prevent 2 users from writing / updating the same records in the DB, you'll need to use a locking mechanism, such as optimistic locking, or pessimistic locking. The links go to the hibernate documentation, but most ORMs support both locking mechanisms.
精彩评论