title: Threading in Java: How to lock an object?
body: <p>The following Function is executing in its own thread:</p>
  
  <pre><code>private void doSendData()
  {
      try {
  
             //writeToFile(); // just a temporary location of a call
             InetAddress serverAddr = InetAddress.getByName(serverAddress);
             serverAddr.wait(60000);
             //Log.d("TCP", "C: Connecting...");
             Socket socket = new Socket(serverAddr, portNumber);
             socket.setSoTimeout(3000);
  
                 try {
                  //Log.d("TCP", "C: Sending: '" + message + "'");
                  PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
                  String message = packData();
                  out.println(message);
                  Log.d("TCP", "C: Sent.");
                  Log.d("TCP", "C: Done.");
                  connectionAvailable = true;
  
               } catch(Exception e) {
                   Log.e("TCP", "S: Error", e);
                   connectionAvailable = false;
  
                 } finally {
                    socket.close();
                    announceNetworkAvailability(connectionAvailable);
                  }
  
           } catch (Exception e) {
                Log.e("TCP", "C: Error", e);
                announceNetworkAvailability(connectionAvailable);
           }
  }
  </code></pre>
  
  <p>When the execution reaches the line <code>serverAddr.wait(60000)</code> it throws an Exception:</p>
  
  <pre class="lang-none prettyprint-override"><code>java.lang.IllegalMonitorStateException: object not locked by thread before wait()
  </code></pre>
  
  <p>Does anyone know how to lock an object or a function in order to prevent the concurrency?
  I've tried to add a Lock object:</p>
  
  <pre><code>private final Lock lock = new ReentrantLock();
  </code></pre>
  
  <p>and the line</p>
  
  <pre><code>boolean locked = lock.tryLock();
  </code></pre>
  
  <p>at the beginning of function but it didn't work.</p>