<?xml version="1.0" encoding="UTF-8" standalone="no"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><description>Groovy programming tips and tricks. Subscribe to this blog, make the switch from Java to Groovy and get more productive!</description><title>Groovy Programming</title><generator>Tumblr (3.0; @groovy-programming-blog)</generator><link>https://groovy-programming.com/</link><xhtml:meta content="noindex" name="robots" xmlns:xhtml="http://www.w3.org/1999/xhtml"/><item><title>The Ternary Operator in Groovy</title><description>&lt;p&gt;The Ternary Operator is a shortcut for the following code:&lt;/p&gt;
&lt;pre&gt;
if (A) {
    B
}
else {
    C
}
&lt;/pre&gt;
&lt;p&gt;The Ternary Operator reduces this code down to&lt;/p&gt;
&lt;pre&gt;
A ? B : C
&lt;/pre&gt;
&lt;p&gt;As you can see, the Ternary Operator operates on three expressions, contrary to the &lt;a href="https://groovy-programming.com/post/507845186"&gt;Elvis operator&lt;/a&gt; that operates on two.&lt;/p&gt;
&lt;h2&gt;When to use the Ternary Operator&lt;/h2&gt;
&lt;p&gt;I like to use the Ternary Operator in cases where A, B and C are reasonably small expressions. Keep in mind that readability is a big concern for software projects long-term and that &lt;em&gt;some&lt;/em&gt; verbosity may be better than byte-saving techniques.&lt;/p&gt;
&lt;h2&gt;Ternary Operator Examples in Groovy&lt;/h2&gt;
&lt;p&gt;The following examples are taken from the &lt;a href="https://github.com/johannburkard/eproxy"&gt;eproxy&lt;/a&gt; project.&lt;/p&gt;
&lt;pre&gt;
….setSharedCache(OnGoogleAppEngineOrDevserver.CONDITION ? true : cacheIsShared)
&lt;/pre&gt;
&lt;p&gt;This forces the &lt;code&gt;sharedCache&lt;/code&gt; property to always be &lt;code&gt;true&lt;/code&gt; on Google App Engine.&lt;/p&gt;
&lt;pre&gt;
long end = m.group(2) ? m.group(2) as long : contentLength
&lt;/pre&gt;
&lt;p&gt;This is converting &lt;code&gt;m.group(2)&lt;/code&gt; to a &lt;code&gt;long&lt;/code&gt; if the value is &lt;em&gt;truthy&lt;/em&gt; and defaults to &lt;code&gt;contentLength&lt;/code&gt; otherwise.&lt;/p&gt;</description><link>https://groovy-programming.com/post/175536037619</link><guid>https://groovy-programming.com/post/175536037619</guid><pubDate>Wed, 04 Jul 2018 11:38:42 +0200</pubDate><category>groovy</category><category>operator</category><category>operators</category><category>ternary</category></item><item><title>Still alive</title><description>&lt;p&gt;After eight years of not posting anything to this blog, I’ll be posting new code snippets from past projects in the coming days.&lt;/p&gt;&lt;p&gt;They’ll be Groovy, I promise.&lt;br/&gt;&lt;/p&gt;</description><link>https://groovy-programming.com/post/175520557494</link><guid>https://groovy-programming.com/post/175520557494</guid><pubDate>Wed, 04 Jul 2018 00:43:16 +0200</pubDate><category>announcement</category></item><item><title>Groovy String Concatenation</title><description>&lt;p&gt;I&amp;rsquo;m trying to come up with as many ways to concatenate strings as possible.&lt;/p&gt;&lt;h2&gt;Plus&lt;/h2&gt;&lt;pre&gt;String s = 'foo' + 'bar'&lt;/pre&gt;&lt;h2&gt;Left Shift Operator&lt;/h2&gt;&lt;pre&gt;String s = ('foo' &amp;lt;&amp;lt; 'bar') as String // The Left Shift Operator returns a StringBuffer.&lt;/pre&gt;&lt;h2&gt;Array join&lt;/h2&gt;&lt;pre&gt;String s = [ 'foo', 'bar' ].join('')&lt;/pre&gt;&lt;h2&gt;String#concat&lt;/h2&gt;&lt;pre&gt;String s = 'foo'.concat('bar')&lt;/pre&gt;&lt;h2&gt;Inject&lt;/h2&gt;&lt;pre&gt;[ 'foo', 'bar' ].inject(new StringBuffer(), { a, b -&amp;gt; a.append(b); return a }).toString()&lt;/pre&gt;&lt;h2&gt;&lt;a href="http://groovy-programming.com/post/16069789641"&gt;With!&lt;/a&gt;&lt;/h2&gt;&lt;pre&gt;new StringBuilder().with { append('foo'); append('bar') }.toString()&lt;/pre&gt;</description><link>https://groovy-programming.com/post/137973068159</link><guid>https://groovy-programming.com/post/137973068159</guid><pubDate>Sun, 24 Jan 2016 22:22:07 +0100</pubDate><category>groovy</category><category>string</category><category>strings</category><category>programming</category></item><item><title>Automatic service layer performance tracking to Google Analytics</title><description>&lt;p&gt;After publishing the &lt;a href="/post/118804818009"&gt;Google Analytics Measurement Protocol server-side client &lt;/a&gt;(!) &lt;a href="http://eaio.com/?utm_source=tumblr&amp;amp;utm_medium=social&amp;amp;utm_term=124073490409&amp;amp;utm_campaign=groovy-programming"&gt;EAIO&lt;/a&gt; uses to send performance data to Google Analytics, here is the code that intercepts Spring’s service layer using Groovy’s &lt;code&gt;Interceptor&lt;/code&gt; feature and tracks the timing of some  method calls.&lt;/p&gt;&lt;p&gt;This code by default intercepts method calls on classes annotated with &lt;code&gt;@Component&lt;/code&gt;, &lt;code&gt;@Service&lt;/code&gt; and &lt;code&gt;@Repository&lt;/code&gt;.&lt;/p&gt;&lt;p&gt;In Google Analytics, automatic alerts for various method calls can then be set up. For example, I receive an email once the &lt;code&gt;ClientService#getClient(long)&lt;/code&gt; method takes longer than 20 ms on average per day.&lt;/p&gt;&lt;p&gt;The first class is the &lt;code&gt;MethodTimingBeanPostProcessor&lt;/code&gt;. This class iterates over all Spring beans annotated with the annotations above that extend &lt;code&gt;GroovyObject&lt;/code&gt; (necessary for the meta-programming interception).&lt;/p&gt;
&lt;pre&gt;
package com.eaio.util.performance;

import groovy.lang.GroovyObject;
import groovy.lang.ProxyMetaClass;

import java.beans.IntrospectionException;

import org.springframework.beans.BeanInstantiationException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import com.eaio.googleanalytics.GoogleAnalyticsService;
import com.eaio.util.googleappengine.OnGoogleAppEngine;

/**
 * Groovy metaprogramming-based interception for {@link Service} instances.
 *
 * @author &amp;lt;a href="mailto:johann@johannburkard.de"&amp;gt;Johann Burkard&amp;lt;/a&amp;gt;
 * @version $Id: MethodTimingBeanPostProcessor.java 7035 2015-04-21 19:29:43Z johann $
 */
