Example usage for org.hibernate.stat SecondLevelCacheStatistics getElementCountInMemory

List of usage examples for org.hibernate.stat SecondLevelCacheStatistics getElementCountInMemory

Introduction

In this page you can find the example usage for org.hibernate.stat SecondLevelCacheStatistics getElementCountInMemory.

Prototype

long getElementCountInMemory();

Source Link

Document

The number of elements currently in memory within the cache provider.

Usage

From source file:com.daphne.es.monitor.web.controller.HibernateCacheMonitorController.java

License:Apache License

private void setMemoryInfo(Model model) {
    ////w  w  w  . j  av a 2  s .  c  o  m
    MemoryUsage heapMemoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    long usedSystemMemory = heapMemoryUsage.getUsed();
    long maxSystemMemory = heapMemoryUsage.getMax();
    model.addAttribute("usedSystemMemory", usedSystemMemory);
    model.addAttribute("maxSystemMemory", maxSystemMemory);

    //
    Statistics statistics = (Statistics) model.asMap().get("statistics");
    String[] secondLevelCacheRegionNames = statistics.getSecondLevelCacheRegionNames();

    int totalMemorySize = 0;
    int totalMemoryCount = 0;
    int totalDiskCount = 0;

    for (String secondLevelCacheRegionName : secondLevelCacheRegionNames) {
        SecondLevelCacheStatistics secondLevelCacheStatistics = statistics
                .getSecondLevelCacheStatistics(secondLevelCacheRegionName);
        totalMemorySize += secondLevelCacheStatistics.getSizeInMemory();
        totalMemoryCount += secondLevelCacheStatistics.getElementCountInMemory();
        totalDiskCount += secondLevelCacheStatistics.getElementCountOnDisk();
    }

    model.addAttribute("totalMemorySize", totalMemorySize);
    model.addAttribute("totalMemoryCount", totalMemoryCount);
    model.addAttribute("totalDiskCount", totalDiskCount);
}

From source file:com.francetelecom.clara.cloud.scalability.helper.StatisticsHelper.java

License:Apache License

private static void secondLevelStats(Statistics stats, String name) {
    logger.info("Second level statistics for " + name);

    SecondLevelCacheStatistics slStats = stats.getSecondLevelCacheStatistics(name);

    logger.info("  Elements in memory : " + slStats.getElementCountInMemory());
    logger.info("  Element on disk : " + slStats.getElementCountOnDisk());
    logger.info("  Entries : " + slStats.getEntries());
    logger.info("  Hit count : " + slStats.getHitCount());
    logger.info("  Miss count : " + slStats.getMissCount());
    logger.info("  Put count : " + slStats.getPutCount());
    logger.info("  Memory size : " + slStats.getSizeInMemory());
}

From source file:com.hazelcast.hibernate.CacheHitMissReadWriteTest.java

License:Open Source License

@Test
public void testUpdateShouldNotInvalidateEntryInCache() {
    insertDummyEntities(10, 4);/*  ww w  . ja v  a  2  s.c om*/
    //all 10 entities and 40 properties are cached
    SecondLevelCacheStatistics dummyEntityCacheStats = sf.getStatistics()
            .getSecondLevelCacheStatistics(CACHE_ENTITY);

    sf.getCache().evictEntityRegions();
    sf.getCache().evictCollectionRegions();

    //miss 10 entities, 10 entities are cached
    getDummyEntities(sf, 10);

    //updates cache entity
    updateDummyEntityName(sf, 2, "updated");

    assertEquals(10, dummyEntityCacheStats.getElementCountInMemory());
}

From source file:com.hibernateinstrumentator.jboss.StatisticsService.java

License:Apache License

@Override
public Map<String, Object> getSecondLevelCacheStatisticsMap(String regionName) {

    Map<String, Object> m = null;
    SecondLevelCacheStatistics slcs = super.getSecondLevelCacheStatistics(regionName);
    if (slcs != null) {
        m = new HashMap<String, Object>();
        m.put("elementCountInMemory", slcs.getElementCountInMemory());
        m.put("elementCountOnDisk", slcs.getElementCountOnDisk());
        m.put("entries", slcs.getEntries());
        m.put("hitCount", slcs.getHitCount());
        m.put("missCount", slcs.getMissCount());
        m.put("putCount", slcs.getPutCount());
        m.put("sizeInMemory", slcs.getSizeInMemory());
    }/* w  w  w .  j a v  a  2 s . co m*/

    return m;
}

