

There’s no black magic behind this connection object. function CreateThreadData: IInterface begin Result := TConnectionPoolData.Create end The magic CreateThreadData factory just creates a connection object (which would in a real program establish a database connection, for example). procedure TfrmConnectionPoolDemo.FormCreate(Sender: TObject) begin FConnectionPool := CreateThreadPool( 'Connection pool') FConnectionPool.ThreadDataFactory := CreateThreadData end procedure TfrmConnectionPoolDemo.FormClose(Sender: TObject var Action: TCloseAction) begin FConnectionPool.CancelAll end FConnectionPool is an interface and its lifetime is managed automatically so we don’t have to do anything explicit with it. In the OnClose event the code terminates all waiting tasks (if any), allowing the application to shutdown gracefully. The latter is a function that will create and initialize new connection for each new thread. In the OnCreate event the code creates a thread pool, assigns it a name and thread data factory. All code was extracted from the demo 24_ConnectionPool. So let’s see how we can code this in the OTL. You can set maximum number of concurrent tasks, idle thread timeout, maximum time the task will wait for execution and more and more. Thread pool will initialize the pool entity (database connection), associate it with a thread and pass it to all tasks that will run in this thread so that they can use it.įurthermore, this solution allows you to use all the functionality of the OTL thread pool. We’ll just create a task and submit it into a thread pool. Threads will be managed by a thread pool and there will be no need for us to create/destroy them. (I had such problem once with TDBIB and Firebird Embedded.) To solve this, we would have to associate entities with threads and we’ll also have to monitor thread lifecycle (to deallocate entities when a thread is terminated). In practice, we can run in a big problem if such entities expect to always run from the thread in which they were created. In a traditional sense, one would build a list of objects managing those entities and would then allocate them to the threads running the code. Let’s say we want to build a pool of some entities that take some time to initialize (database connections, for example). It turned out that implementing thread-global data was not really hard to do so here it is – a tutorial on how to build a connection pool with the OTL (also included in the latest release as a demo 24_ConnectionPool).

The answer, at the time, was – not possible. Recently, an OTL user asked me in the forum how to build a connection pool with the OTL.
