code: @SuppressWarnings("unchecked")
    protected <E> E updateWithOptimisticLockingInternal(E entity, PropertyMetadata versionMetadata) {
      Transaction transaction = null;
      try {
        entityManager.executeEntityListeners(CallbackType.PRE_UPDATE, entity);
        Entity nativeEntity = (Entity) Marshaller.marshal(entityManager, entity, Intent.UPDATE);
        transaction = datastore.newTransaction();
        Entity storedNativeEntity = transaction.get(nativeEntity.getKey());
        if (storedNativeEntity == null) {
          throw new OptimisticLockException(
              String.format("Entity does not exist: %s", nativeEntity.getKey()));
        }
        String versionPropertyName = versionMetadata.getMappedName();
        long version = nativeEntity.getLong(versionPropertyName) - 1;
        long storedVersion = storedNativeEntity.getLong(versionPropertyName);
        if (version != storedVersion) {
          throw new OptimisticLockException(
              String.format("Expecting version %d, but found %d", version, storedVersion));
        }
        transaction.update(nativeEntity);
        transaction.commit();
        E updatedEntity = (E) Unmarshaller.unmarshal(nativeEntity, entity.getClass());
        entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntity);
        return updatedEntity;
      } catch (DatastoreException exp) {
        throw DatastoreUtils.wrap(exp);
      } finally {
        rollbackIfActive(transaction);
      }
    }
docs: Worker method for updating the given entity with optimistic locking.
  
  @param entity
  the entity to update
  @param versionMetadata
  the metadata for optimistic locking
  @return the updated entity