How to Override this run method calling another method - java

I am having a run method which tries to override another run method. But its not happening because I am getting a "Class not found Exception" before it passed on to run method.
HereĀ“s my class with run method
public class PollingSynchronizer implements Runnable{
public Collection<KamMessage> incomingQueue,outgoingQueue,fetchedMessages;
private Connection dbConnection;
/**
* Constructor. Requires to provide a reference to the Kam message queue
*
* #param incomingMessages reference to message queue
* #param dbConnection
*
*/
public PollingSynchronizer(Collection<KpiMessage> incomingQueue, Connection dbConnection) {
super();
this.incomingQueue = incomingQueue;
this.dbConnection = dbConnection;
}
private int seqId;
public int getSeqId() {
return seqId;
}
public void setSeqId(int seqId) {
this.seqId = seqId;
}
#Override
/**
* The method which runs Polling action and record the time at which it is done
*
*/
public void run() {
int seqId = 0;
while(true) {
List<KamMessage> list = null;
try {
list = fullPoll(seqId);
if (!list.isEmpty()) {
seqId = list.get(0).getSequence();
incomingQueue.addAll(list);
this.outgoingQueue = incomingQueue;
System.out.println("waiting 3 seconds");
System.out.println("new incoming message");
Thread.sleep(3000);
//when I debug my execution stops here and throws exception
MessageProcessor processor = new MessageProcessor() {
#Override
public void run() {
new MessageProcessor().generate(outgoingQueue);
}
};
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
This is the method which I have to call in order to execute.
public abstract class MessageProcessor implements Runnable {
private Collection<KpiMessage> fetchedMessages;
private Connection dbConnection;
Statement st = null;
ResultSet rs = null;
PreparedStatement pstmt = null;
private Collection<KpiMessage> outgoingQueue;
public KpiMsg804 MessageProcessor(Collection<KpiMessage> outgoingQueue, Connection
dbConnection){
this.outgoingQueue = outgoingQueue;
this.dbConnection = dbConnection;
return (KpiMsg804) fetchedMessages;
}
public Collection<KamMessage> generate(Collection<KamMessage> outgoingQueue)
{
while(true){
try {
while (rs.next()) {
KamMessage filedClass = convertRecordsetToPojo(rs);
outgoingQueue.add(filedClass);
}
for (KamMessage pojoClass : outgoingQueue) {
KamMsg804 updatedValue = createKamMsg804(pojoClass);
System.out.print(" " + pojoClass.getSequence());
System.out.print(" " + pojoClass.getTableName());
System.out.print(" " + pojoClass.getAction());
System.out.print(" " + updatedValue.getKeyInfo1());
System.out.print(" " + updatedValue.getKeyInfo2());
System.out.println(" " + pojoClass.getEntryTime());
}
return outgoingQueue;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
How can I implement this?
Since I am new here, please give a reason for thumbs down. So that I can explain my question.

Try this:
MessageProcessor processor = new MessageProcessor() {
#Override
public void run() {
**new MessageProcessor()**.generate(outgoingQueue);
}
};
MessageProcessor is an abstract class. object creation inside the run method should have failed at compile time.
processor object is created but unused.. you need to create a thread with the processor instace and start the thread.

Related

Java Nested Monitors (moving past apparent deadlock)

I'm synchronizing and blocking on the same object. Each thread calls the testQueue() method in the PuppetShow class which instantiates a distinct object for each thread to block on. My problem is that once capacity==0, the first thread to encounter that condition calls wait() on its object and then the program hangs and no other thread runs. The third thread outputs "waaah" per the println statement and then no other lines are executed, despite the fact that I instantiate threads after this one.
How do I move past the lock.wait() line in the testQueue method in the PuppetShow() class?
I want to be able to block on distinct objects and add them to vectors in order to queue groups of threads. That's why I'm blocking on distinct objects and then adding these to a vector. To notify the thread I simply notify the element at a position in the vector.
import java.util.Vector;
public class PuppetShow {
private int numSeats = 2;
private int capacity = numSeats;
private Vector<Object> attendingPuppetShow = new Vector<Object>();
public Vector<Object> waitingStudents = new Vector<Object>();
public void testQueue() {
Object lock = new Object();
System.out.println("testQueue begin");
synchronized(lock) {
if(testAttending(lock)) {
try {
System.out.println("waaah");
lock.wait();
System.out.println("ugh");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public synchronized boolean testAttending(Object lock) {
System.out.println("testAttending");
boolean status;
if(capacity==0) {
waitingStudents.add(lock);
System.out.println("capacity="+capacity+" ws size="+waitingStudents.size());
status = true;
}
else {
capacity--;
attendingPuppetShow.add(lock);
System.out.println("capacity="+capacity+" aPS size="+attendingPuppetShow.size());
status = false;
}
return status;
}
public synchronized void testRelease() {
if(waitingStudents.size() > 0) {
while(waitingStudents.size() > 0) {
synchronized(waitingStudents.elementAt(0)) {
waitingStudents.elementAt(0).notify();
}
waitingStudents.removeElementAt(0);
capacity++;
}
}
}
}
class GreenStudent extends Thread {
private PuppetShow ps = new PuppetShow();
public GreenStudent(int id, PuppetShow ps) {
setName("GreenStudent-" + id);
this.ps = ps;
}
#Override
public void run() {
System.out.println(getName()+" queuing for show");
ps.testQueue();
}
}
class StaffMember extends Thread {
private PuppetShow ps = new PuppetShow();
public StaffMember(int id, PuppetShow ps) {
setName("StaffMember-" + id);
this.ps = ps;
}
#Override
public void run() {
ps.testRelease();
}
}
class Driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
PuppetShow ps = new PuppetShow();
GreenStudent gs1 = new GreenStudent(1, ps);
GreenStudent gs2 = new GreenStudent(2, ps);
GreenStudent gs3 = new GreenStudent(3, ps);
StaffMember sm = new StaffMember(1,ps);
gs1.run();
gs2.run();
gs3.run();
sm.run();
}
}
gs1.run();
gs2.run();
gs3.run();
sm.run();
Needs to be
gs1.start();
gs2.start();
gs3.start();
sm.start();
In your example, run will be invoked by the calling thread (main thread). start will launch another thread then eventually call run.

Picking sms from gsm modem with 2 threads

Trying to perform an application that reads sms from gsm modem each a period of time.
Thought about this solution:
Got 2 Threads in my application.
T1)- GSMModemHandler which is a handler for serial communications.
T2)- SMSPicker that requests for sms each period of time and perform some string algorithms on them.
I want my application to do so:
A)- T2 asks for sms using readAllMessages(), a method from the GSMModemHandler class and then keeps blocked.
B)- T1 has got a SerialEventListener, so it listens for the response to the request sent from the GSM-Modem, and sends it back to T2.
C)- Once the response is available in a list from the T2 class, T2 resume its task concerning the string algorithms and then do again the same operations from A after waiting a certain period of time.
I've tried to code that, when i launch the application, it does its work for some time and then blocks, i guess the problem come from a missunderstanding between the 2 Threads, but can't find where the problem is and how to solve it.
Here's my code, and the result:
public class GSMModemHandler extends SerialPort implements
SerialPortEventListener{
private static final String
COMMAND_REMISE_A_ZERO = "ATZ",
COMMAND_SMS_MODE_TEXT = "AT+CMGF=1",
COMMAND_DETAILED_ERRORS = "AT+CMEE=1",
COMMAND_SET_UP_MEMORIES = "AT+CPMS=\"MT\",\"MT\",\"MT\"",
COMMAND_LIST_SUPPORTED_STORAGE_MODES = "AT+CPMS=?",
COMMAND_ENVOIE_SMS = "AT+CMGS=",
COMMAND_GET_ALL_SMS = "AT+CMGL=\"ALL\"",
COMMAND_GET_NEW_SMS = "AT+CMGL=\"REC UNREAD\"",
COMMAND_DELETE_ALL_MESSAGES = "AT+CMGD=0[,4]",
COMMAND_DELETE_READ_MESSAGES = "AT+CMGD=0[,1]";
private SMSPicker smsPicker = null;
private String response = "";
public GSMModemHandler(String port) throws SerialPortException{
super(port);
this.openPort();
this.setParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
this.addEventListener(this);
this.startGsm();
}
public void startGsm() throws SerialPortException{
this.writeString(GSMModemHandler.COMMAND_REMISE_A_ZERO + "\r\n");
this.writeString(GSMModemHandler.COMMAND_SMS_MODE_TEXT + "\r\n");
this.writeString(GSMModemHandler.COMMAND_DETAILED_ERRORS + "\r\n");
this.writeString(GSMModemHandler.COMMAND_SET_UP_MEMORIES + "\r\n");
}
public void sendMessage(SMS sms){
try{
if(this.isOpened()){
this.writeString(GSMModemHandler.COMMAND_ENVOIE_SMS + "\"" + sms.getCorrespondantSms() + "\"\r\n");
this.writeString(sms.getContenuSms() + '\032');
}
}
catch(SerialPortException exp){
exp.printStackTrace();
}
}
public void readAllMessages(){
try{
if(this.isOpened())
this.writeString(GSMModemHandler.COMMAND_GET_ALL_SMS + "\r\n");
}
catch(SerialPortException exp){
exp.printStackTrace();
}
}
public void readUnreadMessages(){
try{
if(this.isOpened())
this.writeString(GSMModemHandler.COMMAND_GET_NEW_SMS + "\r\n");
}
catch(SerialPortException exp){
exp.printStackTrace();
}
}
public void deleteAllMessages(){
try{
if(this.isOpened())
this.writeString(GSMModemHandler.COMMAND_DELETE_ALL_MESSAGES + "\r\n");
}
catch(SerialPortException exp){
exp.printStackTrace();
}
}
public void deleteReadMessages(){
try{
if(this.isOpened())
this.writeString(GSMModemHandler.COMMAND_DELETE_READ_MESSAGES + "\r\n");
}
catch(SerialPortException exp){
exp.printStackTrace();
}
}
public synchronized void fermerConnexion(){
try{
this.closePort();
}
catch(SerialPortException exp){
exp.printStackTrace();
}
}
AtomicBoolean nextResponseIsSms = new AtomicBoolean(false);
#Override
public void serialEvent(SerialPortEvent spe) {
try {
String reponse = this.readString();
System.out.println("GSM response = " + reponse);
// If the next response contains the wanted sms
if(reponse != null && reponse.contains("AT+CMGL=")){
this.nextResponseIsSms.set(true);
System.out.println("nextResponseIsSms = true");
}
// if the response contains sms
else if(this.nextResponseIsSms.get()){
this.smsPicker.getResponse().add(reponse);
System.out.println("response sent !");
this.deleteAllMessages(); // deleting the sms in the gsm modem
System.out.println("messages deleted");
this.nextResponseIsSms.set(false);
System.out.println("nextResponseIsSms = false");
// gives the SMSPicker the hand to treat the response
synchronized(this.smsPicker){ this.smsPicker.notify(); }
System.out.println("smsPicker notified");
}
} catch (SerialPortException ex) {
Logger.getLogger(GSMModemHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #return the smsPicker
*/
public SMSPicker getSmsPicker() {
return smsPicker;
}
/**
* #param smsPicker the smsPicker to set
*/
public void setSmsPicker(SMSPicker smsPicker) {
this.smsPicker = smsPicker;
}
}
public class SMSPicker extends ControlledThread{
private GSMModemHandler modemGsm;
private SMSQueueToDatabase smsQueueHandler;
private volatile Queue<String> responses = new LinkedList<String>();
public SMSPicker(double frequency, GSMModemHandler gsmModem){
super(frequency);
this.modemGsm = gsmModem;
this.modemGsm.setSmsPicker(this);
this.smsQueueHandler = new SMSQueueToDatabase(frequency);
}
#Override
public void whatToDoBeforeTheLoop(){
this.smsQueueHandler.start();
try {
this.wait(2 * this.waitingPeriod.get());
} catch (InterruptedException ex) {
Logger.getLogger(SMSPicker.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void whatToDoDuringTheLoop() throws NullPointerException{
synchronized(this){
try {
System.out.println("I'm going to launch the request !");
// Sending the sms read request to the gsm modem
this.modemGsm.readAllMessages();
System.out.println("i'm going to be stopped!");
// wait till we get the answer
this.wait();
System.out.println("I've been stopped and now resuming");
}
catch (InterruptedException ex) {
Logger.getLogger(SMSPicker.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Treating the response in order to extract sms from it
while(!this.responses.isEmpty()){
String longMessage = this.responses.poll();
if(longMessage != null){
String[] shortMessages = null;
shortMessages = longMessage.split("\\+CMGL: [0-9]*,\"");
if(shortMessages == null) continue;
for(String shortMessage: shortMessages){
int indexLastOK = shortMessage.lastIndexOf("OK");
if(indexLastOK != -1 && shortMessage.contains("+"))
this.smsQueueHandler.getSmsFifo().add(this.fromStringToSms(shortMessage
.substring(0,shortMessage.lastIndexOf("OK") - 2))); // if it is the last sms
else if(shortMessage.contains("REC")) // if it is not the last one
this.smsQueueHandler.getSmsFifo().add(this.fromStringToSms(shortMessage));
}
}
}
}
private SMS fromStringToSms(String stringSms){
String[] smsParts = stringSms.split(",");
String correspondantSms = smsParts[1].replaceAll("\"", "");
String dateSms = smsParts[3].replace("\"","").replaceAll("/", "-");
String heureSms = smsParts[4].substring(0,smsParts[4].lastIndexOf("\"")).substring(0, 8);
String contenuSms = stringSms.substring(stringSms.lastIndexOf("\"") + 3);
LocalDateTime momentSms = LocalDateTime.parse("20" + dateSms + "T" + heureSms);
return new SMS(correspondantSms,contenuSms,momentSms);
}
#Override
public void whatToDoAfterTheLoop() {
}
/**
* #return the modemGsm
*/
public GSMModemHandler getModemGsm() {
return modemGsm;
}
/**
* #param modemGsm the modemGsm to set
*/
public void setModemGsm(GSMModemHandler modemGsm) {
this.modemGsm = modemGsm;
}
/**
* #return the smsQueueHandler
*/
public SMSQueueToDatabase getSmsQueueHandler() {
return smsQueueHandler;
}
/**
* #param smsQueueHandler the smsQueueHandler to set
*/
public void setSmsQueueHandler(SMSQueueToDatabase smsQueueHandler) {
this.smsQueueHandler = smsQueueHandler;
}
/**
* #return the response
*/
public Queue<String> getResponse() {
return responses;
}
/**
* #param response the response to set
*/
public void setResponse(Queue<String> responses) {
this.responses = responses;
}
}
public abstract class ControlledThread extends Thread{
protected AtomicBoolean workable = null;
protected AtomicLong waitingPeriod = null;
public ControlledThread(double frequency){
super();
this.workable = new AtomicBoolean(true);
this.waitingPeriod = new AtomicLong(((long)(1000 / frequency)));
}
#Override
public synchronized void run() {
this.whatToDoBeforeTheLoop();
while(this.workable.get()){
try{
this.whatToDoDuringTheLoop();
this.wait(this.waitingPeriod.get());
}
catch(InterruptedException exp){
exp.printStackTrace();
}
}
this.whatToDoAfterTheLoop();
}
public void stopWorking(){
this.workable.set(false);
}
public synchronized boolean isWorking(){
return this.workable.get();
}
public abstract void whatToDoBeforeTheLoop();
public abstract void whatToDoDuringTheLoop();
public abstract void whatToDoAfterTheLoop();
}
Result:
Note: The blocking state happens at the red line (BUILD STOPPED is just a result of the fact that i stopped the application by a kill)
Thanks in advance !
Most likely, you're experiencing a missed signal : you start waiting for a notify() that has already happened.
This is because you start waiting unconditionally. You should, however, always wait from within a loop that checks its wait condition.
In your case the contion to keep waiting is probably until an answer has been supplied.
so :
while (!hasAnswer()) {
this.wait();
}
You must also make sure that the monitor you synchronize on (the SMSPicker in your case) properly guards the state that determines the condition. Since you simply seem expose the response queue, it think it's likely not the case, but I'm missing too many details to say for sure.
For a more detailed explanation look here.

Java Application Design [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am pretty new to Object Programming and Java, so I am here to gather your advice and feedback. Basically I am trying to write a background service which performs different tasks at different intervals. I'm just not 100% sure of what I am doing is following the coding standards or is efficient.
Main / Start Class:
public class Start {
public static void main(String[] args) {
Service s = new Service();
s.Start();
}
}
Database Class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Database {
/* Database settings */
private final String HOSTNAME = "localhost";
private final String DATABASE = "java_database";
private final String USERNAME = "java_username";
private final String PASSWORD = "java_password";
/* Database connection */
public Connection getConnection() {
try {
return DriverManager.getConnection("jdbc:mysql://" + HOSTNAME + "/" + DATABASE + "?user=" + USERNAME + "&password=" + PASSWORD + "&useSSL=false&useUnicode=true&characterSetResults=utf8");
} catch (SQLException ex) {
ex.printStackTrace();
}
return null;
}
}
Service Class:
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Service {
private int taskId;
private int taskType;
/* Start Service */
public void Start() {
try {
System.out.println("Starting Service...");
while(true) {
System.out.print("Checking for tasks... ");
getNextTask();
if (this.taskId > 0) {
System.out.println("Task ID " + this.taskId + " found.");
switch (this.taskType) {
case 1:
System.out.println("Task 1");
SampleTask s = new SampleTask();
s.Start();
s = null;
break;
default:
System.out.println("Error: Unknown Task");
}
setUsedTask();
} else {
System.out.println("No tasks to perform at this time.");
}
this.taskId = 0;
this.taskType = 0;
Thread.sleep(5000);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
/* Gets the next available task from the database */
public void getNextTask() {
try {
Database db = new Database();
String query = "select taskId, taskType "
+ "from tasks "
+ "where (time_to_sec(timediff(now(), taskLastRun)) > taskFrequency or taskLastRun is null) and taskEnabled = 1 "
+ "limit 1";
Statement stmt = db.getConnection().createStatement();
ResultSet rset = stmt.executeQuery(query);
if (rset.next()) {
this.taskId = rset.getInt(1);
this.taskType = rset.getInt(2);
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
/* Set task as complete */
public void setUsedTask() {
try {
Database db = new Database();
String query = "update tasks "
+ "set taskLastRun = now() "
+ "where taskId = ? "
+ "limit 1";
PreparedStatement pstmt = db.getConnection().prepareStatement(query);
pstmt.setInt(1, this.taskId);
pstmt.executeUpdate();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
Consider replacing your Thread.sleep() approach with a wait() and notify() approach as discussed here.
public class Service {
private int taskId;
private int taskType;
private final Object serviceMonitor;
/* Start Service */
public void Start() {
synchronized(serviceMonitor){
try {
System.out.println("Starting Service...");
while(true) {
System.out.print("Checking for tasks... ");
getNextTask();
if (this.taskId > 0) {
System.out.println("Task ID " + this.taskId + " found.");
switch (this.taskType) {
case 1:
System.out.println("Task 1");
SampleTask s = new SampleTask();
s.Start();
s = null;
break;
default:
System.out.println("Error: Unknown Task");
}
setUsedTask();
} else {
System.out.println("No tasks to perform at this time.");
}
this.taskId = 0;
this.taskType = 0;
serviceMonitor.wait();
}
}
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
}
public void getNextTask() {
synchronized(serviceMonitor){
try {
Database db = new Database();
String query = "select taskId, taskType "
+ "from tasks "
+ "where (time_to_sec(timediff(now(), taskLastRun)) > taskFrequency or taskLastRun is null) and taskEnabled = 1 "
+ "limit 1";
Statement stmt = db.getConnection().createStatement();
ResultSet rset = stmt.executeQuery(query);
if (rset.next()) {
this.taskId = rset.getInt(1);
this.taskType = rset.getInt(2);
serviceMonitor.notifyAll();
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public class Main {
public static void main(String[] args) {
Service service = new Service(Arrays.asList(new SampleTask(),new AnotherTask()));
service.execute();
}
}
class Service {
private List<Task> taskList;
public Service(List<Task> taskList) {
this.taskList = taskList;
}
public void addTask(Task task) {
taskList.add(task);
}
public void execute() {
for (Task task : taskList) {
new Timer().schedule(task, task.getDelay(), task.getPeriod());
}
}
public void clearTasks() {
taskList.clear();
}
}
abstract class Task extends TimerTask {
abstract long getDelay();
abstract long getPeriod();
}
class SampleTask extends Task {
public void run() {
System.out.println("Sample task executed");
}
long getDelay() {
return 1000;
}
long getPeriod() {
return 60000;
}
}
class AnotherTask extends Task {
public void run() {
System.out.println("Another task is executed");
}
long getDelay() {
return 1000;
}
long getPeriod() {
return 500000;
}
}

How to limit the number of records while reading from mysql table using multithreading

I have 1.5 million records in my mysql table. I'm trying to read all the records in a batch process i.e,planning to read 1000 records in a batch and print those records in console.
For this I'm planning to implement multithreading concept using java. How can I implement this?
In MySQL you get all records at once or you get them one by one in a streaming fashion (see this answer). Alternatively, you can use the limit keyword for chunking (see this answer).
Whether you use streaming results or chunking, you can use multi-threading to process (or print) data while you read data. This is typically done using a producer-consumer pattern where, in this case, the producer retrieves data from the database, puts it on a queue and the consumer takes the data from the queue and processes it (e.g. print to the console).
There is a bit of administration overhead though: both producer and consumer can freeze or trip over an error and both need to be aware of this so that they do not hang forever (potentially freezing your application). This is where "reasonable" timeouts come in ("reasonable" depends entirely on what is appropriate in your situation).
I have tried to put this in a minimal running example, but it is still a lot of code (see below). There are two commented lines that can be used to test the timeout-case. There is also a refreshTestData variable that can be used to re-use inserted records (inserting records can take a long time).
To keep it clean, a lot of keywords like private/public are omitted (i.e. these need to be added in non-demo code).
import java.sql.*;
import java.util.*;
import java.util.concurrent.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FetchRows {
private static final Logger log = LoggerFactory.getLogger(FetchRows.class);
public static void main(String[] args) {
try {
new FetchRows().print();
} catch (Exception e) {
e.printStackTrace();
}
}
void print() throws Exception {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Properties dbProps = new Properties();
dbProps.setProperty("user", "test");
dbProps.setProperty("password", "test");
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", dbProps)) {
try (Statement st = conn.createStatement()) {
prepareTestData(st);
}
// https://stackoverflow.com/a/2448019/3080094
try (Statement st = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_READ_ONLY)) {
st.setFetchSize(Integer.MIN_VALUE);
fetchAndPrintTestData(st);
}
}
}
boolean refreshTestData = true;
int maxRecords = 5_555;
void prepareTestData(Statement st) throws SQLException {
int recordCount = 0;
if (refreshTestData) {
st.execute("drop table if exists fetchrecords");
st.execute("create table fetchrecords (id mediumint not null auto_increment primary key, created timestamp default current_timestamp)");
for (int i = 0; i < maxRecords; i++) {
st.addBatch("insert into fetchrecords () values ()");
if (i % 500 == 0) {
st.executeBatch();
log.debug("{} records available.", i);
}
}
st.executeBatch();
recordCount = maxRecords;
} else {
try (ResultSet rs = st.executeQuery("select count(*) from fetchrecords")) {
rs.next();
recordCount = rs.getInt(1);
}
}
log.info("{} records available for testing.", recordCount);
}
int batchSize = 1_000;
int maxBatchesInMem = 3;
int printFinishTimeoutS = 5;
void fetchAndPrintTestData(Statement st) throws SQLException, InterruptedException {
final BlockingQueue<List<FetchRecordBean>> printQueue = new LinkedBlockingQueue<List<FetchRecordBean>>(maxBatchesInMem);
final PrintToConsole printTask = new PrintToConsole(printQueue);
new Thread(printTask).start();
try (ResultSet rs = st.executeQuery("select * from fetchrecords")) {
List<FetchRecordBean> l = new LinkedList<>();
while (rs.next()) {
FetchRecordBean bean = new FetchRecordBean();
bean.setId(rs.getInt("id"));
bean.setCreated(new java.util.Date(rs.getTimestamp("created").getTime()));
l.add(bean);
if (l.size() % batchSize == 0) {
/*
* The printTask can stop itself when this producer is too slow to put records on the print-queue.
* Therefor, also check printTask.isStopping() to break the while-loop.
*/
if (printTask.isStopping()) {
throw new TimeoutException("Print task has stopped.");
}
enqueue(printQueue, l);
l = new LinkedList<>();
}
}
if (l.size() > 0) {
enqueue(printQueue, l);
}
} catch (TimeoutException | InterruptedException e) {
log.error("Unable to finish printing records to console: {}", e.getMessage());
printTask.stop();
} finally {
log.info("Reading records finished.");
if (!printTask.isStopping()) {
try {
enqueue(printQueue, Collections.<FetchRecordBean> emptyList());
} catch (Exception e) {
log.error("Unable to signal last record to print.", e);
printTask.stop();
}
}
if (!printTask.await(printFinishTimeoutS, TimeUnit.SECONDS)) {
log.error("Print to console task did not finish.");
}
}
}
int enqueueTimeoutS = 5;
// To test a slow printer, see also Thread.sleep statement in PrintToConsole.print.
// int enqueueTimeoutS = 1;
void enqueue(BlockingQueue<List<FetchRecordBean>> printQueue, List<FetchRecordBean> l) throws InterruptedException, TimeoutException {
log.debug("Adding {} records to print-queue.", l.size());
if (!printQueue.offer(l, enqueueTimeoutS, TimeUnit.SECONDS)) {
throw new TimeoutException("Unable to put print data on queue within " + enqueueTimeoutS + " seconds.");
}
}
int dequeueTimeoutS = 5;
class PrintToConsole implements Runnable {
private final BlockingQueue<List<FetchRecordBean>> q;
private final CountDownLatch finishedLock = new CountDownLatch(1);
private volatile boolean stop;
public PrintToConsole(BlockingQueue<List<FetchRecordBean>> q) {
this.q = q;
}
#Override
public void run() {
try {
while (!stop) {
List<FetchRecordBean> l = q.poll(dequeueTimeoutS, TimeUnit.SECONDS);
if (l == null) {
log.error("Unable to get print data from queue within {} seconds.", dequeueTimeoutS);
break;
}
if (l.isEmpty()) {
break;
}
print(l);
}
if (stop) {
log.error("Printing to console was stopped.");
}
} catch (Exception e) {
log.error("Unable to print records to console.", e);
} finally {
if (!stop) {
stop = true;
log.info("Printing to console finished.");
}
finishedLock.countDown();
}
}
void print(List<FetchRecordBean> l) {
log.info("Got list with {} records from print-queue.", l.size());
// To test a slow printer, see also enqueueTimeoutS.
// try { Thread.sleep(1500L); } catch (Exception ignored) {}
}
public void stop() {
stop = true;
}
public boolean isStopping() {
return stop;
}
public void await() throws InterruptedException {
finishedLock.await();
}
public boolean await(long timeout, TimeUnit tunit) throws InterruptedException {
return finishedLock.await(timeout, tunit);
}
}
class FetchRecordBean {
private int id;
private java.util.Date created;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public java.util.Date getCreated() {
return created;
}
public void setCreated(java.util.Date created) {
this.created = created;
}
}
}
Dependencies:
mysql:mysql-connector-java:5.1.38
org.slf4j:slf4j-api:1.7.20 (and to get logging shown in console: ch.qos.logback:logback-classic:1.1.7 with ch.qos.logback:logback-core:1.1.7)

How to handle wait() notify()?

Here I have two run methods which should synchronize each other.
Poller Class:
*/
public void run() {
int seqId = 0;
while(true) {
List<KpiMessage> list = null;
try{
if(!accumulator.isUsed){
try {
list = fullPoll(seqId);
if (!list.isEmpty()) {
seqId = list.get(0).getSequence();
accumulator.manageIngoing(list);
}
System.out.println("Updated");
wait();
} catch (Exception e1) {
e1.printStackTrace();
}
}
} catch (Exception e){
// TODO:
System.err.println(e.getMessage());
e.printStackTrace();
}
}
}
/**
* Method which defines polling of the database and also count the number of Queries
* #param lastSeq
* #return pojo col
* #throws Exception
*/
public List<KpiMessage> fullPoll(int lastSeq) throws Exception {
Statement st = dbConnection.createStatement();
System.out.println("Polling");
ResultSet rs = st.executeQuery("Select * from msg_new_to_bde where ACTION = 814 and
STATUS = 200 order by SEQ DESC");
List<KpiMessage> pojoCol = new ArrayList<KpiMessage>();
try {
while (rs.next()) {
KpiMessage filedClass = convertRecordsetToPojo(rs);
pojoCol.add(filedClass);
}
for (KpiMessage pojoClass : pojoCol) {
System.out.print(" " + pojoClass.getSequence());
System.out.print(" " + pojoClass.getTableName());
System.out.print(" " + pojoClass.getAction());
System.out.print(" " + pojoClass.getKeyInfo1());
System.out.print(" " + pojoClass.getKeyInfo2());
System.out.print(" "+ pojoClass.getStatus());
System.out.println(" " + pojoClass.getEntryTime());
}
} finally {
try {
st.close();
rs.close();
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
Processing and Updating Class:
public void run() {
while(true){
try {
while(!accumulator.isUsed)
{
try {
System.out.println("Waiting for new outgoingmessages");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Collection<KpiMessage> outgoingQueue = generate(accumulator.outgoingQueue);
accumulator.manageOutgoing(outgoingQueue, dbConnection);
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
}
}
I have a logical error:
The poller is polling not only for new messsage but also reads the DB again and again from the first.
Also Updates again and again.
How to solve this synchronization problem.
Alternatively you could use a BlockingQueue to transfer the data between threads.
See BlockingQueue for details.
// The end of the list.
private static final Integer End = -1;
static class Producer implements Runnable {
final Queue<Integer> queue;
private int i = 0;
public Producer(Queue<Integer> queue) {
this.queue = queue;
}
#Override
public void run() {
try {
for (int i = 0; i < 1000; i++) {
queue.add(i++);
Thread.sleep(1);
}
// Finish the queue.
queue.add(End);
} catch (InterruptedException ex) {
// Just exit.
}
}
}
static class Consumer implements Runnable {
final Queue<Integer> queue;
private int i = 0;
public Consumer(Queue<Integer> queue) {
this.queue = queue;
}
#Override
public void run() {
boolean ended = false;
while (!ended) {
Integer i = queue.poll();
if ( i != null ) {
ended = i == End;
System.out.println(i);
}
}
}
}
public void test() throws InterruptedException {
Queue queue = new LinkedBlockingQueue();
Producer p = new Producer(queue);
Consumer c = new Consumer(queue);
Thread pt = new Thread(p);
Thread ct = new Thread(c);
// Start it all going.
pt.start();
ct.start();
// Close it down
pt.join();
ct.join();
}
You should synchronize or rather hold the lock or monitor for the object that you are calling wait() or notify() on.
Here is what will help you : wait() throwing IllegalArgumentException
synchronized(lockObject){
lockObject.wait(); //you should hold the lock to be able to call wait()
}

Categories

Resources