Skip to content

Instantly share code, notes, and snippets.

@vkorobkov
Last active April 17, 2019 11:42
Show Gist options
  • Save vkorobkov/7aba6e3c3a2b3bfe7395e5a19c1196e5 to your computer and use it in GitHub Desktop.
Save vkorobkov/7aba6e3c3a2b3bfe7395e5a19c1196e5 to your computer and use it in GitHub Desktop.
Thread-safe singleton version of groovy.sql.Sql
import groovy.sql.Sql
import javax.sql.DataSource
class ThreadSafeSql extends Sql implements GroovyInterceptable {
private final ThreadLocal<Sql> threadLocal = new ThreadLocal<>()
private final DataSource dataSource
ThreadSafeSql(DataSource dataSource) {
super(dataSource)
this.dataSource = dataSource
}
def invokeMethod(String name, Object args) {
def sql = threadLocal.get()
if (!sql) {
sql = new Sql(dataSource)
threadLocal.set(sql)
}
sql.invokeMethod(name, args)
}
}
@vkorobkov
Copy link
Author

vkorobkov commented Sep 28, 2016

Instantiate ThreadSafeSql only once and then use it in any thread of your application thread pools - you'll get the profit of thread local in full! Since this is a subclass of groovy.sql.Sql you don't need to change much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment