title: Kotlin Concurrency: Any standard function to run code in a Lock?
body: <p>I've been searching for a function that takes an object of type <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html" rel="nofollow noreferrer"><code>Lock</code></a>
  and runs a block of code with that lock taking care of locking and also unlocking.</p>
  
  <p>I'd implement it as follows:</p>
  
  <pre><code>fun &lt;T : Lock&gt; T.runLocked(block: () -&gt; Unit) {
      lock()
      try {
          block()
      } finally {
          unlock()
      }
  }
  </code></pre>
  
  <p>Used like this:</p>
  
  <pre><code>val l = ReentrantLock()
  l.runLocked {
      println(l.isLocked)
  }
  
  println(l.isLocked)
  //true
  //false
  </code></pre>
  
  <p>Anything available like this? I could only find the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/synchronized.html" rel="nofollow noreferrer"><code>synchronized</code></a> function which cannot be used like this.</p>