【发布时间】:2016-05-06 10:32:10
【问题描述】:
我有 JAX-RS、Guice、MyBatis 的项目。有通过 REST 端点调用的方法 getToken()。由于@Transactional(isolation = Isolation.SERIALIZABLE),它被同步以避免异常。但是同步方法并不安全,不同的调用可能会同时影响数据并抛出异常:
Cause: org.postgresql.util.PSQLException: ERROR: could not serialize access due to read/write dependencies among transactions
我尝试通过映射器对象进行同步,但它也不起作用。唯一有效的解决方案是删除同步并更改/删除隔离级别。如何使方法同步?
@Singleton
@Path("/forgottenPath")
public class RestEndpoint {
@Inject
private oneService oneService;
@POST
@Path("/someAction")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public SomeResponse makeSomeAction() {
...
oneService.makeSomeAction();
...
}
}
public class OneServiceImpl implements OneService {
@Inject
private AnotherService anotherService;
@Override
public SomeRespose makeSomeAction() {
...
anotherService.getToken());
....
}
}
@Singleton
public class AnotherServiceImpl implements AnotherService {
@Override
@Transactional(isolation = Isolation.SERIALIZABLE)
public synchronized Token getToken() {
// modifies and retrieves info from database
}
}
【问题讨论】:
-
除了getToken()还有什么方法可以调用数据库?
-
还有其他获取和删除令牌的方法。
标签: java multithreading concurrency synchronized transactional