title: How to handle concurrency with an asynchronous singleton bean
body: <p>I want to implement a singleton bean in Java EE, which starts a VPN connection on demand.</p>
  
  <p>Thus I created a Class like:</p>
  
  <pre><code>@Singleton
  class VPNClient{
    private boolean connected;
  
    @Lock(LockType.READ)
    public boolean isConnected(){
      return this.connected;
    }
  
    @Asynchronous
    @Lock(LockType.WRITE)
    public void connect(){
      // do connect, including a while loop for the socket:
  
      while(true){
        // read socket, do stuff like setting connected when VPN successfully established
      }
    }
  }
  </code></pre>
  
  <p>Then I have another bean, which has the demand for the VPN connection and tries to create it:</p>
  
  <pre><code>  class X {
      @Inject 
      VPNClient client;
  
      private void sendStuffToVPN(){
  
        // call the async connect method
        client.connect();
  
        // wait for connect (or exception and stuff in original source)
        while(!client.isConnected()){
  
          // wait for connection to be established
          Thread.sleep(5000);
        }
      }
    }
  </code></pre>
  
  <p>My problem now is, that because of the connect method, that never ends until the connection is destroyed, the write lock it has, will block all reads to isConnected().</p>
  
  <p><strong>[Update]</strong></p>
  
  <p>This should hopefully illustrate the problem:</p>
  
  <ul>
  <li>Thread 1 (Bean X) calls Thread 2 (Singleton Bean VPNClient) .connect()</li>
  <li>Now there is an endless write lock on the singleton bean VPNClient. But because the method was called async. Thread 1 proceeds:</li>
  <li>Thread 1 (Bean x) tries to call Thread 2 (VPNClient.isConnected()), but has to wait for the release of the write lock (which started with connect()).</li>
  <li>Then the J2EE container throws an javax.ejb.ConcurrentAccessTimeoutException because it waited until timeout.</li>
  </ul>
  
  <p>Is there a good pattern to solve this kind of concurrency problem?</p>