From source file:com.openkm.servlet.admin.HibernateStatsServlet.java

License:Open Source License

/**
 * View log//from  ww w  . j av  a  2 s. co  m
 */
private void view(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("view({}, {})", request, response);
    refresh();

    // Query Statistics
    List<Map<String, String>> qStats = new ArrayList<Map<String, String>>();
    for (String query : queryStatistics.keySet()) {
        QueryStatistics queryStats = queryStatistics.get(query);
        Map<String, String> stat = new HashMap<String, String>();
        stat.put("query", query);
        //stat.put("tquery", HibernateUtil.toSql(query));
        stat.put("executionCount", Long.toString(queryStats.getExecutionCount()));
        stat.put("executionRowCount", Long.toString(queryStats.getExecutionRowCount()));
        stat.put("executionMaxTime", Long.toString(queryStats.getExecutionMaxTime()));
        stat.put("executionMinTime", Long.toString(queryStats.getExecutionMinTime()));
        stat.put("executionAvgTime", Long.toString(queryStats.getExecutionAvgTime()));
        stat.put("executionTotalTime",
                Long.toString(queryStats.getExecutionAvgTime() * queryStats.getExecutionCount()));
        stat.put("cacheHitCount", Long.toString(queryStats.getCacheHitCount()));
        stat.put("cacheMissCount", Long.toString(queryStats.getCacheMissCount()));
        stat.put("cachePutCount", Long.toString(queryStats.getCachePutCount()));
        qStats.add(stat);
    }

    // Entity Statistics
    List<Map<String, String>> eStats = new ArrayList<Map<String, String>>();
    for (String entity : entityStatistics.keySet()) {
        EntityStatistics entityStats = entityStatistics.get(entity);
        Map<String, String> stat = new HashMap<String, String>();
        stat.put("entity", entity);
        stat.put("loadCount", Long.toString(entityStats.getLoadCount()));
        stat.put("fetchCount", Long.toString(entityStats.getFetchCount()));
        stat.put("insertCount", Long.toString(entityStats.getInsertCount()));
        stat.put("updateCount", Long.toString(entityStats.getUpdateCount()));
        stat.put("deleteCount", Long.toString(entityStats.getDeleteCount()));
        stat.put("optimisticFailureCount", Long.toString(entityStats.getOptimisticFailureCount()));
        eStats.add(stat);
    }

    // Collection Statistics
    List<Map<String, String>> cStats = new ArrayList<Map<String, String>>();
    for (String collection : collectionStatistics.keySet()) {
        CollectionStatistics collectionStats = collectionStatistics.get(collection);
        Map<String, String> stat = new HashMap<String, String>();
        stat.put("collection", collection);
        stat.put("loadCount", Long.toString(collectionStats.getLoadCount()));
        stat.put("fetchCount", Long.toString(collectionStats.getFetchCount()));
        stat.put("updateCount", Long.toString(collectionStats.getUpdateCount()));
        stat.put("recreateCount", Long.toString(collectionStats.getRecreateCount()));
        stat.put("removeCount", Long.toString(collectionStats.getRemoveCount()));
        cStats.add(stat);
    }

    // 2nd Level Cache Statistics
    long totalSizeInMemory = 0;
    List<Map<String, String>> slcStats = new ArrayList<Map<String, String>>();
    for (String cache : secondLevelCacheStatistics.keySet()) {
        SecondLevelCacheStatistics cacheStats = secondLevelCacheStatistics.get(cache);
        totalSizeInMemory += cacheStats.getSizeInMemory();
        Map<String, String> stat = new HashMap<String, String>();
        stat.put("cache", cache);
        stat.put("putCount", Long.toString(cacheStats.getPutCount()));
        stat.put("hitCount", Long.toString(cacheStats.getHitCount()));
        stat.put("missCount", Long.toString(cacheStats.getMissCount()));
        stat.put("elementCountInMemory", Long.toString(cacheStats.getElementCountInMemory()));
        stat.put("sizeInMemory", Long.toString(cacheStats.getSizeInMemory()));
        stat.put("elementCountOnDisk", Long.toString(cacheStats.getElementCountOnDisk()));
        slcStats.add(stat);
    }

    ServletContext sc = getServletContext();
    sc.setAttribute("generalStats", generalStatistics);
    sc.setAttribute("queryStats", qStats);
    sc.setAttribute("entityStats", eStats);
    sc.setAttribute("collectionStats", cStats);
    sc.setAttribute("secondLevelCacheStats", slcStats);
    sc.setAttribute("totalSizeInMemory", totalSizeInMemory);
    sc.setAttribute("statsEnabled", HibernateUtil.getSessionFactory().getStatistics().isStatisticsEnabled());
    sc.getRequestDispatcher("/admin/hibernate_stats.jsp").forward(request, response);

    // Activity log
    UserActivity.log(request.getRemoteUser(), "ADMIN_HIBERNATE_STATS", null, null, null);

    log.debug("view: void");
}