@Component
@Conditional(OnGoogleAppEngine.class)
public class MethodTimingBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization(java.lang.Object, java.lang.String)
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    /**
     * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization(java.lang.Object, java.lang.String)
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (beanQualifiesForGoogleAnalyticsTimingInterception(bean) &amp;amp;&amp;amp; beanIsNotGoogleAnalyticsService(bean)) {
            GoogleAnalyticsTimingInterceptor interceptor = applicationContext.getBean(GoogleAnalyticsTimingInterceptor.class);
            try {
                ProxyMetaClass proxiedDAO = ProxyMetaClass.getInstance(bean.getClass());
                proxiedDAO.setInterceptor(interceptor);
                ((GroovyObject) bean).setMetaClass(proxiedDAO);
            }
            catch (IntrospectionException e) {
                throw new BeanInstantiationException(bean.getClass(), e.getLocalizedMessage(), e);
            }
        }
        return bean;
    }

    /**
     * Prevents infinite loops.
     */
    boolean beanIsNotGoogleAnalyticsService(Object bean) {
        return !(bean instanceof GoogleAnalyticsService);
    }

    /**
     * Selects beans whose classes have a {@link Service}, {@link Component} or {@link Repository} annotation and implement {@link GroovyObject}.
     */
    boolean beanQualifiesForGoogleAnalyticsTimingInterception(Object bean) {
        return (bean.getClass().isAnnotationPresent(Service.class) ||
                bean.getClass().isAnnotationPresent(Component.class) ||
                bean.getClass().isAnnotationPresent(Repository.class)) &amp;amp;&amp;amp; bean instanceof GroovyObject;
    }

}
&lt;/pre&gt;
&lt;p&gt;The next class is the &lt;code&gt;GoogleAnalyticsTimingInterceptor&lt;/code&gt;. This Interceptor implementation uses a &lt;code&gt;ThreadLocal&lt;/code&gt; to store commons-lang3′s &lt;code&gt;StopWatch&lt;/code&gt; instances in. The &lt;code&gt;StopWatch&lt;/code&gt; is wrapped in a custom data structure called &lt;code&gt;StackSlot&lt;/code&gt; that manages borrows and returns of the &lt;code&gt;StopWatch&lt;/code&gt; instance. This prevents any method calls between services from distorting method timings.&lt;/p&gt;
&lt;pre&gt;
package com.eaio.util.performance;

import groovy.lang.Interceptor;

import org.apache.commons.lang3.time.StopWatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;

import com.eaio.googleanalytics.GoogleAnalyticsService;
import com.eaio.util.StackSlot;
import com.eaio.util.googleappengine.OnGoogleAppEngine;

/**
 * Thread-safe {@link Interceptor} that tracks timing to {@link GoogleAnalyticsService}.
 *
 * @author &amp;lt;a href="mailto:johann@johannburkard.de"&amp;gt;Johann Burkard&amp;lt;/a&amp;gt;
 * @version $Id: GoogleAnalyticsTimingInterceptor.java 7444 2015-06-14 12:52:53Z johann $
 */
@Component
@Conditional(OnGoogleAppEngine.class)
public class GoogleAnalyticsTimingInterceptor implements Interceptor {

    @Autowired
    private GoogleAnalyticsService googleAnalyticsService;

    private ThreadLocal&amp;lt;StackSlot&amp;lt;StopWatch&amp;gt;&amp;gt; stopWatches = new ThreadLocal&amp;lt;StackSlot&amp;lt;StopWatch&amp;gt;&amp;gt;() {

        @Override
        protected StackSlot&amp;lt;StopWatch&amp;gt; initialValue() {
            return new StackSlot&amp;lt;StopWatch&amp;gt;(new StopWatch());
        }

    };

    /**
     * @see groovy.lang.Interceptor#beforeInvoke(java.lang.Object, java.lang.String, java.lang.Object[])
     */
    @Override
    public Object beforeInvoke(Object object, String methodName, Object[] arguments) {
        StopWatch watch = stopWatches.get().increment();
        if (watch != null &amp;amp;&amp;amp; !watch.isStarted()) {
            watch.start();
        }
        return null;
    }

    /**
     * @see groovy.lang.Interceptor#afterInvoke(java.lang.Object, java.lang.String, java.lang.Object[], java.lang.Object)
     */
    @Override
    public Object afterInvoke(Object object, String methodName, Object[] arguments, Object result) {
        StopWatch watch = stopWatches.get().decrement();
        if (watch != null &amp;amp;&amp;amp; watch.isStarted()) {
            int time = (int) watch.getTime();
            watch.reset();
            googleAnalyticsService.trackTiming(object.getClass().getSimpleName(), methodName, time);
        }
        return result;
    }

    /**
     * @see groovy.lang.Interceptor#doInvoke()
     */
    @Override
    public boolean doInvoke() {
        return true;
    }

}
&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;StackSlot&lt;/code&gt; class is little more than an object and a counter that is incremented and decremented. The object is only returned when the counter is 0.&lt;/p&gt;
&lt;pre&gt;
package com.eaio.util;

/**
 * &amp;lt;em&amp;gt;Single-threaded&amp;lt;/em&amp;gt; ADT that returns an Object only if an internal counter is 0. {@link #increment()} attempts to acquire the object and
 * increases the counter. {@link #decrement()} attempts to acquire the object and decreases the counter.
 * &amp;lt;p&amp;gt;
 * The number of increments and decrements must be symmetrical for obvious reasons.
 *
 * @author &amp;lt;a href="mailto:johann@johannburkard.de"&amp;gt;Johann Burkard&amp;lt;/a&amp;gt;
 * @version $Id: StackSlot.java 7411 2015-06-10 20:46:03Z johann $
 */
public class StackSlot&amp;lt;T&amp;gt; {
    
    private int counter = 0;
    
    private final T t;
    
    public StackSlot(T t) {
        this.t = t;
    }
    
    public T increment() {
        return counter++ == 0 ? t : null; 
    }
    
    public T decrement() {
        return --counter == 0 ? t : null;
    }
    
}
&lt;/pre&gt;
&lt;p&gt;As with the &lt;code&gt;GoogleAnalyticsService&lt;/code&gt;, the com.eaio:grabbag:2.5 (or greater) dependency from &lt;code&gt;&lt;a href="http://repo.eaio.com/maven2"&gt;http://repo.eaio.com/maven2&lt;/a&gt;&lt;/code&gt; is required for the &lt;code&gt;OnGoogleAppEngine&lt;/code&gt; conditional class. If this code is used somewhere else, this conditional can of course be removed.&lt;/p&gt;&lt;p&gt;With the &lt;code&gt;GoogleAnalyticsService&lt;/code&gt; configured, you should see service-level method call performance in Google Analytics automatically.&lt;/p&gt;</description><link>https://groovy-programming.com/post/124073490409</link><guid>https://groovy-programming.com/post/124073490409</guid><pubDate>Tue, 14 Jul 2015 17:36:15 +0200</pubDate><category>google analytics</category><category>groovy</category><category>spring</category><category>service</category><category>layer</category><category>performance</category><category>tracking</category><category>track</category></item><item><title>Google Analytics Measurement Protocol in Groovy</title><description>&lt;p&gt;In the last two years that I didn’t blog here, I wrote a lot of code that I migrated into my latest project, &lt;a href="http://eaio.com/?utm_source=tumblr&amp;amp;utm_medium=social&amp;amp;utm_term=118804818009&amp;amp;utm_campaign=groovy-programming"&gt;EAIO&lt;/a&gt;. Some of that code will be released here.&lt;/p&gt;&lt;p&gt;After &lt;a href="https://github.com/johannburkard/tinymeasurement"&gt;tinymeasurement&lt;/a&gt;, a JavaScript client for the measurement protocol, here is an implementation of the &lt;a href="https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters"&gt;Measurement Protocol&lt;/a&gt; in Groovy.&lt;/p&gt;&lt;p&gt;This class was designed to be used with Spring Boot on Google App Engine. It is not using &lt;a href="https://hc.apache.org/httpcomponents-client-ga/index.html"&gt;HttpClient&lt;/a&gt; but rather &lt;a href="http://docs.groovy-lang.org/latest/html/groovy-jdk/java/net/URL.html#getText(java.util.Map)"&gt;URL#getText(Map)&lt;/a&gt; because one can’t connect to Google Services using the Socket API (which is what HttpClient uses).&lt;/p&gt;&lt;p&gt;Apart from Spring Boot, the dependencies of this class are commons-lang and com.eaio:grabbag:2.5 (or greater) &amp;ndash; grabbag primarily for the OnGoogleAppEngine Conditional that prevents unit tests or local testing from sending data to Google Analytics.&lt;/p&gt;&lt;p&gt;In application.properties, the following keys are required:&lt;/p&gt;&lt;pre&gt;http.userAgent=${project.name}/${build}

