user109447
user109447

Reputation: 1119

Substitute for wait and notify in java

Is there any substitute for wait/notify in java ?

I have two threads:

thread1:
run() {
 while(true) {      
  data = getDataFromDatabase()
  changedData = performSomeChanges(data)
  commitUpdateDataToDatabase(changedDate)
  (send signal to thread2 to start and wait for signal for next repetition)
 }  
}

thread2:
run() {
 while(true) {      
  (wait for signal from thread1)
  data = getDataFromDatabase()
  changedData = performSomeChanges(data)
  commitUpdateDataToDatabase(changedDate)
  (send signal to thread1)      
 }  
}

and I want have some kind of synchranization between them. Now I use wait / notify on special common Object for this purpose.

Upvotes: 0

Views: 898

Answers (1)

Stephen C
Stephen C

Reputation: 719279

Firstly, the simple way to implement your example only uses one thread:

run() {
    while(true) {
        // old thread 1 code      
        data = getDataFromDatabase()
        changedData = performSomeChanges(data)
        commitUpdateDataToDatabase(changedDate)
        // old thread 2 code
        data = getDataFromDatabase()
        changedData = performSomeChanges(data)
        commitUpdateDataToDatabase(changedDate)
    }  
}

There is no obvious (to me) advantage in having the execution alternate between two threads. And there a couple of obvious disadvantages; i.e. complexity, and the (smallish) performance hit of the synchronization and thread switching.


But assuming that you do have a legitimate reason for alternating between two threads, then there are lots of ways of doing it:

  • Using wait and notify ... as you are currently doing. (IMO, there is no real need to find an alternative. They work just fine, if used properly! Admittedly, some Java programmers haven't mastered this ...)

  • Using java.util.concurrent.Semaphore and having each thread alternate between acquiring and releasing.

  • Using a java.util.concurrent.Lock and alternating ownership of the lock.

  • Using a BlockingQueue and passing a "token" object back and forth.

  • And so on

Upvotes: 2

Related Questions