I have a program that starts a thread. In the constructor I pass a volatile boolean, but when the variable is changed in the main thread, this change isn't reflected in the thread.
I declare the following in the main class.
private static volatile boolean sendbuff1;
private static volatile boolean sendbuff2;
private static volatile boolean closeSession;
And start the thread like this.
try{
Thread uploader = new Thread(new appendObj(buffer1loc, buffer2loc, sendbuff1, sendbuff2, closeSession));
uploader.start();
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
Later in the main function, the sendbuff1 is set from false to true, but the sendbuff1 in the thread doesn't change. I was printing it out and it stayed false.
In the appendObj thread,
while(!closeSession) {
if (sendbuff1) {
//append
System.out.println("sendbuff 1 changed");
try {
PrintWriter tobuff1 = new PrintWriter(new File(buffer1loc));
try1.appendFile(buffer1loc);
tobuff1.write("");
tobuff1.close();
sendbuff1 = false;
} catch (Exception e) {
System.out.println("error caught print writing send buff 2");
e.printStackTrace();
}
}
if (sendbuff2) {
System.out.println("sendbuff 2 changed");
try {
PrintWriter tobuff2 = new PrintWriter(new File(buffer2loc));
try1.appendFile(buffer2loc);
tobuff2.write("");
tobuff2.close();
sendbuff2 = false;
} catch (Exception e) {
System.out.println("error caught print writing send buff 2");
e.printStackTrace();
}
}
}
No idea what I'm doing wrong