#
# Google Analytics
#

googleanalytics.propertyID=UA-.......-..
googleanalytics.hostName=xxx.xxx
googleanalytics.siteSpeedSampleRate=0.02
# Socket and read timeout
googleanalytics.timeoutInMs=150&lt;/pre&gt;
&lt;p&gt;The timeout values are set low for a reason I&amp;rsquo;ll outline in a later post.&lt;/p&gt;
&lt;p&gt;In Spring, a &lt;a href="https://docs.oracle.com/javase/7/docs/api/java/util/Random.html"&gt;Random&lt;/a&gt; instance needs to be set up, preferably a &lt;a href="https://docs.oracle.com/javase/7/docs/api/java/security/SecureRandom.html"&gt;SecureRandom&lt;/a&gt;.&lt;/p&gt;
&lt;pre&gt;
package com.eaio.googleanalytics

import static java.util.Collections.*
import static org.apache.commons.lang3.StringUtils.*
import groovy.transform.CompileStatic
import groovy.transform.PackageScope
import groovy.util.logging.Slf4j

import org.apache.commons.lang3.exception.ExceptionUtils
import org.apache.commons.lang3.text.StrBuilder
import org.apache.commons.lang3.time.StopWatch
import org.springframework.beans.factory.InitializingBean
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Conditional
import org.springframework.stereotype.Service
import org.springframework.web.util.UriComponentsBuilder

import com.eaio.util.googleappengine.OnGoogleAppEngine

/**
 * Pings back some data to Google Analytics to track eaio usage. Only enabled on GAE.
 *
 * @author &amp;lt;a href="mailto:johann@johannburkard.de"&amp;gt;Johann Burkard&amp;lt;/a&amp;gt;
 * @version $Id: GoogleAnalyticsService.groovy 7670 2015-09-20 13:00:36Z johann $
 */
@Conditional(OnGoogleAppEngine)
@CompileStatic
@Service
@Slf4j
class GoogleAnalyticsService implements InitializingBean {

    @Value('${http.userAgent}')
    String userAgent
    
    @Value('${googleanalytics.propertyID}')
    String propertyID
    
    @Value('${googleanalytics.hostName}')
    String hostName
    
    /**
     * Ranges between 0 to 1.
     */
    @Value('${googleanalytics.siteSpeedSampleRate}')
    Double siteSpeedSampleRate
    
    @Value('${googleanalytics.timeoutInMs}')
    Integer timeoutInMs

    @Autowired
    Random random
    
    private Map&amp;lt;String, Object&amp;gt; defaultParams

    @Lazy
    private URI googleAnalyticsCollect = 'http://www.google-analytics.com/collect'.toURI()

    /**
     * Calling this method tracks an &amp;lt;tt&amp;gt;/init&amp;lt;/tt&amp;gt; pageview.
     */
    @Override
    void afterPropertiesSet() {
        defaultParams = (Map&amp;lt;String, Object&amp;gt;) [ v: 1I, tid: propertyID, dh: hostName, cid: UUID.randomUUID(), aip: 1 ]
        trackPageview('/start')
    }

    void trackPageview(String path, Map&amp;lt;String, Object&amp;gt; params = null) {
        track(((Map&amp;lt;String, Object&amp;gt;) [ t: 'pageview', dp: abbreviate(path, 2048I) ]) + (params ?: EMPTY_MAP))
    }

    void trackEvent(String category, String action, String label = null, Integer value = null, Map&amp;lt;String, Object&amp;gt; params = null) {
        track(((Map&amp;lt;String, Object&amp;gt;) [ t: 'event', ec: abbreviate(category, 150I), ea: abbreviate(action, 500I), el: abbreviate(label, 500I), ev: value ]) + (params ?: EMPTY_MAP))
    }

    void trackTiming(String category, String variable, int time, String label = null, Map&amp;lt;String, Object&amp;gt; params = null) {
        if (time &amp;gt;= 0I &amp;amp;&amp;amp; time &amp;lt; 3600000I &amp;amp;&amp;amp; (!siteSpeedSampleRate || random.nextDouble() &amp;lt;= siteSpeedSampleRate)) {
            track(((Map&amp;lt;String, Object&amp;gt;) [ t: 'timing', utc: abbreviate(category, 150I), utv: abbreviate(variable, 500I), utt: time, utl: abbreviate(label, 500I) ]) + (params ?: EMPTY_MAP))
        }
    }

    void trackException(String category, Throwable thrw, String label, Map&amp;lt;String, Object&amp;gt; params = null) {
        StrBuilder builder = new StrBuilder(4096I)
        thrw.printStackTrace(new PrintWriter(builder.asWriter()))
        trackEvent(category, minifyStack(builder as String), label, null, params)
    }
    
    def trackTiming(String category, String variable, String label = null, Map&amp;lt;String, Object&amp;gt; params = null, Closure c) {
        StopWatch watch = new StopWatch()
        watch.start()
        def out
        try {
            out = c()
        }
        finally {
            trackTiming(category, variable, (int) watch.time, label, params)
        }
        out
    }
    
    @PackageScope
    String minifyStack(String stack) {
        (stack ?: '').replaceAll('\\s*[\r\n]\\s*at\\s*', ' &amp;gt; ').replaceAll('(?:\\w+\\.)+([A-Z][\\w$]*\\s)', '$1').replaceAll('(?:\\w+\\.)+([A-Z][\\w$]*\\.[^(]+)\\([^)]+\\)', '$1')
    }

    /**
     * Uses {@link HttpURLConnection} because you cannot reach Google services with the socket API from within Google App Engine.
     */
    void track(Map&amp;lt;String, Object&amp;gt; params) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromUri(googleAnalyticsCollect)
        
        (defaultParams + params).findAll { it.value != null &amp;amp;&amp;amp; it.value != '' }.each {
            builder.queryParam(it.key, it.value)
        }
        
        URI target = builder.build().toUri()

