I am trying to implement a queue which should be synchronized. The requirement is:
- If the Queue is empty and new data comes then data should be inserted in queue and data processing should start as long as queue does not become empty.
- If Queue is not empty, that means the data in the queue is still being processed. So if some new data comes then the data should just be added to queue.
Here is my implementation:
class QueueManager {
private var jobsQueue: LinkedList<String> = LinkedList()
fun handleIncomingJob() {
if (isEmpty()) {
addJ(jobList)
start()
} else {
addJ(jobList)
}
}
private fun isEmpty(): Boolean {
synchronized(this@QueueManager) {
val ret = jobsQueue.isEmpty()
return ret
}
}
private fun addJ(jobList: Array<SAPJob>) {
synchronized(this@QueueManager) {
jobsQueue.add(jobList)
}
}
private fun remove(): Array<SAPJob> {
synchronized(this@QueueManager) {
return jobsQueue.remove()
}
}
fun start() {
while (!isEmpty()) {
Thread.sleep(10000)
remove()
}
}
}
But the above code does not work.
It fails when multiple thread call handleIncomingJob
method at once and all of them find the queue to be empty. As per my requirement only the first thread should find the queue empty, add data to it and start processing . And the all the other threads should find that since first thread put item in the queue so its not empty , so they should just put the data to queue and exit.
But as per above implementation all thread find the queue to be empty. I do not know whats the problem. I have made all the queue methods to be synchronized. Still it does not work