Last active
April 17, 2019 11:42
-
-
Save vkorobkov/7aba6e3c3a2b3bfe7395e5a19c1196e5 to your computer and use it in GitHub Desktop.
Thread-safe singleton version of groovy.sql.Sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ofgroovy.sql.Sql
you don't need to change much.