        StopWatch watch = new StopWatch()
        watch.start()
        try {
            target.toURL().getText([ connectTimeout: timeoutInMs, readTimeout: timeoutInMs, requestProperties: [ 'User-Agent': userAgent ]])

            log.info('request to {} on {} took {} ms', googleAnalyticsCollect, googleAnalyticsCollect.host, watch.time)
        }
        catch (IOException e) {
            log.info('could not send {} to Google Analytics in {} ms: {}', target, watch.time, ExceptionUtils.getRootCauseMessage(e))
        }
    }

}
&lt;/pre&gt;</description><link>https://groovy-programming.com/post/118804818009</link><guid>https://groovy-programming.com/post/118804818009</guid><pubDate>Tue, 12 May 2015 22:34:06 +0200</pubDate><category>groovy</category><category>google app engine</category><category>gae</category><category>spring</category><category>boot</category></item><item><title>Creating a truly scalable Thread Pool with ThreadPoolExecutor</title><description>&lt;p&gt;Doug Lea’s &lt;a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html"&gt;&lt;code&gt;ThreadPoolExecutor&lt;/code&gt;&lt;/a&gt; is a very useful part of the &lt;code&gt;java.util.concurrent&lt;/code&gt; library. It implements a configurable thread pool that is easy to use and control.&lt;/p&gt;
&lt;p&gt;Thread pools are used to move work that might take longer to complete away from the main application, as well as constraining how much of this work can be done in parallel with the application.&lt;/p&gt;
&lt;p&gt;However, when used with an &lt;em&gt;unbounded&lt;/em&gt; queue, you will find that &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; never allocates more than one thread, even when higher maximum pool sizes are allowed.&lt;/p&gt;
&lt;p&gt;The problem is caused by this code block:&lt;/p&gt;
&lt;pre&gt;        if (poolSize &amp;gt;= corePoolSize || !addIfUnderCorePoolSize(command)) {
            if (runState == RUNNING &amp;amp;&amp;amp; &lt;strong&gt;workQueue.offer(command)&lt;/strong&gt;) {
                if (runState != RUNNING || poolSize == 0)
                    ensureQueuedTaskHandled(command);
            }
            else if (!addIfUnderMaximumPoolSize(command))
                reject(command); // is shutdown or saturated
        }
&lt;/pre&gt;
&lt;p&gt;You can see that &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; delegates the decision whether to add an additional thread to the pool to the &lt;code&gt;workQueue&lt;/code&gt;. This queue however doesn’t know about the &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; containing it and, since it’s unbounded, will always accept a new object.&lt;/p&gt;
&lt;p&gt;In other words, it is impossible to set up &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; so that the number of threads scales up and down dynamically.&lt;/p&gt;
&lt;h2&gt;Making ThreadPoolExecutor truly scalable&lt;/h2&gt;
&lt;p&gt;To create a &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; instance that scales the number of threads up and down, the &lt;code&gt;BlockingQueue&lt;/code&gt; needs to have a reference to the &lt;code&gt;ThreadPoolExecutor&lt;/code&gt; and needs to delegate method calls to &lt;a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html#offer%28E%29"&gt;&lt;code&gt;offer&lt;/code&gt;&lt;/a&gt; to an underlying &lt;code&gt;BlockingQueue&lt;/code&gt; only if the current thread pool size is equal to the &lt;code&gt;ThreadPoolExecutor&lt;/code&gt;’s maximum pool size.&lt;/p&gt;
&lt;p&gt;In all other cases, the &lt;code&gt;BlockingQueue&lt;/code&gt; should return &lt;code&gt;false&lt;/code&gt; to indicate that a new thread should be added to the pool.&lt;/p&gt;
&lt;h2&gt;A Groovy solution&lt;/h2&gt;
&lt;p&gt;Groovy makes it particularly easy to implement such a queue class. By using the @Delegate annotation, delegating code is generated at compile-time and only overriding methods need to be implemented.&lt;/p&gt;
&lt;p&gt;Also, the &lt;a href="http://groovy-programming.com/post/23298032023"&gt;@TupleConstructor&lt;/a&gt; and @Synchronized annotations reduce code bloat and make writing thread-safe code easier.&lt;/p&gt;
&lt;pre&gt;@TupleConstructor
class DynamicBlockingQueue&amp;lt;E&amp;gt; {
    
    @Delegate
    BlockingQueue&amp;lt;E&amp;gt; queue
    
    ThreadPoolExecutor executor

    @Synchronized
    boolean offer(def e) {
        !executor || executor.poolSize == executor.maximumPoolSize ?
            queue.offer(e) : false
    }

}
&lt;/pre&gt;
&lt;p&gt;Use this class like this:&lt;/p&gt;
&lt;pre&gt;LinkedBlockingQueue&amp;lt;Runnable&amp;gt; delegate =
    new LinkedBlockingQueue&amp;lt;Runnable&amp;gt;()
DynamicBlockingQueue queue = new DynamicBlockingQueue(queue: delegate)
ThreadPoolExecutor executor =
    new ThreadPoolExecutor(0, 42 /* maximum number of threads */,
    10, TimeUnit.SECONDS, queue)
queue.executor = executor

// Use your ThreadPoolExecutor
&lt;/pre&gt;
&lt;h2&gt;Maven Users&lt;/h2&gt;
&lt;p&gt;For everybody using Maven, my grabbag project already includes the class above. Add a dependency to Groovy 1.8.0 or greater, this artifact…&lt;/p&gt;
&lt;pre&gt;		&amp;lt;dependency&amp;gt;
			&amp;lt;groupId&amp;gt;com.eaio&amp;lt;/groupId&amp;gt;
			&amp;lt;artifactId&amp;gt;grabbag&amp;lt;/artifactId&amp;gt;
			&amp;lt;version&amp;gt;1.6.2&amp;lt;/version&amp;gt;
		&amp;lt;/dependency&amp;gt;
&lt;/pre&gt;
&lt;p&gt;… and use the &lt;code&gt;com.eaio.concurrent.DynamicBlockingQueue&lt;/code&gt; class.&lt;/p&gt;</description><link>https://groovy-programming.com/post/26923146865</link><guid>https://groovy-programming.com/post/26923146865</guid><pubDate>Tue, 10 Jul 2012 22:01:31 +0200</pubDate><category>groovy</category><category>thread</category><category>threads</category><category>threading</category><category>scalable</category><category>scalability</category><category>threadpoolexecutor</category><category>threadpool</category><category>thread pool</category></item><item><title>Groovy annotations: @TupleConstructor</title><description>&lt;p&gt;If you use an inversion-of-control/dependency injection container like &lt;a href="http://picocontainer.org/"&gt;PicoContainer&lt;/a&gt; that favors constructor injection, you might have classes that look like this:&lt;/p&gt;
&lt;pre&gt;class Foo {

 Guh guh

 Keks keks

 Blorb blorb

 Foo(Guh guh, Keks keks, Blorb blorb) {
  this.guh = guh
  this.keks = keks
  this.blorb = blorb
 }

}
&lt;/pre&gt;
&lt;p&gt;Notice the constructor only sets fields? Why should you have to write this glue code yourself?&lt;/p&gt;
&lt;p&gt;Fortunately, since 1.8.0, Groovy has a &lt;a href="http://groovy.codehaus.org/gapi/groovy/transform/TupleConstructor.html"&gt;&lt;code&gt;@TupleConstructor&lt;/code&gt;&lt;/a&gt; annotation that removes the need for a constructor.&lt;/p&gt;
&lt;pre&gt;@TupleConstructor
class Foo {

 Guh guh

 Keks keks

