Of course, it was easy in ColdFusion - create 3 or more CFThreads and have them each call a function that goes off and gets the weather. Have the function contain a while loop that will keep checking weather until all the countries are complete.
At the bottom of the script after creating the threads, join them together to wait for them all to be finished. No problem.
However, one thing that gets interesting is that you have all these cfthreads grabbing countries off the list and putting the weather results back into a response packet. They are all frantically running at the same time. If you want to make sure you don't have conflicts or repeated calls, you have to use an exclusive cflock so that they patiently take turns getting a country and then wait to add their results.
What we really want here is a queue. We have lots of choices - third parties like RabbitMQ, database queues like Service Broker, etc. But in this case we don't really want to add another layer, we just want a simple in-memory queue. What about the queue datatype that is built into Java (LinkedLists and their relatives)?
I did a quick search, and I didn't see any CF developers playing with this technique, so I thought I'd try it. Sure enough, it really simplified my code due to there being no need for locking, and was very easy to use:
This file contains 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
<cfscript> | |
newQueueObj = CreateObject("java", "java.util.LinkedList"); | |
newQueue = newQueueObj.init(); | |
writedump(newQueue); // queue should be empty | |
newQueue.add('test1'); // add a string to the queue (like array push) | |
newQueue.add('test2'); // add a string to the queue | |
writedump(newQueue.size()); // check queue size | |
writedump(newQueue); // show queue with two items | |
writedump(newQueue.poll()); // use poll to grab the next item (like array pop) | |
writedump(newQueue); // show queue with one items | |
writedump(newQueue.size()); // check queue size | |
</cfscript> |
No comments:
Post a Comment