ibeautiful
解决问题的第一步就是要确保你保护的是数据,而不是代码,先将同步从方法声明移到方法体里。在上面这个简短的例子中,刚开始好像能修改的地方并不多。不过我们考虑的是整个GameServer类,而不只限于这个join()方法:class GameServer {public Map tables = new HashMap();public void join(Player player, Table table) {synchronized (tables) {if (player.getAccountBalance() > table.getLimit()) {List tablePlayers = tables.get(table.getId()); if (tablePlayers.size() < 9) {tablePlayers.add(player);}}}}public void leave(Player player, Table table) {/* body skipped for brevity */}public void createTable() {/* body skipped for brevity */}public void destroyTable(Table table) {/* body skipped for brevity */}}1234567891011121314151617这看似一个很小的改动,却会影响到整个类的行为。当玩家加入牌桌 时,前面那个同步的方法会锁在GameServer的this实例上,并与同时想离开牌桌(leave)的玩家产生竞争行为。而将锁从方法签名移到方法内部以后,则将上锁的时机往后推迟了,一定程度上减小了竞争的可能性缩小锁的作用域public class GameServer {public Map tables = new HashMap();public void join(Player player, Table table) {if (player.getAccountBalance() > table.getLimit()) {synchronized (tables) {List tablePlayers = tables.get(table.getId()); if (tablePlayers.size() < 9) {tablePlayers.add(player);}}}}//other methods skipped for brevity}123456789101112131415现在检查玩家余额的这个耗时操作就在锁作用域外边了。注意到了吧,锁的引入其实只是为了保护玩家数量不超过桌子的容量而已,检查帐户余额这个事情并不在要保护的范围之内。分拆锁public class GameServer {public Map tables = new HashMap();public void join(Player player, Table table) {if (player.getAccountBalance() > table.getLimit()) {List tablePlayers = tables.get(table.getId());synchronized (tablePlayers) { if (tablePlayers.size() < 9) {tablePlayers.add(player);}}}}//other methods skipped for brevity}123456789101112131415现在我们把对所有桌子同步的操作变成了只对同一张桌子进行同步,因此出现锁竞争的概率就大大减小了。如果说桌子中有100张桌子的话,那么现在出现竞争的概率就小了100倍。