 Blorb blorb

}
&lt;/pre&gt;
&lt;p&gt;Behind the scenes, Groovy will add an empty constructor, as well as &lt;code&gt;n&lt;/code&gt; new constructors, where n is the number of fields in the class. For the Foo class above, Groovy would add&lt;/p&gt;
&lt;pre&gt;class Foo {

 Foo() {}
 Foo(Guh guh) { … }
 Foo(Guh guh, Keks keks) { … }
 Foo(Guh guh, Keks keks, Blorb blorb) { … }

}
&lt;/pre&gt;
&lt;p&gt;So, the next time you come across constructors that merely set some fields, replace them with &lt;code&gt;@TupleConstructor&lt;/code&gt;.&lt;/p&gt;</description><link>https://groovy-programming.com/post/23298032023</link><guid>https://groovy-programming.com/post/23298032023</guid><pubDate>Fri, 18 May 2012 19:44:47 +0200</pubDate><category>groovy</category><category>annotation</category><category>constructor</category><category>dependency injection</category><category>ioc</category><category>inversion-of-control</category></item><item><title>Copy Properties or how to Clone a Class to a different Class</title><description>&lt;p&gt;&lt;a href="http://twitter.com/#!/renescheibe"&gt;René&lt;/a&gt; has asked me how to copy properties/fields of an instance of one class to an instance of another class. I.e. you have&lt;/p&gt;
&lt;pre&gt;class A {
    int a
}&lt;/pre&gt;
&lt;p&gt;and&lt;/p&gt;
&lt;pre&gt;class B {
    int a
}&lt;/pre&gt;
&lt;p&gt;where B obviously does not extend A. You want to copy all properties of an instance of A to an instance of B.&lt;/p&gt;
&lt;h2&gt;Copy Properties&lt;/h2&gt;
&lt;p&gt;The solution is to access the &lt;code&gt;properties&lt;/code&gt; property of A, filter it to remove the &lt;code&gt;class&lt;/code&gt; and &lt;code&gt;metaClass&lt;/code&gt; fields (which can&amp;rsquo;t be copied) and then use the &lt;a href="http://groovy.codehaus.org/api/groovy/lang/GroovyObject.html#setProperty%28java.lang.String,%20java.lang.Object%29"&gt;&lt;code&gt;GroovyObject#setProperty&lt;/code&gt;&lt;/a&gt; method on an instance of B.&lt;/p&gt;
&lt;pre&gt;class Copy {
	
	static GroovyObject copy(GroovyObject from, GroovyObject to) {
		from?.properties?.findAll { !(it.key =~ ~/(meta)?[cC]lass/) }?.each {
			try {
				to.setProperty(it.key, from[it.key])
			}
			catch (MissingPropertyException ex) {}
		}
		to
	}
	
	static &amp;lt;T&amp;gt; T copy(GroovyObject from, Class&amp;lt;T&amp;gt; to) {
		copy(from, to.newInstance())
	}

}
&lt;/pre&gt;
&lt;h2&gt;Clone a Class to a different Class&lt;/h2&gt;
&lt;p&gt;The code also lets you instantiate classes which is useful in case you want to clone an instance of A down its class hierarchy.&lt;/p&gt;
&lt;pre&gt;class A {
    int a
}

class C extends A {
 int foo
}
&lt;/pre&gt;
&lt;p&gt;Calling&lt;/p&gt;
&lt;pre&gt;A someA = new A(a: 42)
C someC = use (Copy) { someA.copy(C) }
&lt;/pre&gt;
&lt;p&gt;will give you a clone of A that is of type C.&lt;/p&gt;</description><link>https://groovy-programming.com/post/17161894018</link><guid>https://groovy-programming.com/post/17161894018</guid><pubDate>Mon, 06 Feb 2012 19:48:24 +0100</pubDate><category>class</category><category>cloning</category><category>clone</category><category>properties</category><category>property</category><category>field</category><category>fields</category><category>instance</category></item><item><title>Groovy programming with... with</title><description>&lt;p&gt;The &lt;a href="http://groovy.codehaus.org/groovy-jdk/java/lang/Object.html#with(groovy.lang.Closure)"&gt;&lt;code&gt;with&lt;/code&gt; method&lt;/a&gt;, which is added to all objects by Groovy, “allows the closure to be called for the object reference self.”&lt;/p&gt;
&lt;p&gt;This sounds a bit complicated so here are some easy use cases for &lt;code&gt;with&lt;/code&gt;:&lt;/p&gt;
&lt;h2&gt;Setting fields&lt;/h2&gt;
&lt;p&gt;Many APIs force you to do endless &lt;code&gt;obj.setSomething(something)&lt;/code&gt; calls. In Groovy, …&lt;/p&gt;
&lt;pre&gt;keks.setFoo(someFoo);
keks.setRolf(copter);
keks.setFnuh(guh);
&lt;/pre&gt;
&lt;p&gt;… becomes…&lt;/p&gt;
&lt;pre&gt;keks.with {
 foo = someFoo
 rolf = copter
 fnuh = guh
}
&lt;/pre&gt;
&lt;p&gt;PROTIP: This works great with the JEE &lt;code&gt;HttpServletRequest&lt;/code&gt; and &lt;code&gt;HttpServletResponse&lt;/code&gt; classes.&lt;/p&gt;
&lt;h2&gt;Removing temporary variables&lt;/h2&gt;
&lt;p&gt;Conditional blocks in which you access another property of the same object can look like this&lt;/p&gt;
&lt;pre&gt;if (new File('rofl').exists()) {
 assert new File('rofl').length() &amp;gt; 0;
}
&lt;/pre&gt;
&lt;p&gt;or you might be tempted to use a temporary variable&lt;/p&gt;
&lt;pre&gt;File f = new File('rofl');
if (f.exists()) {
 assert f.length() &amp;gt; 0;
}
&lt;/pre&gt;
&lt;p&gt;neither of which conveys that it’s all about the file. Groovy makes this easier and more readable:&lt;/p&gt;
&lt;pre&gt;new File('rofl').with {
 if (exists()) {
  assert length() &amp;gt; 0
 }
}
&lt;/pre&gt;
&lt;h2&gt;Harmonizing API access&lt;/h2&gt;
&lt;p&gt;By going with &lt;code&gt;with&lt;/code&gt;, you can turn any API, wether it’s fluent or setter-based into one simple, easy-to-read style.&lt;/p&gt;</description><link>https://groovy-programming.com/post/16069789641</link><guid>https://groovy-programming.com/post/16069789641</guid><pubDate>Wed, 18 Jan 2012 19:46:07 +0100</pubDate><category>groovy</category><category>with</category><category>method</category><category>clean</category><category>cleaner</category><category>code</category></item><item><title>Cleaner logging with Log4j, Commons Logging and java.util.logging</title><description>&lt;p&gt;Logging frameworks are the Java programmer&amp;rsquo;s finger exercise &amp;ndash; think content management systems for PHP programmers.&lt;/p&gt;
&lt;p&gt;Most libraries these days use either Log4j or commons-logging, which is fine because &lt;a href="http://slf4j.org"&gt;SLF4J&lt;/a&gt; can replace commons-logging and redirect output from classes using either API to Log4j.&lt;/p&gt;
&lt;p&gt;Problems only arise when the odd library uses the java.util.logging log framework. Not only is it initialized globally, it also can&amp;rsquo;t be replaced on the classpath because of its location in java.*. And its output is ugly.&lt;/p&gt;
&lt;p&gt;With the public interest in Log4j, commons-logging and java.util.logging something like 100 : 10 : 0.5 (source: AdWords), not even Sun using the JDK for leverage can turn a mediocre also-ran product into a winner.&lt;/p&gt;
&lt;p&gt;This means that java.util.logging must go. Thankfully, there&amp;rsquo;s a SLF4JBridgeHandler in SLF4J, but how to replace java.util.logging loggers with the SLF4JBridgeHandler?&lt;/p&gt;
&lt;pre&gt;import java.util.logging.LogManager
import java.util.logging.Logger