From source file:net.welen.buzz.typehandler.impl.hibernate.HibernateSecondLevelStatisticsUnitHandler.java

License:Open Source License

public void getValues(BuzzAnswer values) throws TypeHandlerException {
    for (String tmp : getMeasurableUnits()) {
        String name = tmp.split("" + SEPARATOR)[0];
        String region = tmp.split("" + SEPARATOR)[1];

        // Find the Hibernate Session Factory in JNDI
        SessionFactory sessionFactory = null;

        boolean debug = LOG.isDebugEnabled();

        Object o;//from  w  w w.  j  a v a  2s.c o  m
        try {
            if (debug) {
                LOG.debug("Looking up: " + name);
            }
            o = new InitialContext().lookup(name);
        } catch (NamingException e) {
            throw new TypeHandlerException(e);
        }

        if (debug) {
            LOG.debug("Found class: " + o.getClass().getName());
        }
        if (o.getClass().getName().equals("org.hibernate.ejb.EntityManagerFactoryImpl")) {
            // Hibernate 4
            sessionFactory = ((EntityManagerFactoryImpl) o).getSessionFactory();
        } else {
            // Hibernate 3
            sessionFactory = (SessionFactory) o;
        }

        // Get all values for the SecondLevelCacheRegion
        SecondLevelCacheStatistics stats = sessionFactory.getStatistics().getSecondLevelCacheStatistics(region);
        LOG.debug("Got SecondLevelCacheStatistics for region: " + region + " " + stats);
        String measurementUnit = getMeasurementUnit();

        try {
            values.put(measurementUnit, name + SEPARATOR + region, "ElementCountInMemory",
                    stats.getElementCountInMemory());
            values.put(measurementUnit, name + SEPARATOR + region, "ElementCountOnDisk",
                    stats.getElementCountOnDisk());
            values.put(measurementUnit, name + SEPARATOR + region, "HitCount", stats.getHitCount());
            values.put(measurementUnit, name + SEPARATOR + region, "MissCount", stats.getMissCount());
            values.put(measurementUnit, name + SEPARATOR + region, "PutCount", stats.getPutCount());
            values.put(measurementUnit, name + SEPARATOR + region, "SizeInMemory", stats.getSizeInMemory());
        } catch (IncompatibleClassChangeError e) {
            // Newer versions of SecondLevelCacheStatistics is not an Object anymore. It's an interface
            // so we use Reflection in that case (otherwise we need to recompile Buzz for the specific
            // version if Hibernate.
            LOG.debug("SecondLevelCacheStatistics is an Interface. Using Reflection");

            Class<?> statsClass = stats.getClass();
            try {
                values.put(measurementUnit, name + SEPARATOR + region, "ElementCountInMemory",
                        statsClass.getMethod("getElementCountInMemory", (Class<?>) null)
                                .invoke(stats, (Object[]) null).toString());
                values.put(measurementUnit, name + SEPARATOR + region, "ElementCountOnDisk",
                        statsClass.getMethod("getElementCountOnDisk", (Class<?>) null)
                                .invoke(stats, (Object[]) null).toString());
                values.put(measurementUnit, name + SEPARATOR + region, "HitCount", statsClass
                        .getMethod("getHitCount", (Class<?>) null).invoke(stats, (Object[]) null).toString());
                values.put(measurementUnit, name + SEPARATOR + region, "MissCount", statsClass
                        .getMethod("getMissCount", (Class<?>) null).invoke(stats, (Object[]) null).toString());
                values.put(measurementUnit, name + SEPARATOR + region, "PutCount", statsClass
                        .getMethod("getPutCount", (Class<?>) null).invoke(stats, (Object[]) null).toString());
                values.put(measurementUnit, name + SEPARATOR + region, "SizeInMemory",
                        statsClass.getMethod("getSizeInMemory", (Class<?>) null).invoke(stats, (Object[]) null)
                                .toString());
            } catch (SecurityException ex) {
                throw new TypeHandlerException(ex);
            } catch (NoSuchMethodException ex) {
                throw new TypeHandlerException(ex);
            } catch (IllegalArgumentException ex) {
                throw new TypeHandlerException(ex);
            } catch (IllegalAccessException ex) {
                throw new TypeHandlerException(ex);
            } catch (InvocationTargetException ex) {
                throw new TypeHandlerException(ex);
            }
        }
    }
}

