user2809787
user2809787

Reputation: 41

Delay while reading message from BlockingQueue

I need to add delay while reading message from BlockingQueue. when i added Sleep in consumer it is not going in sleep mode.

Producer Code:

public void run() {
    while ((line = reader.readLine()) != null && !line.trim().isEmpty()) {
        queue.put(line);
        //queue.put(message);
    }
}

Consumer Code:

public void run() {
    try {
                while((msg= queue.poll(3, TimeUnit.SECONDS)) != null && msg.getExpireTime()>=System.currentTimeMillis()) {
            System.out.println(queue.size());
            System.err.println("str = " + msg);
            Long completionTime = 0L;
            switch(msg.getMessageType()){
                case UPDATE:completionTime = 450L;break;
                case ALERT:completionTime = 250L;break;
                case REMOVE:completionTime = 100L;break;
                case ADD:completionTime = 450L;break;
            }
            log.info(msg);
            try {
                Thread.currentThread().sleep(completionTime);
            }catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Thread waiting for "+completionTime +" ms");
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

Input:

first line 450ms sleep
Second Line 450ms sleep
Third Line 100ms sleep

Output:

first line 
Third Line
Third Line

Expected Output:

first line 
Second Line 
Third Line

Upvotes: 0

Views: 268

Answers (1)

Dave
Dave

Reputation: 4597

Consider using a DelayQueue. .take() blocks until the correct amout of time has passed for each element.

Upvotes: 2

Related Questions