Note that there are some explanatory texts on larger screens.

plurals
  1. POSynchronization in threads for Java
    text
    copied!<p>I have a home grown web server in my app. This web server spawns a new thread for every request that comes into the socket to be accepted. I want the web server to wait until a specific point is hit in the thread it just created. </p> <p>I have been through many posts on this site and examples on the web, but cant get the web server to proceed after I tell the thread to wait. A basic code example would be great. </p> <p>Is the synchronized keyword the correct way to go about this? If so, how can this be achieved? Code examples are below of my app:</p> <p><strong>Web Server</strong></p> <pre><code>while (true) { //block here until a connection request is made socket = server_socket.accept(); try { //create a new HTTPRequest object for every file request HttpRequest request = new HttpRequest(socket, this); //create a new thread for each request Thread thread = new Thread(request); //run the thread and have it return after complete thread.run(); /////////////////////////////// wait here until notifed to proceed /////////////////////////////// } catch (Exception e) { e.printStackTrace(logFile); } } </code></pre> <p><strong>Thread code</strong></p> <pre><code>public void run() { //code here //notify web server to continue here } </code></pre> <p>Update - Final code is as below. The <code>HttpRequest</code> does just call <code>resumeListener.resume()</code> whenever I send a response header (of course also adding the interface as a separate class and the <code>addResumeListener(ResumeListener r1)</code> method in <code>HttpRequest</code>):</p> <p><strong>Web Server portion</strong></p> <pre><code>// server infinite loop while (true) { //block here until a connection request is made socket = server_socket.accept(); try { final Object locker = new Object(); //create a new HTTPRequest object for every file request HttpRequest request = new HttpRequest(socket, this); request.addResumeListener(new ResumeListener() { public void resume() { //get control of the lock and release the server synchronized(locker) { locker.notify(); } } }); synchronized(locker) { //create a new thread for each request Thread thread = new Thread(request); //run the thread and have it return after complete thread.start(); //tell this thread to wait until HttpRequest releases //the server locker.wait(); } } catch (Exception e) { e.printStackTrace(Session.logFile); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload