简体   繁体   中英

Thread synchronization when another thread may exist or not

I have a thread which performs some calculations, each calculation has an id. A new thread is started for every calculation. When the processing is completed data is written in the database corresponding to its id.

There could(may or may not) be another request, this needs the calculated result from the other thread. It looks in the database for the id, if found it will return the result. If not it needs to check if a calculation is already in progress If so, wait for the calculation to be completed. Wake up once done, get the data from the database and return. If no calculation is running start a calculation and wait. Wake up once done, get the data from the database and return.

The pseudo code is as follow:
CalculationClass
    receive a request id from a Consumer
    add id to CalculatingIds List
    when calculated
        write data to DB
        remove id from CalculatingIds List

GetDataClass
    look for the the result corresponding to id
    if found return data
    else check if the id is present in the CalculatingIds List
        if present, wait and wake up when data is available
        if not present, pass the id to the Consumer Queue. Wait and wake up when data is available

I am not able to find a way to synchronize the 2 threads for the case when the data is not yet ready for GetDataClass. I was thinking of creating a new object for each calculation and then use this to synchronize the 2 threads.

synchronize(lock)
  if(noData && calculationRunning)
    lock.wait();
  else
    queue.add(id)
    CalculatingIds.add(id)

But how will I handle this lock in the case of CalculationClass ? How will I handle the case when the GetDataClass thread does not exist?

Have a collection that tracks what is currently being processed. Protected it with a lock. A thread that is processing a particular entry makes a notification of such while holding the lock on the collection. When it is finished, it acquires the lock on the collection, removes the entry, and notifies any other threads by calling notifyAll . If a thread finds an entry from another thread while it holds a lock on the collection, it loops on wait until notified that the other thread is finished.

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