473,320 Members | 1,858 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,320 developers and data experts.

Java thread essentials

1> What is reordering of statements in a single thread.

Ans. Compiler/JVM reorder the statements in a particular thread so that it does not affect the code semantics for single thread execution. For example see the following code.
Expand|Select|Wrap|Line Numbers
  1. class A{
  2.  
  3.     private int k = 0;
  4.     private boolean l = false;
  5.     public void example(int a, boolean b){
  6.         k = a;//....  Line 1
  7.         l = b;//....  Line 2
  8.  
  9.     }
  10.  
  11.     public void show(){
  12.         System.out.println(k);//.... Line 3
  13.         System.out.println(l);//.... Line 4
  14.     }
  15.  
  16.     public static void main(String args[]){
  17.  
  18.         A a = new A();
  19.         a.example(3,"true");
  20.         a.show();
  21.  
  22.     }
  23. }
  24.  
  25.  
Scenario 1: Here the order of Line 1 and Line 2 to execute is not at all important. Because they do not depend on one another. So they may be reordered. Now it is very normal that in the main thread the order of execution of the lines are 2,1,3,4.
So output will be
3
true

But the order of execution in the method show() can never be reordered. Because that will change the method semantics. Then the result would be as below
true
3
But this was not the intent of the program. So this would never happen.

Scenario 2: But scenario may be different when two threads act together. Say two threads are started in the main thread. Thread 1 executes method a.example(..) and Thread 2 executes a.show()

Here the execution may very well be in the order as below.
2,3,4,1
Now the output is as below
0
true

That means k is assigned before l.
So this is not exactly what we wanted right?

2> How to stop reordering?

Ans. If the variables k and l are declared as volatile this reordering may be stopped.

Let me rewrite the code again
Expand|Select|Wrap|Line Numbers
  1. class A{
  2.  
  3.     private volatile int k = 0;
  4.     private volatile boolean l = false;
  5.  
  6.     public boolean getL(){
  7.         return l;
  8.     }
  9.     public void example(int a, boolean b){
  10.         k = a;//....  Line 1
  11.         l = b;//....  Line 2
  12.  
  13.     }
  14.  
  15.     public void show(){
  16.         System.out.println(k);//.... Line 3
  17.         System.out.println(l);//.... Line 4
  18.     }
  19.  
  20.     public static void main(String args[]){
  21.  
  22.         A a = new A();
  23.  
  24.         //code is omitted.
  25.         /*a.example(3,true) is run in thread1*/
  26.         /*a.show() is run in thread2*/
  27.  
  28.     }
  29. }
  30.  
Think about scenario 2. I repeat here: Thread 1 is executing a.example() and Thread 2 is executing a.show().
Now one possible ordering may be as below
1,3,4,2

Then output is as below
3
False

Here 1 has executed before 2. The reordering has been stopped. Because if the variables are volatile they are accessed in the same order as the code is written.

But did we want this? We needed to see both the values 3 and "True" assigned.

3> How to do this?

Inside the run method of Thread 2 we may add this

Expand|Select|Wrap|Line Numbers
  1. if(a.getL()){
  2.     a.show();
  3. }
  4.  
Here the lines executed by both the threads will be in following order
1,2,3,4
Also the output will be as follows
3
true

4> Now one tricky question.

Say we have 3 variables j,k and l. I write the class as follws

Expand|Select|Wrap|Line Numbers
  1. class A{
  2.  
  3.     private volatile int j = 0;
  4.     private volatile int k = 0;
  5.     private volatile boolean l = false;
  6.     public void example(int a, boolean b){
  7.         j = a;//....  Line 1
  8.         k = a;//....  Line 2
  9.         l = b;//....  Line 3
  10.  
  11.     }
  12.     public boolean getL(){
  13.         return l;
  14.     }
  15.     public void show(){
  16.         System.out.println(j)//...  Line 4
  17.         System.out.println(k);//.... Line 5
  18.         System.out.println(l);//.... Line 6
  19.     }
  20.  
  21.     public static void main(String args[]){
  22.  
  23.         A a = new A();
  24.  
  25.         //code is omitted.
  26.         /*a.example(3,true) is run in thread1*/
  27.         /*a.show() is run in thread2*/
  28.  
  29.     }
  30. }
  31.  
So if inside the run() method of thread 2 we write as the previous scenario

Expand|Select|Wrap|Line Numbers
  1. if(a.getL()){
  2.     a.show();
  3. }
  4.  
The result will be ordered. Order of execution will be
1,2,3,4,5,6 and output will be
3
3
true

Here is the question. For the same output can the order of execution be as below?
2,1,3,4,5,6
The answer is "Yes". So j and k must be assigned before l. But it is not necessary that j is assigned before k.

So j and k may be non-volatile. Only l needs to be volatile.

5> What is volatile?

Answer:
1> When a volatile variable is written into memory (assigned some value) it is ensured that all the previous assignments/memory writes in the code in the same thread must occur before this write of the volatile variable.
2> Whenever volatile variable is read it must be read from memory. That's why it may see the value, which has been written just before this read.
3> Whenever they are written they are written to memory rather than local cache of the thread.

There are some other things about volatile. I will come up with them in my next article.
Sep 15 '13 #1
0 4714

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Chris Morgan | last post by:
I'm trying to get php to run on my webserver as a Java Servlet, it works the first time but fails the second time and crashes the JVM with the following error: I have tried the latest versions...
5
by: Dhananjay Singh | last post by:
Dear All, There are lot of questions in mind regarding Green Thread. I'd like to know what is green thread? What is the difference between Green Thread and Native Thread? On linux platform...
77
by: Jon Skeet [C# MVP] | last post by:
Please excuse the cross-post - I'm pretty sure I've had interest in the article on all the groups this is posted to. I've finally managed to finish my article on multi-threading - at least for...
11
by: DrUg13 | last post by:
In java, this seems so easy. You need a new object Object test = new Object() gives me exactly what I want. could someone please help me understand the different ways to do the same thing in...
2
by: ramasubramanian.rahul | last post by:
hi i am trying to call some java APIs from c . i use the standatd JNI calls to load the JVM from a c program and call all java functions by using a pointer to the jvm which was returned by the JNI...
3
by: ganeshp | last post by:
hi All, I have crated a thread and in that tread i have created one more thread? is it ok to do this ? i am not getting any errors, regards, Ganesh
6
m6s
by: m6s | last post by:
MovAvg run = new MovAvg(_symbol, this, SumDays.SMALL ); threadExecutor.execute(run); Collection<Double> vl = run.getMovAvg().values(); Iterator itr = vl.iterator(); ...
1
by: kokababu | last post by:
Hi I am developing a WebService using Java (JAX-RPC). According to the requirement, I have to create a Thread to insert data into Database. So I am opening a database connection in the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.