473,385 Members | 1,645 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,385 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 4726

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...
1
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
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.