Meaningless Drivel is fun!*
The moose likes Threads and Synchronization and the fly likes How to suppress duplicate thread? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "How to suppress duplicate thread?" Watch "How to suppress duplicate thread?" New topic
Author

How to suppress duplicate thread?

Ram Prakash Jayapalan
Greenhorn

Joined: Jul 06, 2012
Posts: 10
Hi,

I have an issue with the threads. The logic is that on clicking a button, a thread will be invoked and is made to complete the necessary action. But the issue i'm facing is that users had reported duplicate threads are invoked by clicking on the button. That is, on clicking the button instead of invoking a single parent thread two parent threads are getting invoked which is finally affecting my jsp page with Http 500 exception. I am not sure why this is happening at times. Does any one know how to suppress the duplicate thread?
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1761
    
    7

Hello, welcome to JavaRanch!

Forgive me for saying this, but I think you're barking up the wrong tree when trying to "suppress duplicate threads".
At the very least, you could disable the button using JavaScript as soon as it's been clicked, to prevent duplicate action's by impatient users.
That is a not to be relied upon client-side feature, though. You should really look into the cause of the internal server error and prevent the concurrency issue from occuring, by fixing you code.

Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Ram Prakash Jayapalan
Greenhorn

Joined: Jul 06, 2012
Posts: 10
Hi,
yes i agree with that point of disabling the button after a click. But my issue is something different. On a single click, two threads are getting invoked instead of one.
Any idea on how to handle this?
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Hopefully you won't find this answer too simplistic, but you fix the problem by finding the code which incorrectly spawns two threads and fix it so that it only spawns a single thread. As Jelle already said in his reply. Your code has a bug, so just use standard bug-fixing procedures.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18754
    
  40

Ram Prakash Jayapalan wrote:Hi,
yes i agree with that point of disabling the button after a click. But my issue is something different. On a single click, two threads are getting invoked instead of one.
Any idea on how to handle this?


Keep in mind that the JVM doesn't just start duplicate threads -- so if these threads are getting started, there is a bug, either in you application or one of the libraries that you are using.

I would recommend debugging your application to see when these threads are created. You can't fix something without information on when / how it is happening.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ram Prakash Jayapalan
Greenhorn

Joined: Jul 06, 2012
Posts: 10
Thanks for the info guys. Even I'm trying to figure out any bug in the code. But users say that this is not happening often but only at times. So i need to think upon it
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Ram Prakash Jayapalan wrote:But users say that this is not happening often but only at times. So i need to think upon it


