How to pass the polling thread to another thread for processing. The program execution beings in a controller class which has a main method and a thread pool:
The main class Controller
public static void main(String[] args) throws InterruptedException {
RunnableController controller = new RunnableController();
System.out.println(incomingQueue.size());
controller.initializeDb();
controller.initialiseThreads();
System.out.println("Polling");
controller.initialUpdate();
}
The method which has the thread for Polling class
private void initialiseThreads()
{
try {
threadExecutorRead = Executors.newFixedThreadPool(10);
PollingSynchronizer reader = new PollingSynchronizer(incomingQueue,dbConnection);
threadExecutorRead.submit(reader);
}catch (Exception e){
e.printStackTrace();
}
}
The method which has the thread for the proccesor class
private void initialUpdate()
{
RunnableController.outgoingQueue = incomingQueue;
if((RunnableController.outgoingQueue)!= null){
try {
threadExecutorFetch = Executors.newFixedThreadPool(10);
MessageProcessor updater = new MessageProcessor(outgoingQueue, dbConnection);
threadExecutorFetch.submit(updater);
DBhandler dbhandler = new DBhandler();
dbhandler.updateDb(getOutgoingQueue());
} catch (Exception e) {
}
}
}
The Poller Class and the controller class
public void run() {// Thread in the Poller class
int seqId = 0;
while(true) {
List<KpiMessage> list = null;
try {
list = fullPoll(seqId);
if (!list.isEmpty()) {
seqId = list.get(0).getSequence();
incomingQueue.addAll(list);
this.outgoingQueue = incomingQueue;
System.out.println("waiting");
System.out.println("new incoming message");
while(true){
wait(3000);
notify();
}
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
public void run() {// Second thread in the Processor Class
synchronized (this){
RunnableController.setOutgoingQueue(generate(outgoingQueue));
}
notify();
}
}
My task and Question is :
1.The controller should handle both the threads Poller & processor and it should only call the poller & processor thread
2.Now My question is how to make the poller thread wait for 3 seconds and paralelly notify the processor.
I get the error as follows:
java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at PollingSynchronizer.run(PollingSynchronizer.java:76)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
How to achieve asynchronous processing here?
You need to read something like this first. You cannot use
wait()
without holding the object's monitor. Also, from a short glance, it looks like you use a non-final static member in a multithreading context. Try to make that thread-safe.