I have the following Java program:
public class A extends Thread {
int count;
#Override
public void run() {
while (true)
count++;
}
public static void main(String...strings){
A obj = new A();
obj.start();
System.out.println("The value of count is " + obj.count);
}
}
When running this program the output is: The value of count is 0 (and the program stays running). As far as my understanding with thread it should run in an infinite loop and never print 0. Could anyone help me understanding the nature of this program.
The thread starts at about the same time as the System.out.println runs, and since the thread is background, the println does not wait for it to run, and so you are seeing the initial value of count.
Also as an aside, the count variable should be declared volatile to ensure that the main thread sees changes to the variable made in the loop thread.
The "thread" isn't doing the print, your main is. What were you expecting to happen?
You should also use some kind of protection so both threads can safely access the variable.
Wouldn't the System.out call only run once?
I would put the System.out.println call inside the while loop.
Its probably better to use a getter/setter method for count and make sure only one or the other can access the variable at any given time.
Related
I have written a short program in order to check the effect of the race condition. Class Counter is given below. The class has two methods to update the counter instance variable c. On purpose, I added a random code in both methods , see related code variable i, to increase the probability of their interleaved execution when accessed by two threads.
In the main() method of my program, I put in a loop the following code
t1=new Thread() { public void run(){objCounter.increment();}};
t2=new Thread() { public void run(){objCounter.decrement();}};
t1.start();
t2.start();
try{
t1.join();
t2.join();
}
catch (InterruptedException IE) {}
Then I printed the different values of c in the objCount... Further to the expected values 1, 0, -1, the program displays also the unexpected values: -2,-1, -3, even 4
I sincerely can't see what threads interleaving will lead to the unexpected values given above. Ideally, I should look at the assembly code to see how the statements c++, and c-- got translated...regardless, I Think there is another reason behind the unexpected values.
class Counter{
private volatile int c=0;
public void increment(){
int i=9;
i=i+7;
c++;
i=i+3;
}
public void decrement() {
int i=9;
i=i+7;
c--;
i=i+3;
}
public int value(){ return c; }
}
Even if you marked an int as volatile, that kind of operations are not atomic. Try to replace your primitive int with a Thread Safe Class like:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html
Or just access it through a synchronyzed method.
I put in a loop the following code
You don't show reinitialization of the objCounter variable; this suggests that you're reusing the variable between loop iterations.
As such, you can get -2 from the situation resulting in -1 (e.g. Thread 1 read, Thread 2 read, T1 write, T2 write) happening twice.
In order to avoid reusing the state from previous runs, you should declare and initialize the objCounter variable inside the loop:
for (...) {
Counter objCounter = new Counter();
t1=new Thread() { public void run(){objCounter.increment();}};
t2=new Thread() { public void run(){objCounter.decrement();}};
// ... Start/join the threads.
}
It can't be declared before the loop and initialized inside the loop, because then it is not effectively final, which is required (that, or actual finality) to refer to it inside the anonymous classes of the threads.
On purpose, I added a random code in both methods , see related code variable i, to increase the probability of their interleaved execution when accessed by two threads.
As an aside, this your random code does nothing of the sort.
There is no requirement for Java to execute the statements in program order, only to appear to execute them in the program order from the perspective of the current thread.
These statements may be executed before or after the c++/--, if they are executed at all - they could simply be detected as useless.
You may as well just remove this code, it really only serves to obfuscate.
I am trying to create a simple Java Swing-based application that manually controls two threads which are both trying to continually increment an integer value. The application should be able to 'Start' and 'Stop' either of the threads (both threads incrementing the value simultaneously) and put either of the threads in the critical region (only one thread allowed to increment value).
Here's a screenshot of what I have, so that you may better understand what I am aiming for:
https://i.imgur.com/sQueUD7.png
I've created an "Incrementor" class which does the job of incrementing the int value, but if I try adding the synchronized keyword to the increment() method, I do not get the result I want.
private void increment() {
while (Thread.currentThread().isAlive()) {
if (Thread.currentThread().getName().equals("Thread 1")) {
if (t1Stop.isEnabled()) {
value++;
t1TextField.setText("Thread 1 has incremented value by 1. Current value = " + value + "\n");
}
} else if (Thread.currentThread().getName().equals("Thread 2")) {
if (t2Stop.isEnabled()) {
value++;
t2TextField.setText("Thread 2 has incremented value by 1. Current value = " + value + "\n");
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
Any advice on how to proceed?
I hope I've made it clear what it is I am looking for, if not, let me know and I'll update this post.
your problem is the dreaded thread lock !!
but if I try adding the synchronized keyword to the increment() method, I do not get the result I want.
of course ! Thread manager changes the "Working" thread whenever he feels like it !, and you should post more code here , but from the first look , you are running the same method in both threads , so it will be dropped down to 2 case :-
the good case !
the Thread Manager changes the thread after it finishes calling the increment method(good old win win for both threads ^-^).
the bad case (and this is what you have faced)
imagine that a thread accessed the method and before completing the method the thread managers changes it and when the other method tries to access it find's a big nasty synchronized in it's face with the lock in the other thread !from here is their is no guarantee what will happen but i can assure you that 90% of this cases result's only pleases the thread manager .
The application should be able to 'Start' and 'Stop' either of the threads (both threads incrementing the value simultaneously) and put either of the threads in the critical region (only one thread allowed to increment value).
sorry to break it to you but the thread manager is not-controllable my friend .
but we can suggest a fair amount of thing's to the thread manager , so what you are trying to achieve is not possible at the java thread manager .
and stopping thread's ooky dooky , but starting a thread after stopping it is big NO !!!
from the Thread.start() documentation
It is never legal to start a thread more than once.
In particular, a thread may not be restarted once it has completed
execution.
throws IllegalThreadStateException if the thread was already
started.
here's a very rich link were you can get the topic explained more widely at the oracle's
You can use object-level lock using synchronized keyword.
=> Object-level lock : To synchronize a non static method or block so that it can be accessed by only one thread at a time for that instance. It is used to protect non static data.
Example :
public class ClasswithCriticalSections {
private AtomicInteger count = new AtomicInteger(0);
public synchronized int increment() {
count.incrementAndGet();
return count;
}
}
or
public class ClasswithCriticalSections {
Object lock1 = new Object();
Object lock2 = new Object();
private AtomicInteger count = new AtomicInteger(0);
public int increment() {
synchronized(lock1) {
count.incrementAndGet();
return count;
}
}
public int decrement() {
synchronized(lock2) {
count.addAndGet(-1);
return count;
}
}
}
This question already has an answer here:
Loop doesn't see value changed by other thread without a print statement
(1 answer)
Closed 7 years ago.
In the following code, if i use sysout statement inside for loop then the code executes and goes inside the loop after the condition met but if i do not use sysout statement inside loop then then infinite loop goes on without entering inside the if condition even if the if condition is satisfied.. can anyone please help me to find out the exact reason for this. Just A sysout statement make the if condition to become true. why is it so?
The code is as follows:-
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name){
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
for(;;)
{
//Output 1: without this sysout statement.
//Output 2: After uncommenting this sysout statement
//System.out.println(Thread.currentThread().isInterrupted());
if(TestThread.i>3)
{
try {
for(int j = 4; j > 0; j--) {
System.out.println("Thread: " + threadName + ", " + j);
}
} catch (Exception e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
}
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
static int i=0;
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i+=4;
System.out.println(i);
}
}
Output without sysout statement in the infinite loop:-
Output with sysout statement in the infinite loop:-
The problem here can be fixed by changing
static int i=0;
to
static volatile int i=0;
Making a variable volatile has a number of complex consequences and I am not an expert at this. So, I'll try to explain how I think about it.
The variable i lives in your main memory, your RAM. But RAM is slow, so your processor copies it to the faster (and smaller) memory: the cache. Multiple caches in fact, but thats irrelevant.
But when two threads on two different processors put their values in different caches, what happens when the value changes? Well, if thread 1 changes the value in cache 1, thread 2 still uses the old value from cache 2. Unless we tell both threads that this variable i might be changing at any time as if it were magic. That's what the volatile keyword does.
So why does it work with the print statement? Well, the print statement invokes a lot of code behind the scenes. Some of this code most likely contains a synchronized block or another volatile variable, which (by accident) also refreshes the value of i in both caches. (Thanks to Marco13 for pointing this out).
Next time you try to access i, you get the updated value!
PS: I'm saying RAM here, but its probably the closest shared memory between the two threads, which could be a cache if they are hyperthreaded for instance.
This is a great explanation too (with pictures!):
http://tutorials.jenkov.com/java-concurrency/volatile.html
When you are accessing a variable value, the changes aren't written to (or loaded from) the actual memory location every time. The value can be loaded into a CPU register, or cached, and sit there until the caches are flushed. Moreover, because TestThread.i is not modified inside the loop at all, the optimizer might decide to just replace it with a check before the loop, and get rid of the if statement entirely (I do not think it is actually happening in your case, but the point is that it might).
The instruction that makes the thread to flush its caches and synchronize them with the current contents of physical memory is called memory barrier. There are two ways in Java to force a memory barrier: enter or exit a synchronized block or access a volatile variable.
When either of those events happens, the cached are flushed, and the thread is guaranteed to both see an up-to-date view of the memory contents, and have all the changes it has made locally committed to memory.
So, as suggested in comments, if your declare TestThread.i as volatile, the problem will go away, because whenever the value is modified, the change will be committed immediately, and the optimizer will know not to optimizer,e the check away from the loop, and not to cache the value.
Now, why does adding a print statement changes the behaviour? Well, there is a lot of synchronization going on inside the io, the thread hits a memory barrier somewhere, and loads the fresh value. This is just a coincidence.
While learning Java concurrency I ran into this behaviour which I can't explain:
public class ThreadInterferrence implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new ThreadInterferrence());
t.start();
append("1", 50);
t.join();
System.out.println(value);
}
private static String value = "";
public void run() {
append("2", 50);
}
private static void append(String what, int times) {
for (int i = 0; i < times; ++i) {
value = value + what;
}
}
}
Why does the program generate random Strings? More importantly why does the length of output vary? shouldn't it always be exactly 100 chars?
Output examples:
22222222222222222222222222222222222222222222222222
1111111111111111111111111111112121112211221111122222222222222
etc..
Reason is you have two threads.
Main thread which is appending to same value string
ThreadInterferrence Thread which is appending again to same value String.
It's Operating System (OS) who is scheduling which thread to run when and hence you see random output. So in your case, OS schedules your runnable to run for a time being which prints 1 and then tries to run main thread which in turn prints 2.
On the topic of your updated question (why does the length of output vary? shouldn't it always be exactly 100 chars?)
The behavior will be unpredictable, since the re-assignment of the new String is not atomic. Note that Strings are immutable and you keep reassinging a value to a variable. So what is happening is one thread gets the value, the other thread also gets the value, one thread adds a character and writes it again but so does the other thread with the old value. Now you're losing data because the update from one of the threads is lost.
In such a case you could use a StringBuffer which is thread-safe, or add synchronization which I'm sure you'll learn about.
[Question] More importantly why does the length of output vary?
[Answer] The variable "value" is being used by multiple threads (Main thread as well as the other thread). Hence the method which is used to change the state of the variable needs to be thread safe to control the final length. That is not the case here.
I was wondering if it was okay that you give a thread access to an instance of a class
so you can perform operations on certain members/variables of that class.
For example, I have both a main thread and a thread.
I'm giving the second thread access to the instance of the main class
so I can perform an operation on x.
However, what if at some point in the future I decide to do operations on x
in the main thread? Or just simply reading from x. What if both the other thread and the main
thread want to read x at the same time?
Is this at all okay by the way I have it structured in my code to do?
package test;
import java.lang.Thread;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
class AThread extends Thread {
Test test;
AThread(Test test) {
this.test = test;
}
BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
public void run() {
String msg;
while ((msg = queue.poll()) != null) {
// Process the message
//System.out.println(msg); //should print "hello"
if (msg.equals("up")) {
test.setX(test.getX()+1);
System.out.println(test.getX());
}
}
}
}
public class Test {
AThread aThread;
private int x = 5;
void setX(int x){
this.x = x;
}
int getX(){
return x;
}
Test() throws InterruptedException{
System.out.println("MainThread");
aThread = new AThread(this);
aThread.start();
while (true) {
aThread.queue.put("up");
}
}
public static void main(String[] args) throws InterruptedException {
new Test();
}
}
And not just the member 'x', but also there could be more members in class "Test" that I'd want to be able to perform operations on such as reading/writing.
Is this an okay structure to do so? If not, what should be fixed?
There are several problems with your code.
Consider this line:
aThread = new AThread(this);
It is always a bad idea to pass this somewhere in a constructor. And this has nothing to do with the threads... yet. The reason is that the 'somewhere' may call a method on this, and the method could be overridden in a subclass whose constructor wasn't called yet, and it may end up in disaster because that override may use some of the subclass fields that aren't initialized yet.
Now, when threads come into the picture, things get even worse. A thread is guaranteed to have correct access to a class instance that was created before the thread is started. But in your case, it isn't created yet, because the constructor is not finished yet! And it's not going to finish anywhere soon because of the infinite loop below:
while (true) {
aThread.queue.put("up");
}
So you have an object creation running in parallel to a startup of a thread. Java doesn't guarantee that the thread will see the initialized class in such case (even if there was no loop).
This is also one of the reasons why starting threads in constructors is considered a bad idea. Some IDEs even give a warning in such cases. Note that running infinite loops in constructors is probably a bad idea too.
If you move your code into a run() kind of method and do new Test().run() in main(), then you code will look fine, but you are right to worry about
However, what if at some point in the future I decide to do operations
on x in the main thread?
The best idea is for the main thread to forget about the object right after it is passed to the thread:
public static void main(String[] args) throws InterruptedException {
AThread aThread = new AThread(new Test());
aThread.start();
while (true) {
aThread.queue.put("up");
}
}
However, what if at some point in the future I decide to do operations on x in the main thread? Or just simply reading from x. What if both the other thread and the main thread want to read x at the same time?
Any time you are sharing information between two threads, you need to provide for memory synchronization. In this case, if you make int x be volatile int x then your code should work fine. You should read the Java tutorial on the subject.
However, if the thread is doing more complex operations, as opposed to just setting or getting x, then you may need to make the method be synchronized or otherwise provide a mutex lock to make sure that the 2 threads don't overlap improperly.
For example, if you need to increment the value of x, a volatile won't help since increment is actually 3 operations: get, increment, and set. You could use a synchronized lock to protect the ++ or you should consider using an AtomicInteger which handles incrementAndGet() methods in a thread-safe manner.
#Segey's answer gives some great feedback about the rest of your code. I'll add one comment about this code:
while (true) {
aThread.queue.put("up");
}
You almost never want to spin like this. If you want to do something like this then I'd add some Thread.sleep(10) or something to slow down the adding to the queue or make the queue bounded in size. It is likely that you are going to run out of memory spinning and creating queue elements like this.