Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>While you are using synchronized(this) you are using the class instance as a lock itself. This means that while lock is acquired by thread 1 the thread 2 should wait</p> <p>Suppose the following code</p> <pre><code>public void method1() { do something ... synchronized(this) { a ++; } ................ } public void method2() { do something ... synchronized(this) { b ++; } ................ } </code></pre> <p>Method 1 modifying the variable <em>a</em> and method 2 modifying the variable <em>b</em>, the concurrent modification of the same variable by two threads should be avoided and it is. BUT while <em>thread1</em> modifying <em>a</em> and <em>thread2</em> modifying <em>b</em> it can be performed without any race condition.</p> <p>Unfortunately, the above code will not allow this since we are using the same reference for a lock; This means that threads even if they are not in a race condition should wait and obviously the code sacrifices concurrency of the program.</p> <p>The solution is to use <em>2</em> different locks for <em>two</em> different variables.</p> <pre><code> class Test { private Object lockA = new Object(); private Object lockB = new Object(); public void method1() { do something ... synchronized(lockA) { a ++; } ................ } public void method2() { do something ... synchronized(lockB) { b ++; } ................ } </code></pre> <p>The above example uses more fine grained locks (2 locks instead one (<em>lockA</em> and <em>lockB</em> for variables <em>a</em> and <em>b</em> respectively) and as a result allows better concurrency, on the other hand it became more complex than the first example ...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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