【发布时间】:2013-01-27 12:44:26
【问题描述】:
我正在使用 Java EE 开发用于游戏评论的内容管理系统。
我有一个非常简单的问题,这里是:
我有一个带有 Game 对象的 ArrayList。每个游戏对象都有 GameRank 属性,这是一个简单的类,定义如下:
public class GameRank
{
private int activity;
private int positiveVotes;
private int negativeVotes;
public GameRank(int activity, int positiveVotes, int negativeVotes)
{
this.activity = activity;
this.positiveVotes = positiveVotes;
this.negativeVotes = negativeVotes;
}
}
网站的访问者可以选择对游戏投赞成票或反对票,结果将使用 ajax 发送到服务器。
所以问题是:
我应该在哪里同步对 GameRank 对象属性的访问 - 它们的 getter 和 setter 方法,或者在处理用户投票并根据游戏 ID 决定应该更新哪个对象的 Controller Servlet 中?
提前 10 倍
如果我决定在类中使用同步,我可以使用 AtomicInteger 作为建议的海报之一或这样:
public class GameRank
{
private volatile int activity;
private volatile int positiveVotes;
private volatile int negativeVotes;
public GameRank(int activity, int positiveVotes, int negativeVotes)
{
this.activity = activity;
this.positiveVotes = positiveVotes;
this.negativeVotes = negativeVotes;
this.checkAndFixValues();
}
private void checkAndFixValues()
{
if(this.activity < 1) this.activity = 1;
if(this.positiveVotes < 1) this.positiveVotes = 1;
if(this.negativeVotes < 1) this.negativeVotes = 1;
}
public int getActivity()
{
synchronized(GameRank.class)
{
return activity;
}
}
public int getPositiveVotes()
{
synchronized(GameRank.class)
{
return positiveVotes;
}
}
public int getNegativeVotes()
{
synchronized(GameRank.class)
{
return negativeVotes;
}
}
public void incrementActivitiy()
{
synchronized(GameRank.class)
{
activity++;
}
}
}
我说的对吗?
【问题讨论】:
标签: java multithreading jakarta-ee synchronized volatile