Tomcat 6 thread safe email queue (javax.mail.*) - queue

Hi I have design/architecture question. I would like to send emails from one of my jsp pages. I have one particular issue that has been a little bit of a problem. there is an instance where one of the pages will need to send around 50 emails at near the same time. I would like the messages sent to a queue where a background thread will actually do the email sending. What is the appropriate way to solve this problem? If you know of a tutorial, example code or tomcat configuration is needed please let me know.
Thanks,

Your solution is rather sound: append the messages to a internal queue and then let some background task handle them.
Here are a few pointers that may be useful:
Unless you want to go distributed (in which case you should look at JMS), use a BlockingQueue implementation for your queue. In your background thread, just do an infinite loop while take()-ing messages from the queue. Those classes take care of potential concurrency issues for you.
Use a ServletContextListener to set up your background thread when your Web application starts and when it is stopped.
One possible problem with using a raw BlockingQueue is that when your Web application is stopped, all the messages in the queue are lost. If that's a serious problem, then it would probably be easiest just to use a database for the queue and to use notify() to wake up your background thread, which then processes all requests from the database.

Related

iOS. Best way to pull data from a server (dynamic intervals) for HTTP chat client?

I am working on a chat client. To get new messages (or post new one) I have to perform GET (or POST) request. All new messages are stored via core data. At the moment I don't know how to implement it in most optimal way.
My thoughts:
On view controller init stage create background thread which will periodically checks for new messages (if conversation is active - with short period, if not - with period about 60 secs). If there are new messages, we store them in DB and signal delegate that there are new messages to display.
Friend suggested to use performSelector afterDelay, but I don't understand how to use it in my app.
Something else?
Thanks in advance.
Don't use performSelector afterDelay. Using NSTimer is much better (as the trigger for starting the next download). Also, use NSOperationQueue to manage your background tasks. Create yourself a custom NSOperation that you can instantiate and it will complete your request process. When you create a new operation to check for new messages, check if one is already in progress (there is no point having multiple requests in progress at the same time).
Other notes:
Make sure you consider the threading with regards to the Core Data store (having the operation call back to the main thread with the results will probably be easiest as the result data will always be relatively small).
If you have lots of messages being sent and you want to show constant status (like Skype does, showing you when someone is typing) you would need to use sockets to keep the connection alive the whole time (the cost of new connections each time would be prohibitive).

Abort button in ZK

I want to put an Abort Label or button below...the processing message is shown in ZK. or is there any way to load my custom components instead of the default Processing. message in ZK.
Want will happen if do abort while processing is it ideal to do that, I want to do that anyways as few times my application sleeps while loading
ZK is built on Servlets. When the busy button is shown on the ui awaiting the ajax response then the servlet thread is doing long running work on the server. Perhaps it would be possible to send another thread to interrupt the first thread but really that is high risk as all the servlet threads can end up doing long running work and no new ones will be available to cancel them.
The best solution is that long running work should not be on the servlet thread but handed off to a background thread or message queue. See zk-asynchronous-ui-updates-and-background-processing. In that example the work is offloaded to a java.util.concurrent.ExecutorService which has an API to cancel the work.
Note that cancelling of a working thread uses interruption and it is not guaranteed that code which doing the work will respond to the interrupt properly such that it is actually cancellable. The answers on the thread cancel with executor service outline some of the issues and you should test whether the work you are doing can be interrupted using the API.

how many threads is too many in iphone/objective-c dev