From source file:org.apache.ignite.cache.hibernate.GridHibernateL2CacheSelfTest.java

License:Apache License

/**
 * @param accessType Cache access type./*w  ww .ja va  2  s.  co m*/
 * @throws Exception If failed.
 */
private void testVersionedEntity(AccessType accessType) throws Exception {
    createSessionFactories(accessType);

    try {
        Session ses = sesFactory1.openSession();

        VersionedEntity e0 = new VersionedEntity(0);

        try {
            Transaction tx = ses.beginTransaction();

            ses.save(e0);

            tx.commit();
        } finally {
            ses.close();
        }

        ses = sesFactory1.openSession();

        long ver;

        try {
            ver = ((VersionedEntity) ses.load(VersionedEntity.class, 0)).getVersion();
        } finally {
            ses.close();
        }

        SecondLevelCacheStatistics stats1 = sesFactory1.getStatistics()
                .getSecondLevelCacheStatistics(VERSIONED_ENTITY_NAME);
        SecondLevelCacheStatistics stats2 = sesFactory2.getStatistics()
                .getSecondLevelCacheStatistics(VERSIONED_ENTITY_NAME);

        assertEquals(1, stats1.getElementCountInMemory());
        assertEquals(1, stats2.getElementCountInMemory());

        ses = sesFactory2.openSession();

        try {
            assertEquals(ver, ((VersionedEntity) ses.load(VersionedEntity.class, 0)).getVersion());
        } finally {
            ses.close();
        }

        assertEquals(1, stats2.getElementCountInMemory());
        assertEquals(1, stats2.getHitCount());

        if (accessType == AccessType.READ_ONLY)
            return;

        e0.setVersion(ver - 1);

        ses = sesFactory1.openSession();

        Transaction tx = ses.beginTransaction();

        try {
            ses.update(e0);

            tx.commit();

            fail("Commit must fail.");
        } catch (StaleObjectStateException e) {
            log.info("Expected exception: " + e);
        } finally {
            tx.rollback();

            ses.close();
        }

        sesFactory1.getStatistics().clear();

        stats1 = sesFactory1.getStatistics().getSecondLevelCacheStatistics(VERSIONED_ENTITY_NAME);

        ses = sesFactory1.openSession();

        try {
            assertEquals(ver, ((VersionedEntity) ses.load(VersionedEntity.class, 0)).getVersion());
        } finally {
            ses.close();
        }

        assertEquals(1, stats1.getElementCountInMemory());
        assertEquals(1, stats1.getHitCount());
        assertEquals(1, stats2.getElementCountInMemory());
        assertEquals(1, stats2.getHitCount());
    } finally {
        cleanup();
    }
}

From source file:org.apache.ignite.cache.hibernate.GridHibernateL2CacheSelfTest.java

License:Apache License

/**
 * @param accessType Cache access type./*from w  w w.j a  va 2 s  .c o  m*/
 * @throws Exception If failed.
 */
private void testRegionClear(AccessType accessType) throws Exception {
    createSessionFactories(accessType);

    try {
        final int ENTITY_CNT = 100;

        Session ses = sesFactory1.openSession();

        try {
            Transaction tx = ses.beginTransaction();

            for (int i = 0; i < ENTITY_CNT; i++) {
                Entity e = new Entity(i, "name-" + i);

                Collection<ChildEntity> children = new ArrayList<>();

                for (int j = 0; j < 3; j++)
                    children.add(new ChildEntity());

                e.setChildren(children);

                ses.save(e);
            }

            tx.commit();
        } finally {
            ses.close();
        }

        loadEntities(sesFactory2, ENTITY_CNT);

        SecondLevelCacheStatistics stats1 = sesFactory1.getStatistics()
                .getSecondLevelCacheStatistics(ENTITY_NAME);
        SecondLevelCacheStatistics stats2 = sesFactory2.getStatistics()
                .getSecondLevelCacheStatistics(ENTITY_NAME);

        NaturalIdCacheStatistics idStats1 = sesFactory1.getStatistics()
                .getNaturalIdCacheStatistics(NATURAL_ID_REGION);
        NaturalIdCacheStatistics idStats2 = sesFactory2.getStatistics()
                .getNaturalIdCacheStatistics(NATURAL_ID_REGION);

        SecondLevelCacheStatistics colStats1 = sesFactory1.getStatistics()
                .getSecondLevelCacheStatistics(CHILD_COLLECTION_REGION);
        SecondLevelCacheStatistics colStats2 = sesFactory2.getStatistics()
                .getSecondLevelCacheStatistics(CHILD_COLLECTION_REGION);

        assertEquals(ENTITY_CNT, stats1.getElementCountInMemory());
        assertEquals(ENTITY_CNT, stats2.getElementCountInMemory());

        assertEquals(ENTITY_CNT, idStats1.getElementCountInMemory());
        assertEquals(ENTITY_CNT, idStats2.getElementCountInMemory());

        assertEquals(ENTITY_CNT, colStats1.getElementCountInMemory());
        assertEquals(ENTITY_CNT, colStats2.getElementCountInMemory());

        // Test cache is cleared after update query.

        ses = sesFactory1.openSession();

        try {
            Transaction tx = ses.beginTransaction();

            ses.createQuery("delete from " + ENTITY_NAME + " where name='no such name'").executeUpdate();

            ses.createQuery("delete from " + ChildEntity.class.getName() + " where id=-1").executeUpdate();

            tx.commit();
        } finally {
            ses.close();
        }

        assertEquals(0, stats1.getElementCountInMemory());
        assertEquals(0, stats2.getElementCountInMemory());

        assertEquals(0, idStats1.getElementCountInMemory());
        assertEquals(0, idStats2.getElementCountInMemory());

        assertEquals(0, colStats1.getElementCountInMemory());
        assertEquals(0, colStats2.getElementCountInMemory());

        // Load some data in cache.

        loadEntities(sesFactory1, 10);

        assertEquals(10, stats1.getElementCountInMemory());
        assertEquals(10, stats2.getElementCountInMemory());
        assertEquals(10, idStats1.getElementCountInMemory());
        assertEquals(10, idStats2.getElementCountInMemory());

        // Test evictAll method.

        sesFactory2.getCache().evictEntityRegion(ENTITY_NAME);

        assertEquals(0, stats1.getElementCountInMemory());
        assertEquals(0, stats2.getElementCountInMemory());

        sesFactory2.getCache().evictNaturalIdRegion(ENTITY_NAME);

        assertEquals(0, idStats1.getElementCountInMemory());
        assertEquals(0, idStats2.getElementCountInMemory());

        sesFactory2.getCache().evictCollectionRegion(CHILD_COLLECTION_REGION);

        assertEquals(0, colStats1.getElementCountInMemory());
        assertEquals(0, colStats2.getElementCountInMemory());
    } finally {
        cleanup();
    }
}

From source file:org.bedework.calcore.hibernate.DbStatistics.java

License:Apache License

private static void secondLevelStats(Collection<StatsEntry> c, Statistics dbStats, String name) {
    c.add(new StatsEntry("Second level statistics for " + name));

    SecondLevelCacheStatistics slStats = dbStats.getSecondLevelCacheStatistics(name);

    c.add(new StatsEntry("Elements in memory", slStats.getElementCountInMemory()));
    c.add(new StatsEntry("Element on disk", slStats.getElementCountOnDisk()));
    //c.add(new StatsEntry("Entries", slStats.getEntries()));
    c.add(new StatsEntry("Hit count", slStats.getHitCount()));
    c.add(new StatsEntry("Miss count", slStats.getMissCount()));
    c.add(new StatsEntry("Put count", slStats.getPutCount()));
    c.add(new StatsEntry("Memory size", slStats.getSizeInMemory()));
}

From source file:org.firstopen.singularity.util.HibernateUtilImpl.java

License:Apache License

public void printSecondLevelCacheStatistics(Class cachedClass) {

    SecondLevelCacheStatistics slcs = getSessionFactory().getStatistics()
            .getSecondLevelCacheStatistics(cachedClass.getName());
    log.debug("SecondLevelCacheStatistics = " + slcs.getElementCountInMemory());
}