import org.slf4j.bridge.SLF4JBridgeHandler

class KillJavaUtilLogging {

    static {
        Logger log = LogManager.logManager.getLogger('')
        while (log.parent) {
            log = log.parent
        }
        log.with {
            handlers.each { removeHandler(it) }
            addHandler(new SLF4JBridgeHandler())
        }
    }

}
&lt;/pre&gt;
&lt;p&gt;Now, simply mentioning KillJavaUtilLogging will redirect all java.util.logging output into SLF4J where it is logged using Log4j (or commons-logging, if you want).&lt;/p&gt;
&lt;pre&gt;class BlobFilter implements Filter {
    
    {
        KillJavaUtilLogging
    }
}
&lt;/pre&gt;
&lt;p&gt;The corresponding Maven POM dependencies might look like this:&lt;/p&gt;
&lt;pre&gt;		&amp;lt;dependency&amp;gt;
			&amp;lt;groupId&amp;gt;log4j&amp;lt;/groupId&amp;gt;
			&amp;lt;artifactId&amp;gt;log4j&amp;lt;/artifactId&amp;gt;
			&amp;lt;version&amp;gt;1.2.16&amp;lt;/version&amp;gt;
		&amp;lt;/dependency&amp;gt;
		&amp;lt;dependency&amp;gt;
			&amp;lt;groupId&amp;gt;org.slf4j&amp;lt;/groupId&amp;gt;
			&amp;lt;artifactId&amp;gt;slf4j-log4j12&amp;lt;/artifactId&amp;gt;
			&amp;lt;version&amp;gt;1.6.2&amp;lt;/version&amp;gt;
		&amp;lt;/dependency&amp;gt;
		&amp;lt;dependency&amp;gt;
			&amp;lt;groupId&amp;gt;org.slf4j&amp;lt;/groupId&amp;gt;
			&amp;lt;artifactId&amp;gt;jcl-over-slf4j&amp;lt;/artifactId&amp;gt;
			&amp;lt;version&amp;gt;1.6.2&amp;lt;/version&amp;gt;
		&amp;lt;/dependency&amp;gt;
		&amp;lt;dependency&amp;gt;
			&amp;lt;groupId&amp;gt;org.slf4j&amp;lt;/groupId&amp;gt;
			&amp;lt;artifactId&amp;gt;jul-to-slf4j&amp;lt;/artifactId&amp;gt;
			&amp;lt;version&amp;gt;1.6.2&amp;lt;/version&amp;gt;
		&amp;lt;/dependency&amp;gt;
&lt;/pre&gt;</description><link>https://groovy-programming.com/post/10983645751</link><guid>https://groovy-programming.com/post/10983645751</guid><pubDate>Mon, 03 Oct 2011 19:10:32 +0200</pubDate><category>java</category><category>integration</category><category>logging</category><category>logger</category><category>log</category><category>log4j</category><category>commons</category><category>apache</category><category>commons-logging</category><category>clogging</category><category>java.util.logging</category><category>jul</category><category>maven</category><category>pom</category><category>pom.xml</category></item><item><title>CodeNarc for Eclipse released</title><description>&lt;p&gt;My friend &lt;a href="http://twitter.com/#!/renescheibe"&gt;René&lt;/a&gt; has released &lt;a href="http://codenarceclipse.sourceforge.net/"&gt;CodeNarc for Eclipse&lt;/a&gt; which integrates &lt;a href="http://codenarc.sourceforge.net/"&gt;CodeNarc&lt;/a&gt; into Eclipse.&lt;/p&gt;
&lt;p&gt;CodeNarc tries to find errors and potential problems in Groovy code. The &lt;a href="http://codenarc.sourceforge.net/codenarc-rules-basic.html"&gt;list of code checks&lt;/a&gt; is already quite large and covers a lot more than the basics (for example bitwise OR instead of boolean OR).&lt;/p&gt;
&lt;p&gt;If you find yourself writing more Groovy and less Java, it might make sense to expand  static analysis to dynamic code, just as it is normally done for Java with tools like PMD, CheckStyle or FindBugs.&lt;/p&gt;
&lt;p&gt;The Eclipse update sites are&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;&lt;a href="http://codenarceclipse.sourceforge.net/eclipse/release/"&gt;http://codenarceclipse.sourceforge.net/eclipse/release/&lt;/a&gt; for release builds&lt;/li&gt;
&lt;li&gt;&lt;a href="http://codenarceclipse.sourceforge.net/eclipse/snapshot/"&gt;http://codenarceclipse.sourceforge.net/eclipse/snapshot/&lt;/a&gt; for snapshot builds&lt;/li&gt;
&lt;/ul&gt;</description><link>https://groovy-programming.com/post/8965805542</link><guid>https://groovy-programming.com/post/8965805542</guid><pubDate>Mon, 15 Aug 2011 23:15:27 +0200</pubDate><category>static analysis</category><category>groovy</category><category>eclipse</category><category>plugin</category><category>plugins</category></item><item><title>Groovy operators: The spread operator is null-safe</title><description>&lt;p&gt;Groovy&amp;rsquo;s spread operator lets you collect a property of objects from a collection. Here&amp;rsquo;s an example:&lt;/p&gt;
&lt;pre&gt;[ 1, 2, 3 ]*.toString() == [ '1', '2', '3' ]&lt;/pre&gt;
&lt;p&gt;This is identical but shorter than calling&lt;/p&gt;
&lt;pre&gt;[ 1, 2, 3 ].collect { it.toString() }&lt;/pre&gt;
&lt;p&gt;Keep in mind that, just like &lt;code&gt;.collect&lt;/code&gt;, the spread operator is null-safe, i.E. both of these work without throwing any exceptions:&lt;/p&gt;
&lt;pre&gt;null*.toString()
[ 1, null, 3 ]*.toString()
&lt;/pre&gt;</description><link>https://groovy-programming.com/post/6899630959</link><guid>https://groovy-programming.com/post/6899630959</guid><pubDate>Sat, 25 Jun 2011 13:18:10 +0200</pubDate><category>spread</category><category>spread operator</category><category>operator</category><category>operators</category><category>groovy</category><category>null</category><category>null-safe</category></item><item><title>Performance of four methods of concatenating Strings...</title><description>&lt;img src="https://64.media.tumblr.com/tumblr_lllqixhqIf1qbau5mo1_500.png"/&gt;&lt;br/&gt;&lt;br/&gt;&lt;h1&gt;Performance of four methods of concatenating Strings together&lt;/h1&gt;
&lt;ul&gt;&lt;li&gt;plus: &lt;code&gt;a + a&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;.concat: &lt;code&gt;a.concat(b)&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;GString: &lt;code&gt;"${a}${b}".toString()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;left shift: &lt;code&gt;a &lt;&lt; b&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;.concat is the fastest method in all cases. If you’d like a more groovy version, &lt;code&gt;a &lt;&lt; b&lt;/code&gt; is faster than &lt;code&gt;a + b&lt;/code&gt;.&lt;/p&gt;</description><link>https://groovy-programming.com/post/5732276432</link><guid>https://groovy-programming.com/post/5732276432</guid><pubDate>Sun, 22 May 2011 16:49:45 +0200</pubDate><category>groovy</category><category>string</category><category>strings</category><category>performance</category><category>gstring</category><category>concat</category><category>leftShift</category></item><item><title>Java hangs when converting 2.2250738585072012e-308 -- prevent DOS attacks with Groovy</title><description>&lt;p&gt;&lt;a href="http://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/"&gt;The big news now&lt;/a&gt; is that&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Java — both its runtime and compiler — go into an infinite loop when converting the decimal number 2.2250738585072012e-308 to double-precision binary floating-point.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;This has a big impact on web applications since many of them use the &lt;code&gt;java.lang.Double#parseDouble(String)&lt;/code&gt; method with data input by the user.&lt;/p&gt;
&lt;p&gt;While I’m sure most programmers are aware of SQL injection, this is a new threat since user input is usually handled only with &lt;code&gt;try { double foo = Double.parseDouble(input); } catch (NumberFormatException ex) { /* Flip it and reverse it */ }&lt;/code&gt; which does not protect against the denial-of-service attack with the value mentioned above.&lt;/p&gt;
&lt;h2&gt;A Groovy Solution&lt;/h2&gt;
&lt;p&gt;Fortunately, Groovy makes it easy to protect yourself from this attack. A simple regular expression that tests for &lt;code&gt;/[eE]-\d*30\d/&lt;/code&gt; is all it takes.&lt;/p&gt;
&lt;p&gt;Here is an example of my &lt;a href="http://pearsoncorrelation.com"&gt;Pearson Correlation Calculator&lt;/a&gt;:&lt;/p&gt;
&lt;h3&gt;Vulnerable Code&lt;/h3&gt;
&lt;pre&gt;def calculateFromTwoColumns(String x, String y) {

    def xTokens = (x ?: '').tokenize(defaultSeparator)
    def yTokens = (y ?: '').tokenize(defaultSeparator)

    correlation(xTokens.collect { it as double }, yTokens.collect { it as double })

}&lt;/pre&gt;
&lt;h3&gt;Safe Code&lt;/h3&gt;
&lt;pre&gt;def calculateFromTwoColumns(String x, String y) {

    def xTokens = (x ?: '').tokenize(defaultSeparator).
        findAll { !(it =~ /[eE]-\d*30\d/).find() }
    def yTokens = (y ?: '').tokenize(defaultSeparator).
        findAll { !(it =~ /[eE]-\d*30\d/).find() }

    correlation(xTokens.collect { it as double }, yTokens.collect { it as double })

}&lt;/pre&gt;
&lt;p&gt;This will protect against all the values mentioned in the article, such as 0.00022250738585072012e-304, 00000000002.2250738585072012e-308, 2.225073858507201200000e-308, 2.2250738585072012e-00308, 2.2250738585072012997800001e-308.&lt;/p&gt;</description><link>https://groovy-programming.com/post/3072661748</link><guid>https://groovy-programming.com/post/3072661748</guid><pubDate>Wed, 02 Feb 2011 21:26:00 +0100</pubDate><category>dos</category><category>attack</category><category>denial of service</category><category>java</category><category>double</category><category>as double</category><category>toDouble</category><category>parseDouble</category></item><item><title>Count Words in Groovy</title><description>&lt;p&gt;This is a little snippet to show you how to get the word count of a text in Groovy.&lt;/p&gt;
&lt;pre&gt;def text = '''
right about now, the funk soul brother.
check it out now, the funk soul brother.
'''
int words = text
    .collect { it.charAt(0).digit || it.charAt(0).letter ? it : ' ' }
    .join('').tokenize(' ').size()
