New-age Transactional Systems - Not Your Grandpa's OLTP
John Hugg discusses high volume transaction processing applications with high and low frequency profiles, and how VoltDB can be used for that purpose.
The content has been bookmarked!
There was an error bookmarking this content! Please retry.
Posted by Niclas Nilsson on Sep 14, 2007
Most server-side applications and many desktop applications contains data that is tied to a particular task that’s being executed. A common solution is to keep that kind of data in thread-local storage; to keep the data in variables bound to the executing thread. Convenient, but a practice based on a faulty assumption.
Bob Martin wrote an article about the problem of assuming that a unit-of-work has a one-to-one relationship with a thread.
ThreadLocal variables are a wonderfully convenient way to associate data with a given thread. Indeed, frameworks like Hibernate take advantage of this to hold session information. However, the practice depends upon assumption that a thread is equivalent to a unit-of-work. This is a faulty assumption.
ThreadLocal is the Java terminology, but the construct is common in multi-threaded environments. Bob remembers:
Thirteen years ago, while working on my first book, Jim Coplien and I were having a debate on the nature of threads and objects. He made a clarifying statement that has stuck with me since. He said: “An object is an abstraction of function. A thread is an abstraction of schedule.”
Mapping the data of a unit-of-work to one thread is a standard pattern today; a pattern that is found in many popular frameworks, and even though that approach works most of the time, there are situations where the faulty abstraction leaks.
It is not uncommon for a task to have different priorities for different parts of the task, and there are no rules that a task must be single-threaded. Bob exemplifies by saying that a unit-of-work may very well need responsive communication with an external service while performing a relatively long-time computation based upon the incoming data; a problem commonly solved by using two threads. He asks:
Where are the unit-of-work related variables? They can’t be kept in a ThreadLocal since each part of the task runs in a separate thread. They can’t be kept in static variables since there is more than one thread. The answer is that they have to be passed around between the threads as function arguments on the stack, and recorded in the data structured placed on the queue.
TapsaKoo encountered a similar situation a while ago. When trying to work in a domain-driven way in WinForms, he described his problems finding a place to keep session-specific data.
If the application has only one form open at a time, I could save the session-object into the CallContext. What if the application has multiple forms open at a time and each of them wants to have a separate instance of my session-class? CallContext is out of the question. So are all thread-specific alternatives. What is left? Nothing? I’m not the first person pondering this issue. A solution probably exists but I can’t find it. Do I really have to inject the session-object into every object instance that might need it? Or should I refactor a lot behavior from domain-classes into services and inject the session-object into them. I don’t like this approach because I want my classes to be more than data containers.
When reading Uncle Bobs post, TapsaKoo agreed that there are no easy solutions to the problem:
It doesn’t matter if you have 1 or 10 threads. The problem is always the same. UnitOfWork or SessionState should have a place that does not depend on threads. It’s a dangerous assumption that UnitOfWork is directly related to one single thread. That assumption seriously limits your other architectural choices.
Bob concludes that something seems to be missing:
So, though convenient, ThreadLocal variables confuse the issue of separating function from schedule. They tempt us to couple function and schedule together. This is unfortunate since the correspondence of function and schedule is weak and accidental.
What we’d really like is to be able to create UnitOfWorkLocal variables.
Improve Java Garbage Collection, Runtime Execution, and JVM visibility with Zing
Using Drools? See what you're missing! Get the Power of Drools with the Assurance of Red Hat
A practical guide to choosing the right agile tools
Monitor your Production Java App - includes JMX! Low Overhead - Free download
18 agile and lean practices for effective software development governance
While I agree with this point theorically, I don't think multi threads unit of works can be applied practically (in most applications).
If you take transaction management, for example, it is clear that the transaction life must be bound to your unit of work. Problem is, in application servers, JTA transactions (and associated resources as JDBC connections obtained through JNDI lookup) are bound to a particular thread. Same goes for caller information and other useful, infrastructure provided data.
If you were to implement a multi thread unit of work, you'd have to abandon those low level features. It simply seems too much pain for me. I prefer using a logical unit of work (in the use case sense) that spans several technical units of work (in the ORM/tx sense of the term) that can be distributed amongst many thread. Mechanisms as workflows, JMS asynchronism, sync points, ... exist to support this way of programming, and you still can use all the features provided by your application server.
JTA is particularly insidious in this regard (binding work to the current thread). Actually, that seems common in most transactional systems. I even think that's ok as long as you can strip the info off the thread at some point and move it to a different thread.
When I was at MetaMatrix, we used the Atomikos transaction manager and we were able to move transactions between threads (and include sub-transactions on different VMs). But it certainly wasn't pretty and didn't seem to be the way people normally used it.
Indeed, sharing connections and transactions between threads is unusual and unpractical. Also, the transaction schemantics of JTA and Spring - notably, the propagation levels - have clear behavior when it comes to delimiting the association of "unit-of-work" objects with the threads.
There are two approaches I have taken to share context between threads. Both required a pool of threads to share a ThreadGroup.
1) Create a ThreadGroupLocal. This holds a value/values for each ThreadGroup shared between threads in that group.
2) Create a custom ThreadGroup which holds a thread safe Map of values.
Where you have something which is single threaded I associate a single thread pool and a cached (variable sized) pool with the thread group. Single threaded processing requires adding a task the first pool and any which isn't single threaded is added to the second pool.
This is the cut down version. You add sub-tasks to either the single pool or the multi threaded pool. The single threaded pool can kick off any number of tasks concurrently and then collect the results with the Future.get() method. Multi-threaded tasks can add sub-task which must run in the same threaded to the single pool.
This structure is used to run a large number of unrelated tasks at once. (Although the single threaded portions have to wait for each other)
public class MyThreadGroup extends ThreadGroup{
public MyThreadGroup(String name) {
super(name);
}
private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(new MyThreadFactory());
private final ExecutorService multiExecutorService = Executors.newCachedThreadPool(new MyThreadFactory());
private final Map<String, Object> values = new ConcurrentHashMap<String, Object>();
public static <T> Future<T> submitSingle(Callable<T> callable) {
// add code to check in is not in the single threaded executor already.
return getMyThreadGroup().executorService.submit(callable);
}
public static <T> Future<T> submit(Callable<T> callable) {
return getMyThreadGroup().multiExecutorService.submit(callable);
}
public static Object getValue(String key) {
return getMyThreadGroup().values.get(key);
}
public static Object setValue(String key, Object value) {
return getMyThreadGroup().values.put(key, value);
}
private static MyThreadGroup getMyThreadGroup() {
return (MyThreadGroup) Thread.currentThread().getThreadGroup();
}
class MyThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
return new Thread(MyThreadGroup.this, r, getName());
}
}
}
</t></t></t></t></t></t>
In Java EE 5, this disparity has been addressed with the new TransactionSynchronizationRegistry interface. In particular, take a look at the putResource(Object,Object) and getResource(Object) methods.
-Patrick
--
Patrick Linskey
bea.com
JTA is particularly insidious in this regard (binding work to the current thread).
One can suspend() the transaction on one thread and resume() it on another.
Peace,
Cameron Purdy
Oracle Coherence: The Java Data Grid
Probably what you are missing is the idea of fluid variables (called special variables in Common Lisp).
John Hugg discusses high volume transaction processing applications with high and low frequency profiles, and how VoltDB can be used for that purpose.
Kevlin Henney examines code samples to see what can be learned from them starting from the premise that one won’t write great code unless he knows how to read it.
Jason Ayers share the observations he made watching a team of developers collaborating in real time on the same code base, pushing XP, pair programming and continuous integration to their extremes.
Michael Snoyman presents Yesod, a web framework written in Haskell and containing a web server, templating, ORM, libraries (templating, gravatar, etc.).
Richard Kreuter and Kyle Banker on how to avoid classical RDBMS transactional systems by using compensation mechanisms, transactional messaging or transactional procedures.
Attila Szegedi talks about performance tuning Java and Scala programs at Twitter: how to approach GC problems, the importance of asynchronous I/O, when to use MySQL/Cassandra/Redis, and much more.
One category of risk that project teams need to ensure they address is business value failure – delivering a product that fails to provide value for the business investor.
InfoQ spoke to the authors of Software Systems Architecture on a couple of new topics, the System Context viewpoint and Agile, which have been added to the second edition.
7 comments
Watch Thread Reply