In the session object there is a boolean "cancel" flag initially set false
1. request A thread creates the data base query but does not execute it directly
2. instead, it creates a new Runnable object which will do the request and starts it
3. request A thread now sleeps X milliseconds
4. request A thread wakes up, looks at the Runnable object to see if the database request is done, if so go to 8
5. if not, check a flag in the session to see if it has been cancelled
6. if cancelled, complete the HTTP request - will have to provide some way for the Runnable object to eventually recover and clean up all objects created for the database request
7. if not go to 3
8. recover the retrieved data from the Runnable object, format and complete the request.
Your cancel request sets the session cancel flag to true.
If the database operation warrants that a cancel button be placed on the page, then I really doubt if such an operation belongs on the servlet. William's approach should work but it will likely waste a lot of thread resources on the server. Also, you will have to come up with a way to send a response, but keep threads on the server alive that will monitor the activity of the request made. And what happens when the user logs out and the session is lost ? Can your code handle that ?
If you are looking to say deliver a report using POI or something like that, it will make sense to move to a batch like process.
The request will be made and saved to a DB.
A batch process picks up the request and processes the data.
The results are saved in a table / file and the batch process sets a flag to denote this.
The web app meanwhile displays a message to the user that the process is taking place and the user can check back sometime later.
If the user wants to cancel, set a flag in the db. The batch process should read this flag at some stage of the processing and decide what to do.
If the web app detects the flag denoting that the batch process is done, it display the data / file.
Can you provide more details about the operation to be performed. We can provide better answers if we know what problem you are trying to solve.