&lt;/pre&gt;</description><link>https://groovy-programming.com/post/981557418</link><guid>https://groovy-programming.com/post/981557418</guid><pubDate>Fri, 20 Aug 2010 10:24:48 +0200</pubDate><category>word</category><category>words</category><category>count</category><category>counting</category><category>groovy</category><category>snippet</category></item><item><title>Long number arithmetic problematic in Groovy</title><description>&lt;p&gt;When you divide &lt;code&gt;long&lt;/code&gt; numbers in Groovy, you are calling a recursive algorithm that only terminates once an Exception is thrown (&lt;code&gt;org.codehaus.groovy.runtime.typehandling.BigDecimalMath#normalize(BigDecimal)&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;This is not a good thing because with Groovy&amp;rsquo;s inflated call stacks, it means that, for every long division, the entire stack is cloned. And that&amp;rsquo;s costing CPU cycles and memory.&lt;/p&gt;
&lt;h2&gt;Problem&lt;/h2&gt;
&lt;pre&gt;long a = 100
long b = 10
double d = a / b
&lt;/pre&gt;
&lt;p&gt;Will cause an Exception to be thrown.&lt;/p&gt;
&lt;h2&gt;Solution&lt;/h2&gt;
&lt;pre&gt;long a = 100
long b = 10
double d = (double) a / b
&lt;/pre&gt;
&lt;p&gt;Will not cause an Exception to be thrown and will be faster in your average “container” environment.&lt;/p&gt;
&lt;h2&gt;Background&lt;/h2&gt;
&lt;p&gt;I noticed this when I was profiling &lt;a href="http://media.io"&gt;media.io&lt;/a&gt; in &lt;a href="http://yourkit.com"&gt;YourKit&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;When you write &lt;a href="http://pastebin.com/RYNuafRe"&gt;a simple test case&lt;/a&gt;, the numbers are very similar, but when you get stacks that are 30 or more stack elements deep, long division will become slower than double division:&lt;/p&gt;
&lt;pre&gt;Warming up, this could take 5 s or so
long: 1791
double: 2004
long (deep): 2138
&lt;/pre&gt;</description><link>https://groovy-programming.com/post/683498414</link><guid>https://groovy-programming.com/post/683498414</guid><pubDate>Thu, 10 Jun 2010 14:29:38 +0200</pubDate><category>groovy</category><category>arithmeticexception</category><category>number</category><category>long</category><category>exception</category><category>slow</category><category>slowdown</category><category>optimization</category><category>numbers</category><category>division</category><category>divide</category></item><item><title>"Groovy creates BigDecimal numbers deliberately. […] 3.5 is a BigDecimal, whereas 3.5f is a..."</title><description>“Groovy creates BigDecimal numbers deliberately. […] 3.5 is a BigDecimal, whereas 3.5f is a float or 3.5d is a double. Also, when creating variables, if you say double constant = 3.14, you’ll get the a double, although def constant = 3.14 will give you a BigDecimal.”&lt;br/&gt;&lt;br/&gt; - &lt;em&gt;Comment by Guillaume Laforge on &lt;a href="http://weblogs.java.net/blog/forax/archive/2010/05/24/jvm-language-developpers-your-house-burning#comment-14874"&gt;JVM Language developpers: Your house is burning&lt;/a&gt;.&lt;/em&gt;</description><link>https://groovy-programming.com/post/631803276</link><guid>https://groovy-programming.com/post/631803276</guid><pubDate>Tue, 25 May 2010 19:49:00 +0200</pubDate><category>number</category><category>double</category><category>bigdecimal</category><category>literal</category><category>performance</category><category>optimization</category></item><item><title>foo.class or foo.getClass()? Which one to use?</title><description>&lt;p&gt;Groovy converts calls to &lt;code&gt;foo.x&lt;/code&gt; to &lt;code&gt;foo.getX()&lt;/code&gt; – that’s common perception.&lt;/p&gt;
&lt;p&gt;Now, you might be tempted to write &lt;code&gt;foo.class&lt;/code&gt; to access the object’s class.&lt;/p&gt;
&lt;p&gt;But when you do that, sometimes &lt;code&gt;null&lt;/code&gt; is returned, depending on how much Groovy and Java there is in your project.&lt;/p&gt;
&lt;h2&gt;The reason&lt;/h2&gt;
&lt;p&gt;For Groovy objects – which is any class generated from a file with a &lt;code&gt;.groovy&lt;/code&gt; extension –, &lt;code&gt;foo.class&lt;/code&gt; will be mapped to &lt;code&gt;foo.getProperty('class')&lt;/code&gt; which is (most likely) null.&lt;/p&gt;
&lt;p&gt;In other words, &lt;code&gt;foo.class&lt;/code&gt; works for Java objects but probably not for Groovy objects, which is why you should use &lt;code&gt;foo.getClass()&lt;/code&gt;.&lt;/p&gt;</description><link>https://groovy-programming.com/post/624854643</link><guid>https://groovy-programming.com/post/624854643</guid><pubDate>Sun, 23 May 2010 14:36:13 +0200</pubDate><category>class</category><category>getclass</category><category>java</category><category>groovy</category><category>hybrid</category><category>error</category><category>errors</category><category>trap</category></item><item><title>Three good reasons for Groovy</title><description>&lt;ol&gt;&lt;li&gt;
&lt;h2&gt;It’s easy to learn&lt;/h2&gt;
&lt;p&gt;If you know Java, you know Groovy. You start by getting rid of boilerplate code such as casts, getters and setters and the &lt;code&gt;public&lt;/code&gt; keyword. And semicolons. Then, you replace tedious loops with &lt;code&gt;any&lt;/code&gt;, &lt;code&gt;each&lt;/code&gt;, &lt;a href="http://groovy-programming.com/post/516574575"&gt;&lt;code&gt;find&lt;/code&gt;&lt;/a&gt; and &lt;code&gt;findAll&lt;/code&gt;. &lt;a href="http://groovy-programming.com/post/507845186"&gt;Groovy’s operators&lt;/a&gt; and &lt;a href="http://groovy-programming.com/post/506426634"&gt;metaprogramming&lt;/a&gt; might come next.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;h2&gt;Wide syntactic range&lt;/h2&gt;
&lt;p&gt;A while ago, I converted a Ruby script to Groovy and, while the Groovy version was a few characters shorter (thanks to the built-in &lt;a href="http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html#sum()"&gt;sum method&lt;/a&gt;), it looked 99 % like the original Ruby script.&lt;/p&gt;
&lt;p&gt;When I was writing mostly Java, I thought it was designed to make everybody’s code look the same.&lt;/p&gt;
&lt;p&gt;I know now that Java doesn’t stop anyone from writing bad or unintelligible code so there’s no benefit of a language that always looks the same.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;h2&gt;Killer productivity hacks&lt;/h2&gt;
&lt;p&gt;It’s easy to increase your productivity if all you know is Java. Groovy has its fair share of &lt;a href="http://groovy-programming.com/post/516574575"&gt;ways to make coding easier&lt;/a&gt;, but I assume every language has that these days, so let me show you something else.&lt;/p&gt;
&lt;p&gt;If you mistype a method name, Groovy suggests possible methods:&lt;/p&gt;
&lt;pre&gt;groovy.lang.MissingPropertyException:
No such property: stdErr for class: fnuh.Guh
Possible solutions: stderr, stdOut
&lt;/pre&gt;
&lt;p&gt;That’s smarter than necessary and you can find it at many places in Groovy.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;</description><link>https://groovy-programming.com/post/604773263</link><guid>https://groovy-programming.com/post/604773263</guid><pubDate>Sun, 16 May 2010 23:02:53 +0200</pubDate><category>groovy</category><category>language</category><category>design</category><category>java</category><category>comparison</category><category>benefit</category><category>benefits</category></item><item><title>as Groovy as it can go!</title><description>&lt;p&gt;“&lt;code&gt;as&lt;/code&gt;” is one of the wonderful little things in Groovy.&lt;/p&gt;
&lt;p&gt;Instead of boring you with what it is, I searched my workspace for my uses of “&lt;code&gt;as&lt;/code&gt;” and let the examples talk instead.&lt;/p&gt;
&lt;h2&gt;Closures and &lt;code&gt;as&lt;/code&gt; as a Replacement for Anonymous Inner Classes&lt;/h2&gt;
&lt;pre&gt;def nullIOFileFilter = { true } as IOFileFilter
&lt;/pre&gt;
&lt;p&gt;What it does: Creates a &lt;a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Proxy.html"&gt;Proxy&lt;/a&gt; that implements &lt;a href="http://commons.apache.org/io/api-release/org/apache/commons/io/filefilter/IOFileFilter.html"&gt;IOFileFilter&lt;/a&gt; (from commons-io) with every method call on the proxy being delegated to the closures (which always returns &lt;code&gt;true&lt;/code&gt;). There are many interfaces with one or two methods in Java and this makes it effortless.&lt;/p&gt;
&lt;p&gt;The same in Java:&lt;/p&gt;
&lt;pre&gt;IOFileFilter filter = new IOFileFilter() {

    public boolean accept(File file) {
        return true;
    }

    public boolean accept(File dir, String name) {
        return true;
    }

};
&lt;/pre&gt;
&lt;h2&gt;&lt;code&gt;as&lt;/code&gt; for automatic Array Conversion&lt;/h2&gt;
&lt;pre&gt;['fnuh', 42, 'guh'] as String[]&lt;/pre&gt;
&lt;p&gt;What it does: Converts the list into a String array. This does more than just calling &lt;a href="http://java.sun.com/javase/6/docs/api/java/util/List.html#toArray()"&gt;List#toArray()&lt;/a&gt; because 42 clearly isn&amp;rsquo;t a String but is converted to one.&lt;/p&gt;
&lt;p&gt;The same in Java:&lt;/p&gt;
&lt;pre&gt;String[] stringArray = new String[something.size()];
for (int i = 0; i &amp;lt; something.size(); ++i) {
    Object o = something.get(i);
    stringArray[i] = o instanceof String ? o : o.toString();
}
&lt;/pre&gt;
&lt;p&gt;Sorry, Java.&lt;/p&gt;
&lt;h2&gt;&lt;code&gt;as&lt;/code&gt; for String-to-Character Conversion&lt;/h2&gt;
&lt;pre&gt;'%' as char&lt;/pre&gt;
&lt;p&gt;What it does: Takes the first character of the String and returns it as &lt;code&gt;char&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;The desperate Pseudo Object&lt;/h2&gt;
&lt;pre&gt;{} as Configuration&lt;/pre&gt;
&lt;p&gt;What it does: Creates an object that implements Configuration but doesn&amp;rsquo;t do anything. Useful in those cases where there are null checks in place but the object doesn&amp;rsquo;t need to do anything. I touched this before in &lt;a href="http://groovy-programming.com/post/506426634"&gt;Dynamic Proxies with Metaprogramming&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Type Conversion&lt;/h2&gt;
&lt;pre&gt;foo(bla.keks as int, doStuff() as String)&lt;/pre&gt;
&lt;p&gt;What it does: Converts values to primitives and to Strings.&lt;/p&gt;</description><link>https://groovy-programming.com/post/538285066</link><guid>https://groovy-programming.com/post/538285066</guid><pubDate>Wed, 21 Apr 2010 15:48:00 +0200</pubDate><category>as</category><category>operator</category><category>operators</category><category>groovy</category><category>type</category><category>types</category><category>conversion</category><category>convert</category></item></channel></rss>