473,395 Members | 1,977 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Integrate a Queue with an ObjectPool

I would like to have a limited pool of objects (the objects are expensive to
create) that can be enlisted to process items in a queue. Moreover, I
would like to be able to have the processing (time-consuming) occur on a
background thread.

I have two questions:
* what is a good way to block the queue loop while it waits for a free
worker?
* is my approach a reasonable one?

Thanks,

Craig Buchanan

Here's my psedo-code:

Sub ProcessQueue

Do While Queue.Count 0

'wait for next available worker
Worker = ObjectPool.getFreeWorker()

'assign next item in the queue to the worker
Worker.Item = Queue.Dequeue

'run time-consuming process in background
ThreadPool.QueueUserWorkItem(AddressOf ProcessItem, Worker)

Loop

End Sub

Sub ProcessItem(State As Object)

Dim WorkerAs Worker= CType(State,Worker)

Try

'process item
Worker.Process()

Catch ex As Exception

'return item to queue
Queue.Enqueue(Worker.Item)

Finally

'return worker to pool
ObjectPool.returnWorker(Worker)

End Try

End Sub
Mar 27 '07 #1
10 1384
I've written this code more times than I can count, so I hope it's a decent
pattern to follow.

One of these days soon, I'll post my ObjectPool<Tclasses to my blog, along
with some instructions on how to use them. This problem seems to come up
very frequently when writing server applications - we've got dozens of
"expensive" object pools that we maintain. Everything from AD & LDAP
connections, to pinned byte[] buffers for use in reading & writing to
Sockets (to avoid heap fragmentation).

