Java同步的正确使用方法?
我正在构建一个库存系统,该系统将在具有多个用户的办公室 LAN 上使用。我有一个关于使用同步关键字正确更新库存的疑问。我想做的是允许多个用户更新库存,但当然一次只允许一个用户更新。我创建了如下方法来更新库存:
public static synchronized boolean UpdateXYZStock(Stock so){
//update code
}
这是正确的方法吗?
谢谢
S。
I am building a stock system which will be used over an office LAN with multiple users. I have a query about using the synchronized keyword to update the stock correctly. What I wish to do is allow multiple users to update the stock but of course only allow one user to update at one time. I have created a method as follows for the update of stock:
public static synchronized boolean UpdateXYZStock(Stock so){
//update code
}
Is this the correct way to do this?
Thanks
S.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会锁定对象的实例,而不是类。即不要锁定静态方法,因为您正在锁定该类。除此之外,您可能希望锁定底层对象,例如
,以便您可以更精细地控制锁定的粒度(我假设此方法位于服务器内的组件上,从而为多个客户端提供服务)
I would lock on an instance of the object, not the class. i.e. don't lock a static method since you're locking the class. Further to that you may want to lock on an underlying object e.g.
so you can control the granularity of the locking more finely (I'm assuming this method is on a component within a server and thus serving multiple clients)
同步静态方法的唯一问题是您实际上是在整个类上同步。因此,如果该类中有多个静态方法,则该类是同步的这一事实将阻止其他类访问任何静态方法,直到该类完成为止。
否则应该完成你想要的。
The only problem with synchronizing on a static method is that you are actually synchronizing on the entire class. So if you have more than one static method in that class, the fact that this one is synchronized will prevent other classes from accessing any of the static methods until this one completes.
Otherwise is should accomplish what you want.
您还可以考虑使用 ReadWriteLock< /a>.
You can also consider using ReadWriteLock.
使用
synchronized
这种方式就可以了。这取决于您实际存储数据的位置。如果它只是存储在一个对象中,则使用该对象的监视器,即非静态同步方法。如果将数据存储在数据库中,请确保更新表中该行的所有代码都使用相同的锁。正如其他回复中突出显示的那样,这可以是您通过静态字段提供的对象。 (只是不要使用字符串充当监视器)。
Using
synchronized
that way is fine. It depends on where you are actually storing the data. If it is just stored within an objects, use this object's monitor, i.e. a non-static synchronized method.If you store the data in a database, make sure all code updating this row in a table is using the same lock. This can be, as highlighted in the other reply, be an object that you make available through a static field. (Just don't use Strings to act as monitors).