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:

use/modified global date

I need the corrispondent in java


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() { 
  try {
    // do whatever modification you want
  } finally {

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