Search code examples
javajpacachingeclipselink

monitoring elipselink cache L2,L1


Is there a tool or a programmatic method to monitor the level one,two cache of eclipse link. my goal is to know the number of entity cached for a certain class. here some links i found but they are not enough:

http://www.eclipse.org/eclipselink/documentation/2.5/solutions/performance002.htm https://wiki.eclipse.org/EclipseLink/Examples/JPA/Monitoring


Solution

  • JPA doesn't specify such capabilities, however you can do it with EclipseLink internals e.g.:

    L1 (transactional cache, persistence context)

    import org.eclipse.persistence.jpa.JpaEntityManager;
    import org.eclipse.persistence.internal.sessions.UnitOfWorkImpl;
    ...
    JpaEntityManager jem = em.unwrap(JpaEntityManager.class);
    UnitOfWorkImpl ouw = jem.unwrap(UnitOfWorkImpl.class);
    ...
    long count = countCachedEntitiesL1(clazz);
    

    and the corresponding method:

    // Java 7
    public long countCachedEntitiesL1(Class clazz) {
        long count = 0;
        for (Map.Entry<Object, Object> entity : ouw.getCloneMapping().entrySet()) {
            if (entity.getKey().getClass().equals(clazz)) {
                count++;
            }
        }
        return count;
    }
    
    // Java 8
    public long countCachedEntitiesL1(Class clazz) {
        return ouw.getCloneMapping().keySet().stream()
            .filter(entity -> entity.getClass().equals(clazz))
            .count();
    }
    


    L2 (shared cache)

    import org.eclipse.persistence.jpa.JpaEntityManager;
    import org.eclipse.persistence.sessions.server.ServerSession;
    import org.eclipse.persistence.internal.sessions.IdentityMapAccessor;
    ...
    JpaEntityManager jem = em.unwrap(JpaEntityManager.class);
    ServerSession ss = jem.unwrap(ServerSession.class);
    IdentityMapAccessor ima = (IdentityMapAccessor) ss.getIdentityMapAccessor();
    ...
    int count = countCachedEntitiesL2(clazz);
    

    and the corresponding method:

    public int countCachedEntitiesL2(Class clazz) {
        return ima.getIdentityMap(clazz).getSize();
    }