Single class IdFactory with synchronized static methods.

This commit is contained in:
MobiusDevelopment
2020-02-08 14:34:00 +00:00
parent 29771aa0d8
commit a534cc943c
497 changed files with 4701 additions and 10894 deletions

View File

@ -36,7 +36,6 @@ import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;
import org.l2jmobius.commons.enums.IdFactoryType;
import org.l2jmobius.commons.enums.ServerMode;
import org.l2jmobius.commons.util.ClassMasterSettings;
import org.l2jmobius.commons.util.L2Properties;
@ -78,7 +77,6 @@ public class Config
// protected
private static final String DAEMONS_CONFIG_FILE = "./config/protected/Daemons.ini";
private static final String PROTECT_FLOOD_CONFIG_FILE = "./config/protected/Flood.ini";
private static final String ID_CONFIG_FILE = "./config/protected/IdFactory.ini";
private static final String PROTECT_OTHER_CONFIG_FILE = "./config/protected/Other.ini";
public static final String TELNET_CONFIG_FILE = "./config/protected/Telnet.ini";
// events
@ -216,9 +214,6 @@ public class Config
public static boolean IS_TELNET_ENABLED;
public static IdFactoryType IDFACTORY_TYPE;
public static boolean BAD_ID_CHECKING;
public static boolean JAIL_IS_PVP;
public static boolean JAIL_DISABLE_CHAT;
public static int WYVERN_SPEED;
@ -1282,25 +1277,6 @@ public class Config
}
public static void loadIdFactoryConfig()
{
try
{
final Properties idSettings = new Properties();
final InputStream is = new FileInputStream(new File(ID_CONFIG_FILE));
idSettings.load(is);
is.close();
IDFACTORY_TYPE = IdFactoryType.valueOf(idSettings.getProperty("IDFactory", "BITSET"));
BAD_ID_CHECKING = Boolean.parseBoolean(idSettings.getProperty("BadIdChecking", "true"));
}
catch (Exception e)
{
e.printStackTrace();
throw new Error("Failed to Load " + ID_CONFIG_FILE + " File.");
}
}
public static void loadRatesConfig()
{
try
@ -3768,9 +3744,6 @@ public class Config
// Load network
loadServerConfig();
// Load system
loadIdFactoryConfig();
// Head
loadRatesConfig();
loadCharacterConfig();

View File

@ -1,26 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.l2jmobius.commons.enums;
/**
* @author Mobius
*/
public enum IdFactoryType
{
BITSET,
STACK
}

View File

@ -180,7 +180,8 @@ public class GameServer
}
Util.printSection("IdFactory");
if (!IdFactory.getInstance().isInitialized())
IdFactory.init();
if (!IdFactory.hasInitialized())
{
LOGGER.severe("IdFactory: Could not read object IDs from database. Please check your configuration.");
throw new Exception("Could not initialize the ID factory!");
@ -412,7 +413,7 @@ public class GameServer
Util.printSection("Game Server");
LOGGER.info("IdFactory: Free ObjectID's remaining: " + IdFactory.getInstance().size());
LOGGER.info("IdFactory: Free ObjectID's remaining: " + IdFactory.size());
if (Config.L2JMOD_ALLOW_WEDDING)
{

View File

@ -140,10 +140,8 @@ public class CrestCache
LOGGER.info("Found old crest file \"" + file.getName() + "\" for clanId " + clanId);
final int newId = IdFactory.getInstance().getNextId();
final int newId = IdFactory.getNextId();
final Clan clan = ClanTable.getInstance().getClan(clanId);
if (clan != null)
{
removeOldPledgeCrest(clan.getCrestId());

View File

@ -180,7 +180,7 @@ public class ItemTable
public ItemInstance createItem(String process, int itemId, int count, PlayerInstance actor, WorldObject reference)
{
// Create and Init the ItemInstance corresponding to the Item Identifier
final ItemInstance item = new ItemInstance(IdFactory.getInstance().getNextId(), itemId);
final ItemInstance item = new ItemInstance(IdFactory.getNextId(), itemId);
// create loot schedule also if autoloot is enabled
if (process.equalsIgnoreCase("loot")/* && !Config.AUTO_LOOT */)
@ -299,7 +299,7 @@ public class ItemTable
item.setLastChange(ItemInstance.REMOVED);
World.getInstance().removeObject(item);
IdFactory.getInstance().releaseId(item.getObjectId());
IdFactory.releaseId(item.getObjectId());
// if it's a pet control item, delete the pet as well
if (PetDataTable.isPetItem(item.getItemId()))

View File

@ -191,7 +191,7 @@ public class ClanTable
return null;
}
final Clan clan = new Clan(IdFactory.getInstance().getNextId(), clanName);
final Clan clan = new Clan(IdFactory.getNextId(), clanName);
final ClanMember leader = new ClanMember(clan, player.getName(), player.getLevel(), player.getClassId().getId(), player.getObjectId(), player.getPledgeType(), player.getPowerGrade(), player.getTitle());
clan.setLeader(leader);
@ -329,7 +329,7 @@ public class ClanTable
final int clanLvl = clan.getLevel();
_clans.remove(clanId);
IdFactory.getInstance().releaseId(clanId);
IdFactory.releaseId(clanId);
try (Connection con = DatabaseFactory.getConnection())
{

View File

@ -123,7 +123,7 @@ public class BoatData implements IXmlReader
npcDat.set("baseMDef", 100);
final CreatureTemplate template = new CreatureTemplate(npcDat);
final BoatInstance boat = new BoatInstance(IdFactory.getInstance().getNextId(), template);
final BoatInstance boat = new BoatInstance(IdFactory.getNextId(), template);
boat.getPosition().setHeading(set.getInt("heading"));
boat.setXYZ(set.getInt("spawnX"), set.getInt("spawnY"), set.getInt("spawnZ"));
boat.setPathA(set.getInt("pathIdA"), set.getInt("ticketA"), set.getInt("xTeleNoTicketA"), set.getInt("yTeleNoTicketA"), set.getInt("zTeleNoTicketA"), set.getString("announcerA"), set.getString("message10A"), set.getString("message5A"), set.getString("message1A"), set.getString("message0A"), set.getString("messageBeginA"), paths.get(set.getInt("pathIdA")));

View File

@ -180,7 +180,7 @@ public class DoorData implements IXmlReader
npcDat.set("baseMDef", mDef);
final CreatureTemplate template = new CreatureTemplate(npcDat);
final DoorInstance door = new DoorInstance(IdFactory.getInstance().getNextId(), template, id, name, unlockable);
final DoorInstance door = new DoorInstance(IdFactory.getNextId(), template, id, name, unlockable);
door.setRange(xMin, yMin, zMin, xMax, yMax, zMax);
try
{

View File

@ -75,7 +75,7 @@ public class StaticObjectData implements IXmlReader
}
// Create and spawn the StaticObject instance.
final StaticObjectInstance obj = new StaticObjectInstance(IdFactory.getInstance().getNextId());
final StaticObjectInstance obj = new StaticObjectInstance(IdFactory.getNextId());
obj.setType(set.getInt("type"));
obj.setStaticObjectId(set.getInt("id"));
obj.setXYZ(set.getInt("x"), set.getInt("y"), set.getInt("z"));

View File

@ -216,9 +216,9 @@ public class AdminFightCalculator implements IAdminCommandHandler
mid1 = Integer.parseInt(st.nextToken());
mid2 = Integer.parseInt(st.nextToken());
npc1 = new MonsterInstance(IdFactory.getInstance().getNextId(), NpcTable.getInstance().getTemplate(mid1));
npc1 = new MonsterInstance(IdFactory.getNextId(), NpcTable.getInstance().getTemplate(mid1));
npc2 = new MonsterInstance(IdFactory.getInstance().getNextId(), NpcTable.getInstance().getTemplate(mid2));
npc2 = new MonsterInstance(IdFactory.getNextId(), NpcTable.getInstance().getTemplate(mid2));
}
int miss1 = 0;

View File

@ -73,7 +73,7 @@ public class ChristmasTree implements IItemHandler
try
{
final Spawn spawn = new Spawn(template1);
spawn.setId(IdFactory.getInstance().getNextId());
spawn.setId(IdFactory.getNextId());
spawn.setX(target.getX());
spawn.setY(target.getY());
spawn.setZ(target.getZ());

View File

@ -64,7 +64,7 @@ public class JackpotSeed implements IItemHandler
try
{
final Spawn spawn = new Spawn(template1);
spawn.setId(IdFactory.getInstance().getNextId());
spawn.setId(IdFactory.getNextId());
spawn.setX(player.getX());
spawn.setY(player.getY());
spawn.setZ(player.getZ());

View File

@ -148,7 +148,7 @@ public class SummonItems implements IItemHandler
try
{
final Spawn spawn = new Spawn(npcTemplate);
spawn.setId(IdFactory.getInstance().getNextId());
spawn.setId(IdFactory.getNextId());
spawn.setX(player.getX());
spawn.setY(player.getY());
spawn.setZ(player.getZ());

View File

@ -79,7 +79,7 @@ public class SiegeFlag implements ISkillHandler
try
{
// Spawn a new flag
final SiegeFlagInstance flag = new SiegeFlagInstance(player, IdFactory.getInstance().getNextId(), NpcTable.getInstance().getTemplate(35062));
final SiegeFlagInstance flag = new SiegeFlagInstance(player, IdFactory.getNextId(), NpcTable.getInstance().getTemplate(35062));
if (skill.isAdvancedFlag())
{

View File

@ -1,151 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.l2jmobius.gameserver.idfactory;
import java.util.BitSet;
import java.util.concurrent.atomic.AtomicInteger;
import org.l2jmobius.commons.concurrent.ThreadPool;
import org.l2jmobius.gameserver.util.PrimeFinder;
/**
* This class ..
* @version $Revision: 1.2 $ $Date: 2004/06/27 08:12:59 $
*/
public class BitSetIDFactory extends IdFactory
{
private BitSet _freeIds;
private AtomicInteger _freeIdCount;
private AtomicInteger _nextFreeId;
protected class BitSetCapacityCheck implements Runnable
{
@Override
public void run()
{
synchronized (BitSetIDFactory.this)
{
if (reachingBitSetCapacity())
{
increaseBitSetCapacity();
}
}
}
}
protected BitSetIDFactory()
{
super();
synchronized (BitSetIDFactory.class)
{
ThreadPool.scheduleAtFixedRate(new BitSetCapacityCheck(), 30000, 30000);
initialize();
}
LOGGER.info(getClass().getSimpleName() + ": " + _freeIds.size() + " id's available.");
}
public void initialize()
{
try
{
_freeIds = new BitSet(PrimeFinder.nextPrime(100000));
_freeIds.clear();
_freeIdCount = new AtomicInteger(FREE_OBJECT_ID_SIZE);
for (int usedObjectId : extractUsedObjectIDTable())
{
final int objectID = usedObjectId - FIRST_OID;
if (objectID < 0)
{
LOGGER.warning(getClass().getSimpleName() + ": Object ID " + usedObjectId + " in DB is less than minimum ID of " + FIRST_OID);
continue;
}
_freeIds.set(usedObjectId - FIRST_OID);
_freeIdCount.decrementAndGet();
}
_nextFreeId = new AtomicInteger(_freeIds.nextClearBit(0));
_initialized = true;
}
catch (Exception e)
{
_initialized = false;
LOGGER.severe(getClass().getSimpleName() + ": Could not be initialized properly: " + e.getMessage());
}
}
@Override
public synchronized void releaseId(int objectID)
{
if ((objectID - FIRST_OID) > -1)
{
_freeIds.clear(objectID - FIRST_OID);
_freeIdCount.incrementAndGet();
}
else
{
LOGGER.warning(getClass().getSimpleName() + ": Release objectID " + objectID + " failed (< " + FIRST_OID + ")");
}
}
@Override
public synchronized int getNextId()
{
final int newID = _nextFreeId.get();
_freeIds.set(newID);
_freeIdCount.decrementAndGet();
final int nextFree = _freeIds.nextClearBit(newID) < 0 ? _freeIds.nextClearBit(0) : _freeIds.nextClearBit(newID);
if (nextFree < 0)
{
if (_freeIds.size() >= FREE_OBJECT_ID_SIZE)
{
throw new NullPointerException("Ran out of valid Id's.");
}
increaseBitSetCapacity();
}
_nextFreeId.set(nextFree);
return newID + FIRST_OID;
}
@Override
public synchronized int size()
{
return _freeIdCount.get();
}
protected synchronized int usedIdCount()
{
return _freeIdCount.get() - FIRST_OID;
}
protected synchronized boolean reachingBitSetCapacity()
{
return PrimeFinder.nextPrime((usedIdCount() * 11) / 10) > _freeIds.size();
}
protected synchronized void increaseBitSetCapacity()
{
final BitSet newBitSet = new BitSet(PrimeFinder.nextPrime((usedIdCount() * 11) / 10));
newBitSet.or(_freeIds);
_freeIds = newBitSet;
}
}

View File

@ -17,24 +17,26 @@
package org.l2jmobius.gameserver.idfactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import org.l2jmobius.Config;
import org.l2jmobius.commons.concurrent.ThreadPool;
import org.l2jmobius.commons.database.DatabaseFactory;
import org.l2jmobius.gameserver.util.PrimeFinder;
/**
* @version $Revision: 1.3.2.1.2.7 $ $Date: 2005/04/11 10:06:12 $
* @author Mobius (reworked from L2J version)
*/
public abstract class IdFactory
{
protected final Logger LOGGER = Logger.getLogger(getClass().getName());
private static final Logger LOGGER = Logger.getLogger(IdFactory.class.getName());
protected static final String[] ID_CHECKS =
{
@ -59,80 +61,50 @@ public abstract class IdFactory
"SELECT item_obj_id FROM pets WHERE item_obj_id >= ? AND item_obj_id < ?",
"SELECT object_id FROM itemsonground WHERE object_id >= ? AND object_id < ?"
};
//@formatter:off
private static final String[][] ID_EXTRACTS =
{
{"characters", "obj_Id"},
{"items", "object_id"},
{"clan_data", "clan_id"},
{"itemsonground", "object_id"}
{"characters","obj_Id"},
{"items","object_id"},
{"clan_data","clan_id"},
{"itemsonground","object_id"}
};
//@formatter:on
protected boolean _initialized;
private static final String[] TIMESTAMPS_CLEAN =
{
"DELETE FROM character_skills_save WHERE restore_type = 1 AND systime <= ?"
};
public static final int FIRST_OID = 0x10000000;
public static final int LAST_OID = 0x7FFFFFFF;
public static final int FREE_OBJECT_ID_SIZE = LAST_OID - FIRST_OID;
protected static final IdFactory _instance;
private static BitSet _freeIds;
private static AtomicInteger _freeIdCount;
private static AtomicInteger _nextFreeId;
private static boolean _initialized;
protected IdFactory()
{
setAllCharacterOffline();
cleanUpDB();
}
static
{
switch (Config.IDFACTORY_TYPE)
{
case BITSET:
{
_instance = new BitSetIDFactory();
break;
}
case STACK:
{
_instance = new StackIDFactory();
break;
}
default:
{
_instance = null;
break;
}
}
}
/**
* Sets all character offline
*/
private void setAllCharacterOffline()
public static void init()
{
// Update characters online status.
try (Connection con = DatabaseFactory.getConnection();
Statement s = con.createStatement())
{
s.executeUpdate("UPDATE characters SET online = 0");
LOGGER.info("Updated characters online status.");
}
catch (SQLException e)
catch (Exception e)
{
LOGGER.log(Level.WARNING, "Could not update characters online status: " + e.getMessage(), e);
LOGGER.warning("IdFactory: Could not update characters online status: " + e);
}
}
/**
* Cleans up Database
*/
private void cleanUpDB()
{
try (Connection con = DatabaseFactory.getConnection())
// Cleanup database.
try (Connection con = DatabaseFactory.getConnection();
Statement stmt = con.createStatement())
{
final long cleanupStart = System.currentTimeMillis();
int cleanCount = 0;
final Statement stmt = con.createStatement();
// Character related
// Characters
cleanCount += stmt.executeUpdate("DELETE FROM character_friends WHERE character_friends.char_id NOT IN (SELECT obj_Id FROM characters);");
cleanCount += stmt.executeUpdate("DELETE FROM character_hennas WHERE character_hennas.char_obj_id NOT IN (SELECT obj_Id FROM characters);");
cleanCount += stmt.executeUpdate("DELETE FROM character_macroses WHERE character_macroses.char_obj_id NOT IN (SELECT obj_Id FROM characters);");
@ -147,10 +119,12 @@ public abstract class IdFactory
cleanCount += stmt.executeUpdate("DELETE FROM olympiad_nobles WHERE olympiad_nobles.char_id NOT IN (SELECT obj_Id FROM characters);");
cleanCount += stmt.executeUpdate("DELETE FROM pets WHERE pets.item_obj_id NOT IN (SELECT object_id FROM items);");
cleanCount += stmt.executeUpdate("DELETE FROM seven_signs WHERE seven_signs.char_obj_id NOT IN (SELECT obj_Id FROM characters);");
// Auction
cleanCount += stmt.executeUpdate("DELETE FROM auction WHERE auction.id IN (SELECT id FROM clanhall WHERE ownerId <> 0);");
cleanCount += stmt.executeUpdate("DELETE FROM auction_bid WHERE auctionId IN (SELECT id FROM clanhall WHERE ownerId <> 0)");
// Clan related
// Clan
stmt.executeUpdate("UPDATE clan_data SET auction_bid_at = 0 WHERE auction_bid_at NOT IN (SELECT auctionId FROM auction_bid);");
cleanCount += stmt.executeUpdate("DELETE FROM clan_data WHERE clan_data.leader_id NOT IN (SELECT obj_Id FROM characters);");
cleanCount += stmt.executeUpdate("DELETE FROM auction_bid WHERE auction_bid.bidderId NOT IN (SELECT clan_id FROM clan_data);");
@ -162,71 +136,165 @@ public abstract class IdFactory
cleanCount += stmt.executeUpdate("DELETE FROM clan_wars WHERE clan_wars.clan2 NOT IN (SELECT clan_id FROM clan_data);");
cleanCount += stmt.executeUpdate("DELETE FROM siege_clans WHERE siege_clans.clan_id NOT IN (SELECT clan_id FROM clan_data);");
stmt.executeUpdate("UPDATE castle SET taxpercent=0 WHERE castle.id NOT IN (SELECT hasCastle FROM clan_data);");
// Character & clan related
cleanCount += stmt.executeUpdate("DELETE FROM items WHERE items.owner_id NOT IN (SELECT obj_Id FROM characters) AND items.owner_id NOT IN (SELECT clan_id FROM clan_data);");
stmt.executeUpdate("UPDATE characters SET clanid=0 WHERE characters.clanid NOT IN (SELECT clan_id FROM clan_data);");
// Forum related
// Forums
cleanCount += stmt.executeUpdate("DELETE FROM forums WHERE forums.forum_owner_id NOT IN (SELECT clan_id FROM clan_data) AND forums.forum_parent=2;");
cleanCount += stmt.executeUpdate("DELETE FROM topic WHERE topic.topic_forum_id NOT IN (SELECT forum_id FROM forums);");
cleanCount += stmt.executeUpdate("DELETE FROM posts WHERE posts.post_forum_id NOT IN (SELECT forum_id FROM forums);");
stmt.close();
LOGGER.info("Cleaned " + cleanCount + " elements from database.");
}
catch (SQLException e)
{
// Ignore.
}
}
/**
* @return
* @throws Exception
* @throws SQLException
*/
protected final Integer[] extractUsedObjectIDTable() throws Exception
{
final List<Integer> temp = new ArrayList<>();
try (Connection con = DatabaseFactory.getConnection();
Statement s = con.createStatement())
{
String extractUsedObjectIdsQuery = "";
// Update needed items after cleaning has taken place.
cleanCount += stmt.executeUpdate("DELETE FROM items WHERE items.owner_id NOT IN (SELECT obj_Id FROM characters) AND items.owner_id NOT IN (SELECT clan_id FROM clan_data);");
stmt.executeUpdate("UPDATE characters SET clanid=0 WHERE characters.clanid NOT IN (SELECT clan_id FROM clan_data);");
for (String[] tblClmn : ID_EXTRACTS)
LOGGER.info("IdFactory: Cleaned " + cleanCount + " elements from database in " + ((System.currentTimeMillis() - cleanupStart) / 1000) + " seconds.");
}
catch (Exception e)
{
LOGGER.warning("IdFactory: Could not clean up database: " + e);
}
// Cleanup timestamps.
try (Connection con = DatabaseFactory.getConnection())
{
int cleanCount = 0;
for (String line : TIMESTAMPS_CLEAN)
{
extractUsedObjectIdsQuery += "SELECT " + tblClmn[1] + " FROM " + tblClmn[0] + " UNION ";
}
extractUsedObjectIdsQuery = extractUsedObjectIdsQuery.substring(0, extractUsedObjectIdsQuery.length() - 7); // Remove the last " UNION "
try (ResultSet rs = s.executeQuery(extractUsedObjectIdsQuery))
{
while (rs.next())
try (PreparedStatement stmt = con.prepareStatement(line))
{
temp.add(rs.getInt(1));
stmt.setLong(1, System.currentTimeMillis());
cleanCount += stmt.executeUpdate();
}
}
LOGGER.info("IdFactory: Cleaned " + cleanCount + " expired timestamps from database.");
}
Collections.sort(temp);
return temp.toArray(new Integer[temp.size()]);
catch (Exception e)
{
LOGGER.warning("IdFactory: Could not clean expired timestamps from database. " + e);
}
// Initialize.
try
{
_freeIds = new BitSet(PrimeFinder.nextPrime(100000));
_freeIds.clear();
_freeIdCount = new AtomicInteger(FREE_OBJECT_ID_SIZE);
// Collect already used ids.
final List<Integer> usedIds = new ArrayList<>();
try (Connection con = DatabaseFactory.getConnection();
Statement statement = con.createStatement())
{
String extractUsedObjectIdsQuery = "";
for (String[] tblClmn : ID_EXTRACTS)
{
extractUsedObjectIdsQuery += "SELECT " + tblClmn[1] + " FROM " + tblClmn[0] + " UNION ";
}
extractUsedObjectIdsQuery = extractUsedObjectIdsQuery.substring(0, extractUsedObjectIdsQuery.length() - 7); // Remove the last " UNION "
try (ResultSet result = statement.executeQuery(extractUsedObjectIdsQuery))
{
while (result.next())
{
usedIds.add(result.getInt(1));
}
}
}
Collections.sort(usedIds);
// Register used ids.
for (int usedObjectId : usedIds)
{
final int objectId = usedObjectId - FIRST_OID;
if (objectId < 0)
{
LOGGER.warning("IdFactory: Object ID " + usedObjectId + " in DB is less than minimum ID of " + FIRST_OID);
continue;
}
_freeIds.set(usedObjectId - FIRST_OID);
_freeIdCount.decrementAndGet();
}
_nextFreeId = new AtomicInteger(_freeIds.nextClearBit(0));
_initialized = true;
}
catch (Exception e)
{
_initialized = false;
LOGGER.severe("IdFactory: Could not be initialized properly: " + e.getMessage());
}
// Schedule increase capacity task.
ThreadPool.scheduleAtFixedRate(() ->
{
synchronized (_nextFreeId)
{
if (PrimeFinder.nextPrime((usedIdCount() * 11) / 10) > _freeIds.size())
{
increaseBitSetCapacity();
}
}
}, 30000, 30000);
LOGGER.info("IdFactory: " + _freeIds.size() + " id's available.");
}
public boolean isInitialized()
public synchronized static void releaseId(int objectId)
{
synchronized (_nextFreeId)
{
if ((objectId - FIRST_OID) > -1)
{
_freeIds.clear(objectId - FIRST_OID);
_freeIdCount.incrementAndGet();
}
else
{
LOGGER.warning("IdFactory: Release objectID " + objectId + " failed (< " + FIRST_OID + ")");
}
}
}
public synchronized static int getNextId()
{
synchronized (_nextFreeId)
{
final int newId = _nextFreeId.get();
_freeIds.set(newId);
_freeIdCount.decrementAndGet();
final int nextFree = _freeIds.nextClearBit(newId) < 0 ? _freeIds.nextClearBit(0) : _freeIds.nextClearBit(newId);
if (nextFree < 0)
{
if (_freeIds.size() >= FREE_OBJECT_ID_SIZE)
{
throw new NullPointerException("IdFactory: Ran out of valid ids.");
}
increaseBitSetCapacity();
}
_nextFreeId.set(nextFree);
return newId + FIRST_OID;
}
}
private static void increaseBitSetCapacity()
{
final BitSet newBitSet = new BitSet(PrimeFinder.nextPrime((usedIdCount() * 11) / 10));
newBitSet.or(_freeIds);
_freeIds = newBitSet;
}
private static int usedIdCount()
{
return _freeIdCount.get() - FIRST_OID;
}
public static int size()
{
return _freeIdCount.get();
}
public static boolean hasInitialized()
{
return _initialized;
}
public static IdFactory getInstance()
{
return _instance;
}
public abstract int getNextId();
/**
* return a used Object ID back to the pool
* @param id
*/
public abstract void releaseId(int id);
public abstract int size();
}

View File

@ -1,152 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.l2jmobius.gameserver.idfactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Stack;
import org.l2jmobius.Config;
import org.l2jmobius.commons.database.DatabaseFactory;
/**
* @version $Revision: 1.3.2.1.2.7 $ $Date: 2005/04/11 10:06:12 $
*/
public class StackIDFactory extends IdFactory
{
private int _curOID;
private int _tempOID;
private final Stack<Integer> _freeOIDStack = new Stack<>();
protected StackIDFactory()
{
super();
_curOID = FIRST_OID;
_tempOID = FIRST_OID;
try (Connection con = DatabaseFactory.getConnection())
{
// con.createStatement().execute("drop table if exists tmp_obj_id");
final Integer[] tmpObjIds = extractUsedObjectIDTable();
if (tmpObjIds.length > 0)
{
_curOID = tmpObjIds[tmpObjIds.length - 1];
}
LOGGER.info("Max Id = " + _curOID);
int n = tmpObjIds.length;
for (int idx = 0; idx < n; idx++)
{
n = insertUntil(tmpObjIds, idx, n, con);
}
_curOID++;
LOGGER.info("IdFactory: Next usable Object ID is: " + _curOID);
_initialized = true;
}
catch (Exception e)
{
LOGGER.severe(getClass().getSimpleName() + ": Could not be initialized properly:" + e.getMessage());
}
}
private int insertUntil(Integer[] tmpObjIds, int idx, int n, Connection con) throws SQLException
{
final int id = tmpObjIds[idx];
if (id == _tempOID)
{
_tempOID++;
return n;
}
// check these IDs not present in DB
if (Config.BAD_ID_CHECKING)
{
for (String check : ID_CHECKS)
{
try (PreparedStatement ps = con.prepareStatement(check))
{
ps.setInt(1, _tempOID);
// ps.setInt(1, _curOID);
ps.setInt(2, id);
try (ResultSet rs = ps.executeQuery())
{
if (rs.next())
{
final int badId = rs.getInt(1);
LOGGER.severe("Bad ID " + badId + " in DB found by: " + check);
throw new RuntimeException();
}
}
}
}
}
// int hole = id - _curOID;
final int hole = (id - _tempOID) > (n - idx) ? n - idx : id - _tempOID;
for (int i = 1; i <= hole; i++)
{
_freeOIDStack.push(_tempOID);
_tempOID++;
}
if (hole < (n - idx))
{
_tempOID++;
}
return n - hole;
}
public static IdFactory getInstance()
{
return _instance;
}
@Override
public synchronized int getNextId()
{
int id;
if (!_freeOIDStack.empty())
{
id = _freeOIDStack.pop();
}
else
{
id = _curOID;
_curOID += 1;
}
return id;
}
/**
* return a used Object ID back to the pool
* @param id
*/
@Override
public synchronized void releaseId(int id)
{
_freeOIDStack.push(id);
}
@Override
public int size()
{
return (FREE_OBJECT_ID_SIZE - _curOID) + FIRST_OID + _freeOIDStack.size();
}
}

View File

@ -472,7 +472,7 @@ public class ChristmasManager
final NpcTemplate template1 = NpcTable.getInstance().getTemplate(id);
final Spawn spawn = new Spawn(template1);
spawn.setId(IdFactory.getInstance().getNextId());
spawn.setId(IdFactory.getNextId());
spawn.setX(x);
spawn.setY(y);

View File

@ -716,7 +716,7 @@ public class MercTicketManager
{
itemId = ITEM_IDS[i];
// create the ticket in the gameworld
final ItemInstance dropticket = new ItemInstance(IdFactory.getInstance().getNextId(), itemId);
final ItemInstance dropticket = new ItemInstance(IdFactory.getNextId(), itemId);
dropticket.setLocation(ItemInstance.ItemLocation.VOID);
dropticket.dropMe(null, x, y, z);
dropticket.setDropTime(0); // avoids it from beeing removed by the auto item destroyer
@ -840,7 +840,7 @@ public class MercTicketManager
castle.getSiege().getSiegeGuardManager().hireMerc(x, y, z, heading, NPC_IDS[i]);
// create the ticket in the gameworld
final ItemInstance dropticket = new ItemInstance(IdFactory.getInstance().getNextId(), itemId);
final ItemInstance dropticket = new ItemInstance(IdFactory.getNextId(), itemId);
dropticket.setLocation(ItemInstance.ItemLocation.INVENTORY);
dropticket.dropMe(null, x, y, z);
dropticket.setDropTime(0); // avoids it from beeing removed by the auto item destroyer
@ -859,7 +859,7 @@ public class MercTicketManager
final NpcTemplate template = NpcTable.getInstance().getTemplate(npcId);
if (template != null)
{
final SiegeGuardInstance npc = new SiegeGuardInstance(IdFactory.getInstance().getNextId(), template);
final SiegeGuardInstance npc = new SiegeGuardInstance(IdFactory.getNextId(), template);
npc.setCurrentHpMp(npc.getMaxHp(), npc.getMaxMp());
npc.setDecayed(false);
npc.spawnMe(x, y, (z + 20));

View File

@ -89,7 +89,7 @@ public class PetitionManager
public Petition(PlayerInstance petitioner, String petitionText, int petitionType)
{
petitionType--;
_id = IdFactory.getInstance().getNextId();
_id = IdFactory.getNextId();
if (petitionType >= PetitionType.values().length)
{
LOGGER.warning("PetitionManager:Petition : invalid petition type (received type was +1) : " + petitionType);

View File

@ -205,11 +205,11 @@ public abstract class WorldObject
World.getInstance().removeVisibleObject(this, oldregion);
}
public void refreshID()
public void refreshId()
{
World.getInstance().removeObject(this);
IdFactory.getInstance().releaseId(getObjectId());
_objectId = IdFactory.getInstance().getNextId();
IdFactory.releaseId(getObjectId());
_objectId = IdFactory.getNextId();
}
/**

View File

@ -42,7 +42,7 @@ public class FenceInstance extends WorldObject
public FenceInstance(int x, int y, String name, int width, int length, int height, FenceState state)
{
super(IdFactory.getInstance().getNextId());
super(IdFactory.getNextId());
_xMin = x - (width / 2);
_xMax = x + (width / 2);
@ -60,7 +60,7 @@ public class FenceInstance extends WorldObject
_heightFences = new int[height - 1];
for (int i = 0; i < _heightFences.length; i++)
{
_heightFences[i] = IdFactory.getInstance().getNextId();
_heightFences[i] = IdFactory.getNextId();
}
}
}

View File

@ -2088,7 +2088,7 @@ public class NpcInstance extends Creature
sm.addItemName(4442);
player.sendPacket(sm);
final ItemInstance item = new ItemInstance(IdFactory.getInstance().getNextId(), 4442);
final ItemInstance item = new ItemInstance(IdFactory.getNextId(), 4442);
item.setCount(1);
item.setCustomType1(lotonumber);
item.setEnchantLevel(enchant);

View File

@ -844,11 +844,11 @@ public class PetInstance extends Summon
{
if (template.getType().equalsIgnoreCase("BabyPet"))
{
pet = new BabyPetInstance(IdFactory.getInstance().getNextId(), template, owner, control);
pet = new BabyPetInstance(IdFactory.getNextId(), template, owner, control);
}
else
{
pet = new PetInstance(IdFactory.getInstance().getNextId(), template, owner, control);
pet = new PetInstance(IdFactory.getNextId(), template, owner, control);
}
final PreparedStatement statement = con.prepareStatement("SELECT item_obj_id, name, level, curHp, curMp, exp, sp, karma, pkkills, fed FROM pets WHERE item_obj_id=?");

View File

@ -164,7 +164,7 @@ public class RaceManagerInstance extends FolkInstance
player.setRace(0, 0);
player.setRace(1, 0);
ItemInstance item = new ItemInstance(IdFactory.getInstance().getNextId(), 4443);
ItemInstance item = new ItemInstance(IdFactory.getNextId(), 4443);
item.setCount(1);
item.setEnchantLevel(MonsterRace.getInstance().getRaceNumber());
item.setCustomType1(ticket);

View File

@ -401,7 +401,7 @@ public class Auction
else
{
statement = con.prepareStatement("INSERT INTO auction_bid (id, auctionId, bidderId, bidderName, maxBid, clan_name, time_bid) VALUES (?, ?, ?, ?, ?, ?, ?)");
statement.setInt(1, IdFactory.getInstance().getNextId());
statement.setInt(1, IdFactory.getNextId());
statement.setInt(2, _id);
statement.setInt(3, bidder.getClanId());
statement.setString(4, bidder.getName());

View File

@ -95,7 +95,7 @@ public class Wedding
{
PreparedStatement statement;
_Id = IdFactory.getInstance().getNextId();
_Id = IdFactory.getNextId();
statement = con.prepareStatement("INSERT INTO mods_wedding (id, player1Id, player2Id, married, affianceDate, weddingDate) VALUES (?, ?, ?, ?, ?, ?)");
statement.setInt(1, _Id);

View File

@ -332,7 +332,7 @@ public class MonsterRace
{
final NpcTemplate template = NpcTable.getInstance().getTemplate(_npcTemplates.get(i));
_constructor = Class.forName("org.l2jmobius.gameserver.model.actor.instance." + template.getType() + "Instance").getConstructors()[0];
final int objectId = IdFactory.getInstance().getNextId();
final int objectId = IdFactory.getNextId();
_monsters[i] = (NpcInstance) _constructor.newInstance(objectId, template);
}
catch (Exception e)

View File

@ -1363,7 +1363,7 @@ public class FortSiege
{
CommanderInstance commander;
commander = new CommanderInstance(IdFactory.getInstance().getNextId(), NpcTable.getInstance().getTemplate(_sp.getNpcId()));
commander = new CommanderInstance(IdFactory.getNextId(), NpcTable.getInstance().getTemplate(_sp.getNpcId()));
commander.setCurrentHpMp(commander.getMaxHp(), commander.getMaxMp());
commander.setHeading(_sp.getLocation().getHeading());
commander.spawnMe(_sp.getLocation().getX(), _sp.getLocation().getY(), _sp.getLocation().getZ() + 50);
@ -1387,7 +1387,7 @@ public class FortSiege
{
ArtefactInstance combatflag;
combatflag = new ArtefactInstance(IdFactory.getInstance().getNextId(), NpcTable.getInstance().getTemplate(_sp.getNpcId()));
combatflag = new ArtefactInstance(IdFactory.getNextId(), NpcTable.getInstance().getTemplate(_sp.getNpcId()));
combatflag.setCurrentHpMp(combatflag.getMaxHp(), combatflag.getMaxMp());
combatflag.setHeading(_sp.getLocation().getHeading());
combatflag.spawnMe(_sp.getLocation().getX(), _sp.getLocation().getY(), _sp.getLocation().getZ() + 10);

View File

@ -1595,7 +1595,7 @@ public class Siege
{
ArtefactInstance art;
art = new ArtefactInstance(IdFactory.getInstance().getNextId(), NpcTable.getInstance().getTemplate(_sp.getNpcId()));
art = new ArtefactInstance(IdFactory.getNextId(), NpcTable.getInstance().getTemplate(_sp.getNpcId()));
art.setCurrentHpMp(art.getMaxHp(), art.getMaxMp());
art.setHeading(_sp.getLocation().getHeading());
art.spawnMe(_sp.getLocation().getX(), _sp.getLocation().getY(), _sp.getLocation().getZ() + 50);
@ -1624,7 +1624,7 @@ public class Siege
template.getStatSet().set("baseHpMax", _sp.getHp());
ct = new ControlTowerInstance(IdFactory.getInstance().getNextId(), template);
ct = new ControlTowerInstance(IdFactory.getNextId(), template);
ct.setCurrentHpMp(ct.getMaxHp(), ct.getMaxMp());
ct.spawnMe(_sp.getLocation().getX(), _sp.getLocation().getY(), _sp.getLocation().getZ() + 20);

View File

@ -274,7 +274,7 @@ public class BanditStrongholdSiege extends ClanHallSiege
continue;
}
template = NpcTable.getInstance().getTemplate(35427 + mobCounter);
final MonsterInstance questMob = new MonsterInstance(IdFactory.getInstance().getNextId(), template);
final MonsterInstance questMob = new MonsterInstance(IdFactory.getNextId(), template);
questMob.setHeading(100);
questMob.getStatus().setCurrentHpMp(questMob.getMaxHp(), questMob.getMaxMp());
if (mobCounter == 1)
@ -321,7 +321,7 @@ public class BanditStrongholdSiege extends ClanHallSiege
{
template = NpcTable.getInstance().getTemplate(35422 + flagCounter);
}
final DecoInstance flag = new DecoInstance(IdFactory.getInstance().getNextId(), template);
final DecoInstance flag = new DecoInstance(IdFactory.getNextId(), template);
flag.setTitle(clan.getName());
flag.setHeading(100);
flag.getStatus().setCurrentHpMp(flag.getMaxHp(), flag.getMaxMp());

View File

@ -262,7 +262,7 @@ public class WildBeastFarmSiege extends ClanHallSiege
NpcTemplate template;
final Clan clan = ClanTable.getInstance().getClanByName(clanName);
template = NpcTable.getInstance().getTemplate(35617 + mobCounter);
final MonsterInstance questMob = new MonsterInstance(IdFactory.getInstance().getNextId(), template);
final MonsterInstance questMob = new MonsterInstance(IdFactory.getNextId(), template);
questMob.setHeading(100);
questMob.getStatus().setCurrentHpMp(questMob.getMaxHp(), questMob.getMaxMp());
if (mobCounter == 1)
@ -309,7 +309,7 @@ public class WildBeastFarmSiege extends ClanHallSiege
{
template = NpcTable.getInstance().getTemplate(35422 + flagCounter);
}
final DecoInstance flag = new DecoInstance(IdFactory.getInstance().getNextId(), template);
final DecoInstance flag = new DecoInstance(IdFactory.getNextId(), template);
flag.setTitle(clan.getName());
flag.setHeading(100);
flag.getStatus().setCurrentHpMp(flag.getMaxHp(), flag.getMaxMp());

View File

@ -72,7 +72,7 @@ public class EffectSignetMDam extends Effect
return;
}
final EffectPointInstance effectPoint = new EffectPointInstance(IdFactory.getInstance().getNextId(), template, getEffector());
final EffectPointInstance effectPoint = new EffectPointInstance(IdFactory.getNextId(), template, getEffector());
effectPoint.getStatus().setCurrentHp(effectPoint.getMaxHp());
effectPoint.getStatus().setCurrentMp(effectPoint.getMaxMp());

View File

@ -75,7 +75,7 @@ public class SkillCreateItem extends Skill
*/
public void giveItems(PlayerInstance player, int itemId, int count)
{
final ItemInstance item = new ItemInstance(IdFactory.getInstance().getNextId(), itemId);
final ItemInstance item = new ItemInstance(IdFactory.getNextId(), itemId);
item.setCount(count);
player.getInventory().addItem("Skill", item, player, player);

View File

@ -49,7 +49,7 @@ public class SkillSignet extends Skill
}
final NpcTemplate template = NpcTable.getInstance().getTemplate(_effectNpcId);
final EffectPointInstance effectPoint = new EffectPointInstance(IdFactory.getInstance().getNextId(), template, caster);
final EffectPointInstance effectPoint = new EffectPointInstance(IdFactory.getNextId(), template, caster);
effectPoint.getStatus().setCurrentHp(effectPoint.getMaxHp());
effectPoint.getStatus().setCurrentMp(effectPoint.getMaxMp());
World.getInstance().storeObject(effectPoint);

View File

@ -210,11 +210,11 @@ public class SkillSummon extends Skill
}
if (summonTemplate.getType().equalsIgnoreCase("SiegeSummon"))
{
summon = new SiegeSummonInstance(IdFactory.getInstance().getNextId(), summonTemplate, activeChar, this);
summon = new SiegeSummonInstance(IdFactory.getNextId(), summonTemplate, activeChar, this);
}
else
{
summon = new SummonInstance(IdFactory.getInstance().getNextId(), summonTemplate, activeChar, this);
summon = new SummonInstance(IdFactory.getNextId(), summonTemplate, activeChar, this);
}
summon.setName(summonTemplate.getName());

View File

@ -159,7 +159,7 @@ public class AutoSpawn
}
}
final int newId = IdFactory.getInstance().getNextId();
final int newId = IdFactory.getNextId();
newSpawn._objectId = newId;
synchronized (_registeredSpawns)

View File

@ -54,7 +54,7 @@ public class GroupSpawn extends Spawn
final Object[] parameters =
{
IdFactory.getInstance().getNextId(),
IdFactory.getNextId(),
_template
};
final Object tmp = _constructor.newInstance(parameters);

View File

@ -398,7 +398,7 @@ public class Spawn
// Get NpcInstance Init parameters and its generate an Identifier
final Object[] parameters =
{
IdFactory.getInstance().getNextId(),
IdFactory.getNextId(),
_template
};
@ -460,9 +460,6 @@ public class Spawn
newlocz = _locZ;
}
// if (npc != null)
// {
// Do not correct z of flying NPCs.
if (!npc.isFlying())
{
@ -513,8 +510,6 @@ public class Spawn
// Increase the current number of NpcInstance managed by this Spawn
_currentCount++;
// }
return npc;
}
@ -572,7 +567,7 @@ public class Spawn
{
if (_doRespawn)
{
oldNpc.refreshID();
// oldNpc.refreshId();
initializeNpcInstance(oldNpc);
}
}

View File

@ -95,7 +95,7 @@ public abstract class ZoneForm
protected static final void dropDebugItem(int id, int x, int y, int z)
{
final ItemInstance item = new ItemInstance(IdFactory.getInstance().getNextId(), 57);
final ItemInstance item = new ItemInstance(IdFactory.getNextId(), 57);
item.setCount(id);
item.spawnMe(x, y, z + 5);

View File

@ -123,7 +123,7 @@ public class CharacterCreate extends GameClientPacket
return;
}
final int objectId = IdFactory.getInstance().getNextId();
final int objectId = IdFactory.getNextId();
newChar = PlayerInstance.create(objectId, template, getClient().getAccountName(), _name, _hairStyle, _hairColor, _face, _sex != 0);
newChar.setCurrentHp(newChar.getMaxHp()); // L2Off like

View File

@ -102,7 +102,7 @@ public class RequestExSetPledgeCrestLarge extends GameClientPacket
final CrestCache crestCache = CrestCache.getInstance();
final int newId = IdFactory.getInstance().getNextId();
final int newId = IdFactory.getNextId();
if (!crestCache.savePledgeCrestLarge(newId, _data))
{

View File

@ -80,7 +80,7 @@ public class RequestSetAllyCrest extends GameClientPacket
final CrestCache crestCache = CrestCache.getInstance();
final int newId = IdFactory.getInstance().getNextId();
final int newId = IdFactory.getNextId();
if (!crestCache.saveAllyCrest(newId, _data))
{

View File

@ -107,7 +107,7 @@ public class RequestSetPledgeCrest extends GameClientPacket
final CrestCache crestCache = CrestCache.getInstance();
final int newId = IdFactory.getInstance().getNextId();
final int newId = IdFactory.getNextId();
if (clan.hasCrest())
{

View File

@ -225,7 +225,7 @@ public class MinionList
final NpcTemplate minionTemplate = NpcTable.getInstance().getTemplate(minionid);
// Create and Init the Minion and generate its Identifier
final MinionInstance monster = new MinionInstance(IdFactory.getInstance().getNextId(), minionTemplate);
final MinionInstance monster = new MinionInstance(IdFactory.getNextId(), minionTemplate);
// Set the Minion HP, MP and Heading
monster.setCurrentHpMp(monster.getMaxHp(), monster.getMaxMp());