简体   繁体   中英

How to avoid synchronize in multithreaded environment?

I am facing one issue related to multithreading because of shared code. I want to avoid syncronization. I saw so many threads related to AtomicInteger & Semaphore. But havn't got clear idea about what way and how exactly it is better option than synchronization.

Here is my simple code which i want to make thread safe. Class to create thread.

public class ThreadCheck implements Runnable {
TestStaticVar var = new TestStaticVar();
@Override
public void run() {
    // TODO Auto-generated method stub
    try {
        var.holdOn();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public static void main(String args[]) {
    ThreadCheck t = new ThreadCheck();
    Thread t1 = new Thread(t);
    Thread t2 = new Thread(t);
    t1.setName("A");
    t1.start();
    t2.setName("B");
    t2.start();
}}

Class to be executed by multiple threads.

public class TestStaticVar {
Semaphore sem = new Semaphore(1);
public void holdOn() throws InterruptedException{
    sem.acquire();

    System.out.println("Inside Hold on....."+Thread.currentThread().getName()+"==> ");//+i.get());
    try {
          for (long i=0; i<Integer.MAX_VALUE; i++) {

        }
         System.out.println(var1.toString());
    } catch (Exception e) {
    // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Finished Hold on===="+Thread.currentThread().getName());
              sem.release(1);
    System.out.println("Execution Completed by =====> "+Thread.currentThread().getName());
}}

Any help is highly appriciate.

Thanks, Rajesh

One way to avoid synchronization is to make every resource immutable which would be accessed by multiple threads. Making class/object immutable makes sure its threadsafe.

How you avoid synchronization depending on the situation. As your situation is contrived and doesn't do anything which needs locking, the simplest thing to do is remove the lock ie only lock when you need to. (Also remove the long loop which doesn't do anything) Then your application will run much faster.

The two main reasons to try to avoid synchronize blocks are performance and protecting yourself from deadlocks.

Using the synchronize keyword involves performance overhead in setting up the locks and protecting the synchronized operation. While there is a performance penalty for calling a synchronized block, there's a much bigger hit that gets taken when the JVM has to manage resource contention for that block.

The classes in java.util.concurrent.atomic can use machine level atomic instructions rather than locking, making them much faster than code that would use locks. See the javadoc for the package for more information on how that works.

Also, as u3050 mentioned, avoiding mutable shared state goes a long way to preventing the need for synchronization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM