Wait () on Servlet throws Exception

I am running a web application on a Jboss application server and I am trying to implement an event database response from a server.

For this, I use .wait () and .notify () in the servlet class. Basically, there is an Ajax request, a servlet block with wait , until there are events on the server, and if so, notify will be launched on the servlet.

The problem is that I am waiting (1000 * 60) on the servlets that I get:

 Servlet.service() for servlet ProcessesServlet threw exception: java.lang.IllegalMonitorStateException 

Is it possible to execute wait () in the HttpServlet class?

+6
source share
4 answers

Before you wait for an object, you must take responsibility.

This is usually done using a synchronized statement.

  synchronized (obj) { try { obj.wait(someTime); } catch (Throwable e) { e.printStackTrace(); } } 
+7
source

You cannot put wait (...) in a servlet because doPost, doGet, ... are not a synchronized method.

you can put wait only in a synchronized method or block. So you can put the synchronized block and put wait.Like in it below -

  synchronized (object) { try { object.wait(1000*60); } catch (Throwable ex) { ex.printStackTrace(); } } 
+2
source

There is no condition in the accepted answer. Whenever you wait, you should always check the condition to protect yourself from side awakening. In principle, the expectation is guaranteed to return normally in all cases of which he speaks. He may also return for no apparent reason. You must follow the pattern from Javadoc . I would not recommend catching Throwable here or almost everywhere. Instead, catch only an InterruptedException. In addition, you must ensure that the status check is thread safe. So, for example, you can do the following:

 private boolean condition; private Object lock = new Object(); private long timeout = 1000; public void conditionSatisfied() { synchronized (lock) { condition = true; lock.notify(); } } public void awaitCondition() { synchronized (lock) { while (!condition) { try { lock.wait(timeout); } catch (InterruptedException e) { // Probably throw some application specific exception } } // Perform action appropriate to condition } } 

You will notice that you are waiting in a loop. A timeout simply means that you will wait at intervals until the timeout value. If you want to set a common timeout limit, you must mark the current time outside the loop and check it after each wait.

+2
source

As Dystroy said, you need to lock the object to call it wait. If for some reason you cannot or do not want to do this (for example, the same method that simultaneously tries to obtain a lock on the same object), you can use:

 try{ Thread.sleep(time); } catch (Exception ex){ Thread.interrupted(); } 

Or declare a new object where you can get a lock.

+1
source

Source: https://habr.com/ru/post/917653/


All Articles