Then you might find that the problem only occurs when the user clicks twice on the button after all. (Sometimes you don't get completely accurate information from user reports of problems.) In which case disabling the button via Javascript when it's clicked might be a good idea. And also modifying the server code so that it doesn't submit a second thread if the first thread is still running might be a possibility too.
Ram Prakash Jayapalan
Greenhorn

Joined: Jul 06, 2012
Posts: 10
So could you let me know how to stop another thread from getting initiated before the former thread gets completed in detail as I'm not much familiar with thread concepts?
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

You don't have to be a thread expert for that.

When you submit a thread, set a variable somewhere to "true". Have the thread set that variable to "false" when it finishes. Then when you decide to submit a thread, check that variable to see if another thread is still running.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18754
    
  40

Ram Prakash Jayapalan wrote:So could you let me know how to stop another thread from getting initiated before the former thread gets completed in detail as I'm not much familiar with thread concepts?


Paul Clapham wrote:You don't have to be a thread expert for that.

When you submit a thread, set a variable somewhere to "true". Have the thread set that variable to "false" when it finishes. Then when you decide to submit a thread, check that variable to see if another thread is still running.


Or in other words, if you are unable to fix the bug (that instantiates those extra Thread objects and starts them).... from the newly created thread itself, it is too late to prevent the Thread object from being instantiated (obviously), it is too late to prevent the thread from being create too (again obviously), but your newly created thread can detect that it was started incorrectly, and just not doing anything (clean up and return from the run() method).

Henry
Ram Prakash Jayapalan
Greenhorn

Joined: Jul 06, 2012
Posts: 10
Hi,

Below is the code snippet which I am working on. When the user clicks on the respective button, this runFullBatch() method will be invoked. Finally if the process is complete, based upon success/error return string the success/error page is displayed from the view. The issue here is when knowingly/unknowingly if two threads are initiated from this runFullBatch method, the jsp is unable to handle it and it results in HTTP 500 error.

Can anyone tell me how to suppress the duplicate threads/the second thread in a safe way until the former thread completes the process?

public String runFullBatch() {
String returnStr = ActionConstants.BATCH_PROCESS_STATS_STR;
String selectedEstimateDate = estimateDateCriteriaImpl.getSelectedEstimateDate();
try {
if ("".equals(selectedEstimateDate)) {
this.errorMessages.add(" Please select an estimate date to run Full Batch.");
} else {
SystemAdminProcessHandler sysAdminProcessHandler = new SystemAdminProcessHandler();
sysAdminProcessHandler.runFullBatch(estimateDateCriteriaImpl);
}
this.confirmationMessages.add(" The Full Batch has been submitted.");

// Sleep the thread to make sure the button states will be correct
Thread.currentThread().sleep(5000);
}
catch (Exception ex){
............................
...........................
return ActionConstants.ERROR_OUTCOME_STR;
}
return returnStr;
}
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

First of all: get rid of the line which causes the code to sleep for 5 seconds. Making the response slower is likely to make the user click twice, which is apparently one of the sources of your problem. So it contributes to the problem rather than solving it. I don't understand the comment about "button states" but I think whoever put it there didn't know what they were doing.

If you want code which prevents a user from submitting a second batch while the first batch is still running, then here's what you should do. Design a session attribute which works like this: When a batch is running, the session attribute exists. And when no batch is running, the session attribute does not exist.

As Henry suggested earlier, there are several ways to implement that. But in all of them, there's an if-statement which says "If the attribute exists then don't do any batch processing". And there's code which adds the attribute just before processing starts, and code which removes it (in a finally block so it always runs) after processing finishes. Watch out for race conditions between the first two of those three things.
Ram Prakash Jayapalan
Greenhorn

Joined: Jul 06, 2012
Posts: 10
Guys,

Could anyone tell me how to check for the null value value in session variable? Below is the snippet. I am getting null pointer exception when the session variable is null. Could any one tell me how to overcome this null pointer exception and check for null value in the if loop?

HttpSession session = (HttpSession) getFacesContext().getExternalContext().getSession(true);
String sessionVar = session.getAttribute("Thread"); //getting null pointer exception in this step
if(sessionVar.equals (null)){
System.out.println("******** Multiple Threads ********");
}else{
session.setAttribute("Thread","true");
System.out.println("****** The session attribute is :" +session.getAttribute("Thread"));
runFullBatch();

}
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12769
    
    5
if(sessionVar.equals (null)){


Wrong way to check if a reference variable is null, use sessionVar == null

The reason being that the equals method assumes you have an actual object reference.

Bill
Ram Prakash Jayapalan
Greenhorn

Joined: Jul 06, 2012
Posts: 10
Hi,

I wanted to suppress duplicate thread (e., second thread if the user submits a request twice). I have come up with below code where I am setting up a session variable. Initially the session var "Thread" value would be null. So it enters the else block and the runFullBatch method will be invoked.Now if another thread enters before the initial process completes, the second thread will be caught in the if block as the session var is reset only at the end of the runFullBatch method.By this way i'm planning to catch the duplicate thread.

Is this the right way of doing?
Even if I catch the second thread, should it be redirected to any jsf page as I am just logging the error in the logger?
After entering the if block, is there any way to suppress the thread without redirecting to a jsp?

HttpSession session = (HttpSession) getFacesContext().getExternalContext().getSession(true);
String sessionVar =(String )session.getAttribute("Thread");
if(sessionVar!=null){
System.out.println("******** Multiple Threads ********");
try{
Throw new Exception ("******** Multiple Threads ********");
}catch(Exception e) {
Filelogger.logFatal(e);
}
}else{
session.setAttribute("Thread","true");
System.out.println("****** The session attribute is :" +session.getAttribute("Thread"));
runFullBatch();

}

Public string runFullBatch()
{
......
......
session.removeAttribute("Thread");
}
 
Don't get me started about those stupid light bulbs.
 
subject: How to suppress duplicate thread?