It's got a nice robust mechanism for checking objects in & out of the pool
(using IDisposable so that 'using' blocks can be employed, and also using
Object Resurrection so that the Finalizer is run, the expensive object
doesn't get lost) and its very easy to use.

You wait problem, as you've described it, I usually see it solved with the
Monitor.Pulse / PulseAll pattern. Worker threads are kept blocked in a
Monitor, and when data is added to the queue, the Monitor is Pulsed
realeasing one of the waiting threads. You've got to be carefull of race
conditions, but it's a very well worn pattern.

--
Chris Mullins, MCSD.NET, MCPD:Enterprise, Microsoft C# MVP
http://www.coversant.com/blogs/cmullins

"Craig Buchanan" <so*****@somewhere.comwrote in message
news:%2****************@TK2MSFTNGP03.phx.gbl...
>I would like to have a limited pool of objects (the objects are expensive
to create) that can be enlisted to process items in a queue. Moreover, I
would like to be able to have the processing (time-consuming) occur on a
background thread.

I have two questions:
* what is a good way to block the queue loop while it waits for a free
worker?
* is my approach a reasonable one?

Thanks,

Craig Buchanan

Here's my psedo-code:

Sub ProcessQueue

Do While Queue.Count 0

'wait for next available worker
Worker = ObjectPool.getFreeWorker()

'assign next item in the queue to the worker
Worker.Item = Queue.Dequeue

'run time-consuming process in background
ThreadPool.QueueUserWorkItem(AddressOf ProcessItem, Worker)

Loop

End Sub

Sub ProcessItem(State As Object)

Dim WorkerAs Worker= CType(State,Worker)

Try

'process item
Worker.Process()

Catch ex As Exception

'return item to queue
Queue.Enqueue(Worker.Item)

Finally

'return worker to pool
ObjectPool.returnWorker(Worker)

End Try

End Sub

Mar 27 '07 #2
Chris-

Thanks for the reply. Does your approach also use the ThreadPool to process
the long-running job?

Any chance I could see the code? craig dot buchanan at cogniza dot com. is
this your blog: http://instructors.cwrl.utexas.edu/jesson/?q=blog/61 ?

Thanks,

Craig

"Chris Mullins [MVP]" <cm******@yahoo.comwrote in message
news:es****************@TK2MSFTNGP03.phx.gbl...
I've written this code more times than I can count, so I hope it's a
decent pattern to follow.

One of these days soon, I'll post my ObjectPool<Tclasses to my blog,
along with some instructions on how to use them. This problem seems to
come up very frequently when writing server applications - we've got
dozens of "expensive" object pools that we maintain. Everything from AD &
LDAP connections, to pinned byte[] buffers for use in reading & writing to
Sockets (to avoid heap fragmentation).

It's got a nice robust mechanism for checking objects in & out of the pool
(using IDisposable so that 'using' blocks can be employed, and also using
Object Resurrection so that the Finalizer is run, the expensive object
doesn't get lost) and its very easy to use.

You wait problem, as you've described it, I usually see it solved with the
Monitor.Pulse / PulseAll pattern. Worker threads are kept blocked in a
Monitor, and when data is added to the queue, the Monitor is Pulsed
realeasing one of the waiting threads. You've got to be carefull of race
conditions, but it's a very well worn pattern.

--
Chris Mullins, MCSD.NET, MCPD:Enterprise, Microsoft C# MVP
http://www.coversant.com/blogs/cmullins

"Craig Buchanan" <so*****@somewhere.comwrote in message
news:%2****************@TK2MSFTNGP03.phx.gbl...
>>I would like to have a limited pool of objects (the objects are expensive
to create) that can be enlisted to process items in a queue. Moreover, I
would like to be able to have the processing (time-consuming) occur on a
background thread.

I have two questions:
* what is a good way to block the queue loop while it waits for a free
worker?
* is my approach a reasonable one?

Thanks,

Craig Buchanan

Here's my psedo-code:

Sub ProcessQueue

Do While Queue.Count 0

'wait for next available worker
Worker = ObjectPool.getFreeWorker()

'assign next item in the queue to the worker
Worker.Item = Queue.Dequeue

'run time-consuming process in background
ThreadPool.QueueUserWorkItem(AddressOf ProcessItem, Worker)

Loop

End Sub

Sub ProcessItem(State As Object)

Dim WorkerAs Worker= CType(State,Worker)

Try

'process item
Worker.Process()

Catch ex As Exception

'return item to queue
Queue.Enqueue(Worker.Item)

Finally

'return worker to pool
ObjectPool.returnWorker(Worker)

End Try

End Sub


Mar 28 '07 #3
Chris-

I'm wondering if it would make sense for the ObjectPool to drive the process
of 'draining' the queue. Think of how bank tellers process a line of
customers.

Perhaps there would be an event (or delegate) that would fire when an item
in the pool becomes free. in the event's code, the worker would grab the
next time in the queue.

Seems like there would need to be a method on the ObjectPool to signal this
process to begin. Perhaps it could listen to an event raised by
queue.enqueue().

Thoughts?

"Chris Mullins [MVP]" <cm******@yahoo.comwrote in message
news:es****************@TK2MSFTNGP03.phx.gbl...
I've written this code more times than I can count, so I hope it's a
decent pattern to follow.

One of these days soon, I'll post my ObjectPool<Tclasses to my blog,
along with some instructions on how to use them. This problem seems to
come up very frequently when writing server applications - we've got
dozens of "expensive" object pools that we maintain. Everything from AD &
LDAP connections, to pinned byte[] buffers for use in reading & writing to
Sockets (to avoid heap fragmentation).

It's got a nice robust mechanism for checking objects in & out of the pool
(using IDisposable so that 'using' blocks can be employed, and also using
Object Resurrection so that the Finalizer is run, the expensive object
doesn't get lost) and its very easy to use.

You wait problem, as you've described it, I usually see it solved with the
Monitor.Pulse / PulseAll pattern. Worker threads are kept blocked in a
Monitor, and when data is added to the queue, the Monitor is Pulsed
realeasing one of the waiting threads. You've got to be carefull of race
conditions, but it's a very well worn pattern.

--
Chris Mullins, MCSD.NET, MCPD:Enterprise, Microsoft C# MVP
http://www.coversant.com/blogs/cmullins

"Craig Buchanan" <so*****@somewhere.comwrote in message
news:%2****************@TK2MSFTNGP03.phx.gbl...
>>I would like to have a limited pool of objects (the objects are expensive
to create) that can be enlisted to process items in a queue. Moreover, I
would like to be able to have the processing (time-consuming) occur on a
background thread.

I have two questions:
* what is a good way to block the queue loop while it waits for a free
worker?
* is my approach a reasonable one?

Thanks,

Craig Buchanan

Here's my psedo-code:

Sub ProcessQueue

Do While Queue.Count 0

'wait for next available worker
Worker = ObjectPool.getFreeWorker()

'assign next item in the queue to the worker
Worker.Item = Queue.Dequeue

'run time-consuming process in background
ThreadPool.QueueUserWorkItem(AddressOf ProcessItem, Worker)

Loop

End Sub

Sub ProcessItem(State As Object)

Dim WorkerAs Worker= CType(State,Worker)

Try

'process item
Worker.Process()

Catch ex As Exception

'return item to queue
Queue.Enqueue(Worker.Item)

Finally

'return worker to pool
ObjectPool.returnWorker(Worker)

End Try

End Sub


Mar 28 '07 #4
On Mar 27, 3:37 pm, "Craig Buchanan" <some...@somewhere.comwrote:
I would like to have a limited pool of objects (the objects are expensive to
create) that can be enlisted to process items in a queue. Moreover, I
would like to be able to have the processing (time-consuming) occur on a
background thread.

I have two questions:
* what is a good way to block the queue loop while it waits for a free
worker?
The best way to block the loop is to block the getFreeWorker method
until a free worker is available. The pattern you're looking for is a
producer-consumer queue or blocking queue. Look for the
ProducerConsumer class in the following article. The Produce and
Consume methods in that class would map directly to your returnWorker
and getFreeWorker methods respectively. I know the examples in the
article are in C#, but you'll get the idea.

http://www.yoda.arachsys.com/csharp/...eadlocks.shtml
* is my approach a reasonable one?
Yes, I think it is reasonable. There might be some minor changes I
would change regarding your general pattern, but nothing worth
mentioning.
Thanks,

Craig Buchanan

Here's my psedo-code:

Sub ProcessQueue

Do While Queue.Count 0

'wait for next available worker
Worker = ObjectPool.getFreeWorker()

'assign next item in the queue to the worker
Worker.Item = Queue.Dequeue

'run time-consuming process in background
ThreadPool.QueueUserWorkItem(AddressOf ProcessItem, Worker)

Loop

End Sub

Sub ProcessItem(State As Object)

Dim WorkerAs Worker= CType(State,Worker)

Try

'process item
Worker.Process()

Catch ex As Exception

'return item to queue
Queue.Enqueue(Worker.Item)

Finally

'return worker to pool
ObjectPool.returnWorker(Worker)

End Try

End Sub

Mar 28 '07 #5
"Craig Buchanan" <so*****@somewhere.comwrote:
is this your blog: http://instructors.cwrl.utexas.edu/jesson/?q=blog/61 ?
Nope, not my blog. I'll give ya a hint though: look at the bottom of this
message. The owner of that blog would probably cry if he was forced to ready
my poor writing all day long...

I'll post the ObjectPool<Tcode to my blog in a few days (when I write my
next entry).

Ping me if I forget...

--
Chris Mullins, MCSD.NET, MCPD:Enterprise, Microsoft C# MVP
http://www.coversant.com/blogs/cmullins
Mar 28 '07 #6
Thanks for the help.

Craig

"Chris Mullins [MVP]" <cm******@yahoo.comwrote in message
news:uK****************@TK2MSFTNGP03.phx.gbl...
"Craig Buchanan" <so*****@somewhere.comwrote:
>is this your blog: http://instructors.cwrl.utexas.edu/jesson/?q=blog/61 ?

Nope, not my blog. I'll give ya a hint though: look at the bottom of this
message. The owner of that blog would probably cry if he was forced to
ready my poor writing all day long...

I'll post the ObjectPool<Tcode to my blog in a few days (when I write my
next entry).

Ping me if I forget...

--
Chris Mullins, MCSD.NET, MCPD:Enterprise, Microsoft C# MVP
http://www.coversant.com/blogs/cmullins


Mar 28 '07 #7
"Craig Buchanan" <so*****@somewhere.comwrote in message
Thanks for the reply. Does your approach also use the ThreadPool to
process the long-running job?
No, it doesn't. You shouldn't use the ThreadPool for long running jobs.
It'll cause all sorts of issues and problems.

http://www.coversant.com/dotnetnuke/...d=88&EntryID=8

--
Chris Mullins, MCSD.NET, MCPD:Enterprise, Microsoft C# MVP
http://www.coversant.com/blogs/cmullins
Mar 28 '07 #8
Brian-

That's pretty slick. It makes a lot of sense too.

Here's an example of a blocking queue:
http://www.codeproject.com/csharp/bo...ckingqueue.asp

Thanks for the reply,

Craig

"Brian Gideon" <br*********@yahoo.comwrote in message
news:11*********************@y80g2000hsf.googlegro ups.com...
On Mar 27, 3:37 pm, "Craig Buchanan" <some...@somewhere.comwrote:
>I would like to have a limited pool of objects (the objects are expensive
to
create) that can be enlisted to process items in a queue. Moreover, I
would like to be able to have the processing (time-consuming) occur on a
background thread.

I have two questions:
* what is a good way to block the queue loop while it waits for a free
worker?

The best way to block the loop is to block the getFreeWorker method
until a free worker is available. The pattern you're looking for is a
producer-consumer queue or blocking queue. Look for the
ProducerConsumer class in the following article. The Produce and
Consume methods in that class would map directly to your returnWorker
and getFreeWorker methods respectively. I know the examples in the
article are in C#, but you'll get the idea.

http://www.yoda.arachsys.com/csharp/...eadlocks.shtml
>* is my approach a reasonable one?

Yes, I think it is reasonable. There might be some minor changes I
would change regarding your general pattern, but nothing worth
mentioning.
>Thanks,

Craig Buchanan

Here's my psedo-code:

Sub ProcessQueue

Do While Queue.Count 0

'wait for next available worker
Worker = ObjectPool.getFreeWorker()

'assign next item in the queue to the worker
Worker.Item = Queue.Dequeue

'run time-consuming process in background
ThreadPool.QueueUserWorkItem(AddressOf ProcessItem, Worker)

Loop

End Sub

Sub ProcessItem(State As Object)

Dim WorkerAs Worker= CType(State,Worker)

Try

'process item
Worker.Process()

Catch ex As Exception

'return item to queue
Queue.Enqueue(Worker.Item)

Finally

'return worker to pool
ObjectPool.returnWorker(Worker)

End Try

End Sub


Mar 28 '07 #9
Chris-

Are you still planning to add this to your blog?

Thanks,

Craig

"Chris Mullins [MVP]" <cm******@yahoo.comwrote in message
news:uK****************@TK2MSFTNGP03.phx.gbl...
"Craig Buchanan" <so*****@somewhere.comwrote:
>is this your blog: http://instructors.cwrl.utexas.edu/jesson/?q=blog/61 ?

Nope, not my blog. I'll give ya a hint though: look at the bottom of this
message. The owner of that blog would probably cry if he was forced to
ready my poor writing all day long...

I'll post the ObjectPool<Tcode to my blog in a few days (when I write my
next entry).

