java thread in SMP

Tags:

See http://tinyurl.com/7rreb for further information.

From: “Minkoo Seo”
Newsgroups: comp.programming.threads
Subject: Synchronization constructs in Java and their implications
Date: Mon, 26 Sep 2005 04:44:46 -0700

Hi, all.

I’m not sure whether this is the already discussed issue or not.
Anyway, searching ‘JAVA’, ‘JAVA spinlock’, and ‘JAVA reentrantlock’
didn’t return any articles seems to be relevant to my question.

Here’s my question. As some of you might already knows,
JDK 5.0 added some new synchronization constructs like
ReentrantLock, Semaphore, and AtomicInteger. Before
them, ‘synchronized’ was the only keyword available. And it
automatically inserts memory barrier which make it possible to
thread-safe programs in SMP. However, it is not obvious whether
those new constructs are thread safe or not. So, please tell me.
Are those constructs insert memory barriers as the synchronized
keyword does?

For your information, I post a code snippet which gets locks using
several
ways:

  // lock approach
  private ReentrantLock lock = new ReentrantLock();
  public void lock_method(int n) {

    try { startSignal.await(); } catch(InterruptedException ie) {
ie.printStackTrace(); }
    lock.lock();
    try {
      System.out.println(dummy + “+” + n + “=” + (dummy+n));
      dummy++;
    }
    finally {
      lock.unlock();
    }
  }

  // semaphore approach
  private Semaphore s = new Semaphore(1);
  public void semaphore_method(int n) {

    try { startSignal.await(); } catch(InterruptedException ie) {
ie.printStackTrace(); }

    try {
      s.acquire();
      System.out.println(dummy + “+” + n + “=” + (dummy+n));
      dummy++;
    }
    catch(InterruptedException ie) {
      ie.printStackTrace();
    }
    finally {
      s.release();
    }
  }

  // spin lock approach
  // to get dummy value from memory, we need to make it atomic
  AtomicInteger ai_dummy;
  public void spin_lock(int n) {

    int local_dummy = ai_dummy.getAndIncrement();

    System.out.println(local_dummy + “+” + n + “=” + (local_dummy +
n));
  }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *