Search code examples
javamultithreadingconcurrencythread-safetyrmi

Producer/Consumer Threads Concurency Java


I have a producer that produces products and a consumer that consumes them. What I want is, if a product is not consumed in 5 minutes I want it to be destroyed.

This is the part of the producer:

boolean full = false;
public void produce(int p) throws RemoteException {
        //choses a or b randomly 
        //if a or b spot is occupied, thread must wait()

        synchronized(this){
            if ((int)((Math.random()*10)%2) == 1){
                while (a!=-1){try {
                        wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(CHServer.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                a = p;
                if (b!=-1) full = true;
                notifyAll();
            }
            else {
                while (b!=-1){try {
                        wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(CHServer.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                b = p;
                if (a!=-1) full = true;
                notifyAll();
            }
        }
    }

a & b are supposed to be my products.

I really don't know how can I measure that time for example when the thread is waiting or a client isn't trying to consume that product. This piece of code , is running on a RMI java server.


Solution

  • I'd just using a scheme like this: when you produce something use java.util.Timer() to set a timer for 5 minutes in the future. When the item is consumed, .cancel() the timer. If the timer goes off, do whatever cleanup you need to do.