I have a complex sync job that does several asyncronous calls for content over HTTP. Each time this content is received, it asks for the next bit and so on. These are all daisey-chained in a big over-all sync job with data on the server.
There are probably 12 steps in this job chain. It seems to get stuck after around the 5th async request, the request never comes back and it hangs for ever waiting for it. I think it may have to do with too many threads being spawned because if I fire off the one it hangs at at the beginning it returns fine.
In the way I imagine it in my head, the main thread asks for async content a. When it comes back in its own asynchronous time it spawns a new thread which then asks for aync content b. When it comes back in its own sweet time it spawns a new thread which then asks for content c. Isn't a new thread being created everytime an async request returns a result?
Am I daisy-chaining these requests right? I was quite good at threads in Java development but I'm a bit confused on how they work in Obj-C. Do I need to use a Thread pool of say 3 threads and reuse these?
Sorry for the high-level question but I'm sure some experts can help clear the cloud of mystery around this.
NSOperationQueues are built on top of Grand Central Dispatch. If you need precise control over order of operations and the ability to dispatch synchronous requests you might want to use GCD directly. Using either, you don't really need to worry about thread creation/management. You simply queue your operations as needed by your app.
The Apple docs are fine on this IMHO but you can find a number of tutorials out there.
[EDIT: added link to Apple docs]
http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html

Killing a thread or an alternative

Is there any way I can kill a thread spawn through:
[NSThread detachNewThreadSelector:#selector(serverFetchInThread) toTarget:self withObject:nil];
The scenario I am working on is that in my main thread I am letting user enter data in my search bar and what ever user is typing I need to send to server for searching in a separate thread. Now, if user changes his selection by deleting old data and entering new data I do not want the previous thread to waste its time, kill it and spawn a new thread with new data.
Be there any other better way to handle this situation, please guide me.
No, there is no way to kill a thread from another thread. And for good reason as there is no way to do so in a fashion where the targeted thread is killed without risk of crashing the app.
To directly answer your question; you need to have some kind of a flag that indicates to the thread that it should stop doing whatever it is doing and exit.
However, a couple of questions are raised by your question:
First, why are you using threads and not using GCD? Concurrency via GCD or NSOperation is the generally recommended way to solve such problems.
Secondly, if you are talking to a server, are you using HTTP (most of the time, that is the case)? If so, why not directly use the asynchronous features of NSURL and friends?
Have a good look at using NSOperationQueue.
You can subclass NSOperation it to wrap up your server communications, and even make that queue serial (maximum operations = 1).
If a server operation is not yet finished and user has generated more input, you can cancel the existing one, and add the new one.
Due to the effect of the NSOperation wrapping your connection, you can just use the simple synchronous version and keep the connection handling very straightforward.
Also worth mentioning is compatibility. I would prefer to use GCD and blocks, but for compatibility, NSOperationQueue is required.

iphone app photo upload to server from app threads

I have an app that needs to upload a least 5 photos to a server using API call available with the server. For that I am planning to use threads which will take care of photo upload and the main process can go on with the navigation of views etc. What I cant decide is whether it is OK to spawn five separate threads in iphone or use a single thread that will do the upload. In the later cases obviously it will become quite slow.
Basically an HTTP POST request will be made to the server with the NSMutableURLRequest object using NSCOnnection.
More threads mean more complexity and sync issues, but I can try to write code as neat as possible if it means better performance than a single thread which is simple but is a real stopper if performance is considered.
Anybody with any experience in this kinda app. ??
I would suggest using one extra thread and queuing the uploads, one after the other. You'll end up clogging the network interfaces if you try 5 uploads concurrently. Remember that the iPhone will often be on a 3G or even EDGE connection, not always WiFi, so photo uploads can be really slow, and even slower if there are 5 at once.
You could probably benefit from using NSOperation and NSOperationQueue to nicely handle the ugly threading for you. Wrap up an upload process into an NSOperation, and then queue 5 of them for each image. Should work quite nicely.
Jasarien thanks for the bit on NSOperation and NSOperationQueue. It did simplyify in great measure. But right now I hve run into a major issue.
I spawn an extra thread from the main thread. This thread queues up each of the picture upload operation. So this thread queues up 5 picture opload operations in a queue. This is absolutely fine when working with Mac PC. Now when I push the app to the device, only one pic upload is successful and the rest fails. Most of the cases of failure are due to server time out error. So basically I am wondering, whether NSOperationQueue ensure only one operation at a time or not ? I mean if the first pic upload is in progress and say the next operation is already added in the queue. Would it create an extra thread for the second operation too while the first one is running ? I think as the name suggests, it must wait in the queue until the previous one is done. Not sure how to go abt doing it. I am uploading pic which are taken with iphone camera.