refactor : removed all instances of new Random() and replaced with RandomUtil for a ThreadLocal randomizer

This commit is contained in:
ingmargoudt 2016-09-05 15:03:47 +02:00
parent f2cc8d4571
commit e2a479255a
51 changed files with 173 additions and 133 deletions

View file

@ -41,6 +41,7 @@ import java.util.Set;
import java.util.UUID;
import mage.filter.FilterCard;
import mage.game.Game;
import mage.util.RandomUtil;
import mage.util.ThreadLocalStringBuilder;
/**
@ -51,7 +52,6 @@ public class CardsImpl extends LinkedHashSet<UUID> implements Cards, Serializabl
private static final ThreadLocalStringBuilder threadLocalBuilder = new ThreadLocalStringBuilder(200);
private static Random rnd = new Random();
private UUID ownerId;
public CardsImpl() {
@ -114,7 +114,7 @@ public class CardsImpl extends LinkedHashSet<UUID> implements Cards, Serializabl
return null;
}
UUID[] cards = this.toArray(new UUID[this.size()]);
return game.getCard(cards[rnd.nextInt(cards.length)]);
return game.getCard(cards[RandomUtil.nextInt(cards.length)]);
}
@Override

View file

@ -38,13 +38,13 @@ import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository;
import mage.constants.Rarity;
import mage.constants.SetType;
import mage.util.RandomUtil;
/**
* @author BetaSteward_at_googlemail.com
*/
public abstract class ExpansionSet implements Serializable {
protected static Random rnd = new Random();
protected String name;
protected String code;
@ -136,7 +136,7 @@ public abstract class ExpansionSet implements Serializable {
protected void addToBooster(List<Card> booster, List<CardInfo> cards) {
if (!cards.isEmpty()) {
CardInfo cardInfo = cards.remove(rnd.nextInt(cards.size()));
CardInfo cardInfo = cards.remove(RandomUtil.nextInt(cards.size()));
if (cardInfo != null) {
Card card = cardInfo.getCard();
if (card != null) {
@ -156,7 +156,7 @@ public abstract class ExpansionSet implements Serializable {
List<CardInfo> specialLands = getSpecialLand();
List<CardInfo> basicLands = getCardsByRarity(Rarity.LAND);
for (int i = 0; i < numBoosterLands; i++) {
if (ratioBoosterSpecialLand > 0 && rnd.nextInt(ratioBoosterSpecialLand) == 0 && specialLands != null) {
if (ratioBoosterSpecialLand > 0 && RandomUtil.nextInt(ratioBoosterSpecialLand) == 0 && specialLands != null) {
addToBooster(booster, specialLands);
} else {
addToBooster(booster, basicLands);
@ -183,7 +183,7 @@ public abstract class ExpansionSet implements Serializable {
List<CardInfo> rares = getCardsByRarity(Rarity.RARE);
List<CardInfo> mythics = getCardsByRarity(Rarity.MYTHIC);
for (int i = 0; i < numBoosterRare; i++) {
if (ratioBoosterMythic > 0 && rnd.nextInt(ratioBoosterMythic) == 0) {
if (ratioBoosterMythic > 0 && RandomUtil.nextInt(ratioBoosterMythic) == 0) {
addToBooster(booster, mythics);
} else {
addToBooster(booster, rares);
@ -208,11 +208,11 @@ public abstract class ExpansionSet implements Serializable {
for (int i = 0; i < numBoosterDoubleFaced; i++) {
CardCriteria criteria = new CardCriteria();
criteria.setCodes(this.code).doubleFaced(true);
if (rnd.nextInt(15) < 10) {
if (RandomUtil.nextInt(15) < 10) {
criteria.rarities(Rarity.COMMON);
} else if (rnd.nextInt(5) < 4) {
} else if (RandomUtil.nextInt(5) < 4) {
criteria.rarities(Rarity.UNCOMMON);
} else if (rnd.nextInt(8) < 7) {
} else if (RandomUtil.nextInt(8) < 7) {
criteria.rarities(Rarity.RARE);
} else {
criteria.rarities(Rarity.MYTHIC);
@ -265,7 +265,7 @@ public abstract class ExpansionSet implements Serializable {
}
if (specialCards > 0) {
for (int i = 0; i < numBoosterSpecial; i++) {
if (rnd.nextInt(15) < 10) {
if (RandomUtil.nextInt(15) < 10) {
if (specialCommon != null && !specialCommon.isEmpty()) {
addToBooster(booster, specialCommon);
} else {
@ -273,7 +273,7 @@ public abstract class ExpansionSet implements Serializable {
}
continue;
}
if (rnd.nextInt(4) < 3) {
if (RandomUtil.nextInt(4) < 3) {
if (specialUncommon != null && !specialUncommon.isEmpty()) {
addToBooster(booster, specialUncommon);
} else {
@ -281,7 +281,7 @@ public abstract class ExpansionSet implements Serializable {
}
continue;
}
if (rnd.nextInt(8) < 7) {
if (RandomUtil.nextInt(8) < 7) {
if (specialRare != null && !specialRare.isEmpty()) {
addToBooster(booster, specialRare);
} else {
@ -291,7 +291,7 @@ public abstract class ExpansionSet implements Serializable {
}
if (specialMythic != null && !specialMythic.isEmpty()) {
if (specialBonus != null && !specialBonus.isEmpty()) {
if (rnd.nextInt(3) < 2) {
if (RandomUtil.nextInt(3) < 2) {
addToBooster(booster, specialMythic);
continue;
}

View file

@ -45,6 +45,7 @@ import mage.constants.CardType;
import mage.constants.ColoredManaSymbol;
import mage.util.ClassScanner;
import mage.util.RandomUtil;
import org.apache.log4j.Logger;
/**
@ -55,7 +56,6 @@ public class Sets extends HashMap<String, ExpansionSet> {
private static final Logger logger = Logger.getLogger(Sets.class);
private static final Sets fINSTANCE = new Sets();
protected static Random rnd = new Random();
public static Sets getInstance() {
return fINSTANCE;
@ -111,7 +111,7 @@ public class Sets extends HashMap<String, ExpansionSet> {
int tries = 0;
List<Card> cardPool = new ArrayList<>();
while (count < cardsCount) {
CardInfo cardInfo = cards.get(rnd.nextInt(cards.size()));
CardInfo cardInfo = cards.get(RandomUtil.nextInt(cards.size()));
Card card = cardInfo != null ? cardInfo.getCard() : null;
if (card != null) {
cardPool.add(card);

View file

@ -34,6 +34,7 @@ import mage.cards.decks.DeckCardLists;
import mage.cards.repository.CardCriteria;
import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository;
import mage.util.RandomUtil;
/**
*
@ -71,7 +72,7 @@ public class MWSDeckImporter extends DeckImporter {
List<CardInfo> cards = null;
cards = CardRepository.instance.findCards(criteria);
if (!cards.isEmpty()) {
cardInfo = cards.get(new Random().nextInt(cards.size()));
cardInfo = cards.get(RandomUtil.nextInt(cards.size()));
}
}
if (cardInfo == null) {

View file

@ -48,6 +48,7 @@ import java.util.TreeSet;
import java.util.concurrent.Callable;
import mage.constants.CardType;
import mage.constants.SetType;
import mage.util.RandomUtil;
import org.apache.log4j.Logger;
/**
@ -65,7 +66,6 @@ public enum CardRepository {
// raise this if new cards were added to the server
private static final long CARD_CONTENT_VERSION = 57;
private final Random random = new Random();
private Dao<CardInfo, Object> cardDao;
private Set<String> classNames;
@ -317,7 +317,7 @@ public enum CardRepository {
public CardInfo findCard(String name) {
List<CardInfo> cards = findCards(name);
if (!cards.isEmpty()) {
return cards.get(random.nextInt(cards.size()));
return cards.get(RandomUtil.nextInt(cards.size()));
}
return null;
}

View file

@ -124,6 +124,7 @@ import mage.target.TargetPermanent;
import mage.target.TargetPlayer;
import mage.util.GameLog;
import mage.util.MessageToClient;
import mage.util.RandomUtil;
import mage.util.functions.ApplyToPermanent;
import mage.watchers.Watchers;
import mage.watchers.common.BlockedAttackerWatcher;
@ -159,7 +160,6 @@ public abstract class GameImpl implements Game, Serializable {
FILTER_LEGENDARY.add(new SupertypePredicate("Legendary"));
}
private static Random rnd = new Random();
private transient Object customData;
protected boolean simulation = false;
@ -1098,7 +1098,7 @@ public abstract class GameImpl implements Game, Serializable {
UUID[] players = getPlayers().keySet().toArray(new UUID[0]);
UUID playerId;
while (!hasEnded()) {
playerId = players[rnd.nextInt(players.length)];
playerId = players[RandomUtil.nextInt(players.length)];
Player player = getPlayer(playerId);
if (player != null && player.isInGame()) {
fireInformEvent(state.getPlayer(playerId).getLogName() + " won the toss");

View file

@ -34,6 +34,7 @@ import mage.cards.Card;
import mage.cards.repository.CardCriteria;
import mage.cards.repository.CardInfo;
import mage.cards.repository.CardRepository;
import mage.util.RandomUtil;
import org.apache.log4j.Logger;
/**
@ -71,7 +72,6 @@ public abstract class DraftCube {
private static final Logger logger = Logger.getLogger(DraftCube.class);
private static final Random rnd = new Random();
private final String name;
private final int boosterSize = 15;
@ -100,7 +100,7 @@ public abstract class DraftCube {
boolean done = false;
int notValid = 0;
while (!done) {
int index = rnd.nextInt(leftCubeCards.size());
int index = RandomUtil.nextInt(leftCubeCards.size());
CardIdentity cardId = leftCubeCards.get(index);
leftCubeCards.remove(index);
if (!cardId.getName().isEmpty()) {

View file

@ -121,6 +121,7 @@ public abstract class DraftImpl implements Draft {
for(UUID playerId : players.keySet()) {
table.add(playerId);
}
table.setCurrent(currentId);
}
if (oldDraftPlayer.isPicking()) {

View file

@ -45,6 +45,7 @@ import mage.game.result.ResultProtos.MatchProto;
import mage.game.result.ResultProtos.MatchQuitStatus;
import mage.players.Player;
import mage.util.DateFormat;
import mage.util.RandomUtil;
import org.apache.log4j.Logger;
/**
@ -243,7 +244,7 @@ public abstract class MatchImpl implements Match {
}
protected void shufflePlayers() {
Collections.shuffle(this.players, new Random());
Collections.shuffle(this.players, RandomUtil.getRandom());
}
@Override

View file

@ -31,6 +31,7 @@ package mage.game.permanent.token;
import java.util.Random;
import mage.constants.CardType;
import mage.MageInt;
import mage.util.RandomUtil;
/**
*
@ -41,7 +42,7 @@ public class CentaurToken extends Token {
public CentaurToken() {
super("Centaur", "3/3 green Centaur creature token");
cardType.add(CardType.CREATURE);
setTokenType(new Random().nextInt(2) +1); // randomly take image 1 or 2
setTokenType(RandomUtil.nextInt(2) +1); // randomly take image 1 or 2
color.setGreen(true);
subtype.add("Centaur");
power = new MageInt(3);

View file

@ -38,6 +38,7 @@ import mage.abilities.costs.mana.GenericManaCost;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.constants.CardType;
import mage.constants.Zone;
import mage.util.RandomUtil;
/**
*
@ -69,10 +70,10 @@ public class ClueArtifactToken extends Token {
public void setExpansionSetCodeForImage(String code) {
super.setExpansionSetCodeForImage(code);
if (getOriginalExpansionSetCode().equals("SOI")) {
this.setTokenType(new Random().nextInt(6) + 1); // 6 different images
this.setTokenType(RandomUtil.nextInt(6) + 1); // 6 different images
}
if (getOriginalExpansionSetCode().equals("EDM")) {
this.setTokenType(new Random().nextInt(6) + 1); // 6 different images
this.setTokenType(RandomUtil.nextInt(6) + 1); // 6 different images
}
}

View file

@ -37,6 +37,7 @@ import mage.abilities.costs.common.SacrificeSourceCost;
import mage.abilities.mana.SimpleManaAbility;
import mage.constants.CardType;
import mage.constants.Zone;
import mage.util.RandomUtil;
/**
*
@ -65,10 +66,10 @@ public class EldraziScionToken extends Token {
public void setExpansionSetCodeForImage(String code) {
super.setExpansionSetCodeForImage(code);
if (getOriginalExpansionSetCode().equals("BFZ")) {
this.setTokenType(new Random().nextInt(3) + 1); // 3 different images
this.setTokenType(RandomUtil.nextInt(3) + 1); // 3 different images
}
if (getOriginalExpansionSetCode().equals("OGW")) {
this.setTokenType(new Random().nextInt(6) + 1); // 6 different images
this.setTokenType(RandomUtil.nextInt(6) + 1); // 6 different images
}
}

View file

@ -37,6 +37,7 @@ import mage.abilities.costs.common.SacrificeSourceCost;
import mage.abilities.mana.SimpleManaAbility;
import mage.constants.CardType;
import mage.constants.Zone;
import mage.util.RandomUtil;
/**
*
@ -61,6 +62,6 @@ public class EldraziSpawnToken extends Token {
availableImageSetCodes = tokenImageSets;
// Get one of the three possible token images
this.setTokenType(new Random().nextInt(3) + 1);
this.setTokenType(RandomUtil.nextInt(3) + 1);
}
}

View file

@ -33,6 +33,7 @@ import java.util.List;
import java.util.Random;
import mage.MageInt;
import mage.constants.CardType;
import mage.util.RandomUtil;
/**
*
@ -62,7 +63,7 @@ public class SoldierToken extends Token {
public void setExpansionSetCodeForImage(String code) {
super.setExpansionSetCodeForImage(code);
if (getOriginalExpansionSetCode().equals("THS")) {
this.setTokenType(new Random().nextInt(2) + 1);
this.setTokenType(RandomUtil.nextInt(2) + 1);
}
}

View file

@ -34,6 +34,7 @@ import java.util.Random;
import mage.MageInt;
import mage.abilities.keyword.FlyingAbility;
import mage.constants.CardType;
import mage.util.RandomUtil;
/**
*
@ -63,7 +64,7 @@ public class ThopterColorlessToken extends Token {
public void setExpansionSetCodeForImage(String code) {
super.setExpansionSetCodeForImage(code);
if (getOriginalExpansionSetCode().equals("ORI")) {
this.setTokenType(new Random().nextInt(2) + 1);
this.setTokenType(RandomUtil.nextInt(2) + 1);
}
}

View file

@ -46,6 +46,7 @@ import mage.game.events.ZoneChangeEvent;
import mage.game.permanent.Permanent;
import mage.game.permanent.PermanentToken;
import mage.players.Player;
import mage.util.RandomUtil;
public class Token extends MageObjectImpl {
@ -290,7 +291,7 @@ public class Token extends MageObjectImpl {
// we should not set random set if appropriate set is already used
if (getOriginalExpansionSetCode() == null || getOriginalExpansionSetCode().isEmpty()
|| !availableImageSetCodes.contains(getOriginalExpansionSetCode())) {
setOriginalExpansionSetCode(availableImageSetCodes.get(new Random().nextInt(availableImageSetCodes.size())));
setOriginalExpansionSetCode(availableImageSetCodes.get(RandomUtil.nextInt(availableImageSetCodes.size())));
}
}
} else {

View file

@ -32,6 +32,7 @@ import java.util.Arrays;
import java.util.Random;
import mage.MageInt;
import mage.constants.CardType;
import mage.util.RandomUtil;
/**
*
@ -62,7 +63,7 @@ public class WarriorToken extends Token {
public void setExpansionSetCodeForImage(String code) {
super.setExpansionSetCodeForImage(code);
if (getOriginalExpansionSetCode().equals("KTK")) {
this.setTokenType(new Random().nextInt(2) + 1);
this.setTokenType(RandomUtil.nextInt(2) + 1);
}
}
}

View file

@ -33,6 +33,7 @@ import java.util.List;
import java.util.Random;
import mage.MageInt;
import mage.constants.CardType;
import mage.util.RandomUtil;
/**
*
@ -61,13 +62,13 @@ public class ZombieToken extends Token {
public void setExpansionSetCodeForImage(String code) {
super.setExpansionSetCodeForImage(code);
if (getOriginalExpansionSetCode().equals("ISD")) {
this.setTokenType(new Random().nextInt(3) + 1);
this.setTokenType(RandomUtil.nextInt(3) + 1);
}
if (getOriginalExpansionSetCode().equals("C14")) {
this.setTokenType(2);
}
if (getOriginalExpansionSetCode().equals("EMN")) {
this.setTokenType(new Random().nextInt(4) + 1);
this.setTokenType(RandomUtil.nextInt(4) + 1);
}
}

View file

@ -57,6 +57,7 @@ import mage.game.result.ResultProtos.MatchQuitStatus;
import mage.game.result.ResultProtos.TourneyProto;
import mage.game.result.ResultProtos.TourneyRoundProto;
import mage.players.Player;
import mage.util.RandomUtil;
import org.apache.log4j.Logger;
/**
@ -68,7 +69,6 @@ public abstract class TournamentImpl implements Tournament {
protected UUID id = UUID.randomUUID();
protected List<Round> rounds = new CopyOnWriteArrayList<>();
protected Map<UUID, TournamentPlayer> players = new HashMap<>();
protected static Random rnd = new Random();
protected String matchName;
protected TournamentOptions options;
protected TournamentType tournamentType;
@ -217,7 +217,7 @@ public abstract class TournamentImpl implements Tournament {
private TournamentPlayer getNextAvailablePlayer(List<TournamentPlayer> roundPlayers, List<TournamentPlayer> playerWithByes) {
TournamentPlayer nextPlayer;
if (playerWithByes.isEmpty()) {
int i = rnd.nextInt(roundPlayers.size());
int i = RandomUtil.nextInt(roundPlayers.size());
nextPlayer = roundPlayers.get(i);
roundPlayers.remove(i);
} else { // prefer players with byes to pair

View file

@ -45,6 +45,7 @@ import mage.cards.Card;
import mage.constants.Zone;
import mage.filter.FilterCard;
import mage.game.Game;
import mage.util.RandomUtil;
/**
*
@ -52,7 +53,6 @@ import mage.game.Game;
*/
public class Library implements Serializable {
private static Random rnd = new Random();
private boolean emptyDraw;
private final Deque<UUID> library = new ArrayDeque<>();
@ -76,7 +76,7 @@ public class Library implements Serializable {
public void shuffle() {
UUID[] shuffled = library.toArray(new UUID[0]);
for (int n = shuffled.length - 1; n > 0; n--) {
int r = rnd.nextInt(n);
int r = RandomUtil.nextInt(n);
UUID temp = shuffled[n];
shuffled[n] = shuffled[r];
shuffled[r] = temp;

View file

@ -135,13 +135,13 @@ import mage.target.common.TargetCardInLibrary;
import mage.target.common.TargetDiscard;
import mage.util.CardUtil;
import mage.util.GameLog;
import mage.util.RandomUtil;
import org.apache.log4j.Logger;
public abstract class PlayerImpl implements Player, Serializable {
private static final Logger logger = Logger.getLogger(PlayerImpl.class);
private static Random rnd = new Random();
private static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
/**
@ -2329,7 +2329,7 @@ public abstract class PlayerImpl implements Player, Serializable {
*/
@Override
public boolean flipCoin(Game game, ArrayList<UUID> appliedEffects) {
boolean result = rnd.nextBoolean();
boolean result = RandomUtil.nextBoolean();
if (!game.isSimulation()) {
game.informPlayers("[Flip a coin] " + getLogName() + (result ? " won (head)." : " lost (tail)."));
}

View file

@ -47,6 +47,7 @@ import mage.game.Game;
import mage.game.events.GameEvent;
import mage.game.events.GameEvent.EventType;
import mage.players.Player;
import mage.util.RandomUtil;
/**
*
@ -322,7 +323,7 @@ public abstract class TargetImpl implements Target {
Set<UUID> possibleTargets = possibleTargets(source.getSourceId(), playerId, game);
if (possibleTargets.size() > 0) {
int i = 0;
int rnd = new Random().nextInt(possibleTargets.size());
int rnd = RandomUtil.nextInt(possibleTargets.size());
Iterator it = possibleTargets.iterator();
while (i < rnd) {
it.next();

View file

@ -0,0 +1,28 @@
package mage.util;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
/**
* Created by IGOUDT on 5-9-2016.
*/
public class RandomUtil {
private static ThreadLocalRandom random = ThreadLocalRandom.current();
public static Random getRandom(){
return random;
}
public static int nextInt(){
return random.nextInt();
}
public static int nextInt(int max){
return random.nextInt(max);
}
public static boolean nextBoolean() {
return random.nextBoolean();
}
}

View file

@ -61,10 +61,9 @@ public class TournamentUtil {
if (landSetCodes.isEmpty()) {
// if sets have no basic lands and also it has no parent or parent has no lands get last set with lands
// select a set with basic lands by random
Random generator = new Random();
List<ExpansionInfo> basicLandSets = ExpansionRepository.instance.getSetsWithBasicLandsByReleaseDate();
if (basicLandSets.size() > 0) {
landSetCodes.add(basicLandSets.get(generator.nextInt(basicLandSets.size())).getCode());
landSetCodes.add(basicLandSets.get(RandomUtil.nextInt(basicLandSets.size())).getCode());
}
}
@ -75,7 +74,6 @@ public class TournamentUtil {
}
public static List<Card> getLands(String landName, int number, Set<String> landSets) {
Random random = new Random();
CardCriteria criteria = new CardCriteria();
if (!landSets.isEmpty()) {
criteria.setCodes(landSets.toArray(new String[landSets.size()]));
@ -85,7 +83,7 @@ public class TournamentUtil {
List<Card> cards = new ArrayList<>();
if (!lands.isEmpty()) {
for (int i = 0; i < number; i++) {
Card land = lands.get(random.nextInt(lands.size())).getCard();
Card land = lands.get(RandomUtil.nextInt(lands.size())).getCard();
cards.add(land);
}
}