Ping me if I forget...

--
Chris Mullins, MCSD.NET, MCPD:Enterprise, Microsoft C# MVP
http://www.coversant.com/blogs/cmullins


Apr 5 '07 #10
"Chris Mullins [MVP]" <cm******@yahoo.comwrote in message:
One of these days soon, I'll post my ObjectPool<Tclasses to my blog,
along with some instructions on how to use them.
I finally wrote up my ObjectPool<Tclass, and posted it to my Blog.

http://www.coversant.com/Default.asp...=88&EntryID=36

Lemme know how ya like it...

--
Chris Mullins, MCSD.NET, MCPD:Enterprise, Microsoft C# MVP
http://www.coversant.com/blogs/cmullins
Apr 9 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: phil | last post by:
And sorry I got ticked, frustrating week >And I could help more, being fairly experienced with >threading issues and race conditions and such, but >as I tried to indicate in the first place,...
9
by: Brian Henry | last post by:
If i inherite a queue class into my class, and do an override of the enqueue member, how would i then go about actually doing an enqueue of an item? I am a little confused on this one... does over...
3
by: Kceiw | last post by:
Dear all, When I use #include "queue.h", I can't link it. The error message follows: Linking... G:\Projects\Datastructure\Queue\Debug\main.o(.text+0x136): In function `main':...
5
Rooro
by: Rooro | last post by:
Hello everyone i'm working on : " Familiar childhood games such as hide and Go Seek and Tag involve determining the player who is to be "It". One method has the players stand in a circle...
2
by: lavender | last post by:
When define a maxQueue is 10, means it able to store 10 items in circular queue,but when I key in the 10 items, it show "Queue Full" in items number 10. Where is the wrong in my code? Why it cannot...
3
by: jrpfinch | last post by:
I have a script which is based on the following code. Unfortunately, it only works on Python 2.3 and not 2.5 because there is no esema or fsema attribute in the 2.5 Queue. I am hunting through...
4
by: j_depp_99 | last post by:
Thanks to those guys who helped me out yesterday. I have one more problem; my print function for the queue program doesnt work and goes into an endless loop. Also I am unable to calculate the...
2
by: ecestd | last post by:
how do you implement a copy constructor for this pointer-based ADT queue #include <cassert // for assert #include <new // for bad_alloc using namespace std; //private:{Queue::Queue(const...
0
by: ecestd | last post by:
I did implement the copy constructor but still have a problem with it. It is not working. What could be wrong? #include "QueueP.h" #include <cassert // for assert #include <new // for...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.