java: mutual exclusion for a global date used by more thread

hi mate i have a global date in my class, this date is used and modified by two thread, i need to solve the problem of mutual exclusion for this date. i m non expert in java, in c is simple, at example:

lock(...)
use/modified global date
unlock(....)

I need the corrispondent in java

Answers


There are two approach you can use:

1) Use synchronized keywords:

synchronized(theGlobalDate) {
  // do whatever modification you want
}

This is the basics in Java world.

2) In Java 5, there is new set of concurrent library, you can use locks for things you do somehting similar to what you did in C

private final ReentrantLock lock = new ReentrantLock();

.....

public void foo() { 
  lock.lock();
  try {
    // do whatever modification you want
  } finally {
    lock.unlock();
  }
}

For starters, use a synchronized block:

Object dateLock = new Object(); // globally visible lock, declare it 
                                // next to your date object

//...

synchronized(dateLock) {
   // modify date
}

The above is sufficient for two threads. For more complicated scenarios, like when reading is done by multiple threads often and writing is seldom, look into ReadWriteLock.


Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.