← Back to team overview

dhis2-devs team mailing list archive

[Branch ~dhis2-devs-core/dhis2/trunk] Rev 20712: Introduced cache for JEP expression parsing/calculation

 

------------------------------------------------------------
revno: 20712
committer: Lars Helge Overland <larshelge@xxxxxxxxx>
branch nick: dhis2
timestamp: Thu 2015-10-15 10:57:07 +0200
message:
  Introduced cache for JEP expression parsing/calculation
modified:
  dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/util/MathUtils.java


--
lp:dhis2
https://code.launchpad.net/~dhis2-devs-core/dhis2/trunk

Your team DHIS 2 developers is subscribed to branch lp:dhis2.
To unsubscribe from this branch go to https://code.launchpad.net/~dhis2-devs-core/dhis2/trunk/+edit-subscription
=== modified file 'dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/util/MathUtils.java'
--- dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/util/MathUtils.java	2015-10-14 13:33:26 +0000
+++ dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/util/MathUtils.java	2015-10-15 08:57:07 +0000
@@ -33,6 +33,8 @@
 import java.util.List;
 import java.util.Locale;
 import java.util.Random;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
 import java.util.regex.Pattern;
 
 import org.apache.commons.validator.routines.DoubleValidator;
@@ -40,11 +42,23 @@
 import org.hisp.dhis.expression.Operator;
 import org.nfunk.jep.JEP;
 
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+
 /**
  * @author Lars Helge Overland
  */
 public class MathUtils
 {
+    /**
+     * Cache for JEP expression evaluation.
+     */
+    private static Cache<String, Double> EXPR_EVAL_CACHE = CacheBuilder.newBuilder()
+        .expireAfterAccess( 1, TimeUnit.HOURS )
+        .initialCapacity( 200 )
+        .maximumSize( 5000 )
+        .build();
+    
     public static final Double ZERO = new Double( 0 );
     
     private static final Locale LOCALE = new Locale( "en" );
@@ -102,6 +116,18 @@
      */
     public static double calculateExpression( String expression )   
     {
+        try
+        {
+            return EXPR_EVAL_CACHE.get( expression, () -> calculateExpressionInternal( expression ) );
+        }
+        catch ( ExecutionException ex )
+        {
+            throw new RuntimeException( "Expression calculation error", ex );
+        }
+    }
+    
+    private static double calculateExpressionInternal( String expression )
+    {
         final JEP parser = getJep();
         parser.parseExpression( expression );