public final void initialize(@NonNull final Realm realm) { Contracts.requireNonNull(realm, "realm == null"); synchronized (_lock$maximumKeys) { if (_initialized) { throw new IllegalStateException(RealmIdGenerator.class + " is already initialized."); } final val maximumKeys = getMaximumKeys(); final val configuration = realm.getConfiguration(); final val realmSchema = realm.getSchema(); for (final val modelClass : configuration.getRealmObjectClasses()) { final val objectSchema = realmSchema.get(modelClass.getSimpleName()); if (objectSchema.hasPrimaryKey()) { final val primaryKeyField = objectSchema.getPrimaryKey(); final val primaryKey = realm.where(modelClass).max(primaryKeyField); final long primaryKeyValue; if (primaryKey != null) { primaryKeyValue = primaryKey.longValue(); } else { primaryKeyValue = 0L; } maximumKeys.put(modelClass, new AtomicLong(primaryKeyValue)); } } _initialized = true; } }