Using volatile variables in j2me

Hi
I was wondering what are the consequences of using volatile variables in j2me application.
Can someone elaborate on the issue?

Not sure what you mean by consequances but I use them for basically communicating with Threads with good success.
Do you have some specific concerns about them?

Similar Messages

  • Using a variable in two threads...

    i am new to java and have a thread question.
    i am using a GUI and then run a swingworker thread to get updates from a server on a regular basis.
    i realize that if the GUI is updated within the swingworker thread i need to use the invokeLater to put it on the EDT.
    but what if i have a boolean variable declared in the main class that i use within the swingworker thread.
    in other words both the EDT and the swingworker thread might use or set the variable.
    does this variable need to be declared in any special way?
    boolean isOn = false; (how i am declaring)
    so one case would be where the EDT sets the variable true or false and the swingworker thread simply checks the state of the variable.
    if (isOn) (do this);
    else (do that);
    in another case both the EDT and the swingthread check and set the var.
    if (isOn) { Thread.sleep(10);}
    isOn = true;
    isOn = false;
    im new to java so just trying to see if this is ok and if i need to declare isOn as syncronized or something.
    not sure if this will work

    There's no need to use both volatile and
    synchronized. Either declare the variable as volatile
    (*), or use synchronization when reading/writing it.
    (*) At least in theory, I'm not sure this has ever
    been guaranteed to work in practice. In any case,
    volatile is superfluous if you use synchronization.You need to use volatile keyword if do not want that compiler optimizes
    you code in multithread applications.
    For example:
        private boolean isDataChanged;
        void setDataChanged(boolean dataChanged){ isDataChanged = dataChanged; }
        boolean isDataChanged(){ return isDataChanged; }
        void someMethod(){
         isDataChanged = false;
         // some code which does not change isDataChanged variable
         if(isDataChanged){
             // code block 1
         }else{
             // code block 2
        }Compiler can optimize someMethod method to the next code because
    isDataChanged is false in if-else statement:
        void someMethod(){
         isDataChanged = false;
         // some code which does not change isDataChanged variable
         // code block 2
        }But isDataChanged viariable can be changed by another thread
    in multifreads applications so optimization will not be correctly
    because isDataChanged can be true in if-else statement.

  • Can operations on volatile variables be reordered

    Hi everybody,
    I am reading "Java Threads 3rd edition"(Oreilly). The book covers J2SE1.5 so it must also cover thread programming in the new JMM.
    In chapter5 at "The effect of reodering statements", there is an example code as shown below.
    public int currentScore, totalScore, finalScore;
    public void resetScore(boolean done){
      totalScore += currentScore;
      if(done){
         finalScore = totalScore;
         currentScore = 0;
    public int getFinalScore(){
      if(currentScore == 0)
         return finalScore;
      return -1;
    }Then the author explain that this can be a problem if JVM decide to do some reordering.
    Thread1: Update total score
    Thread1: Set currentScore == 0
    Thread2: See if currentScore == 0
    Thread2: Return finalScore
    Thread1: Update finalScore
    Then the author state that
    *"It doesn't make any different whether the variables are defined as volatile: statements that include volatile variables can be reordered just like any other statements"*
    As far as I know, if the currentScore is volatile then JMM must guarantee the happens-before relationship. If the second thread see the update of currentScore then the write to finalScore must happens before the write to currentScore and the second thread should return the correct value of finalScore.
    Do I misunderstand something?
    Regards,
    Chatchai Chailuecha
    www.devguli.com

    It used to be that volatile variable access only had a happens-before relationship with each other, but other non-volatile variable accesses could be re-ordered. Under the new JMM, volatile variable access is similar to synchronization, in that everything done before the write to a volatile variable is guaranteed to be visible to a thread that later does a read of that volatile variable. A volatile variable access can be thought of as a barrier across which instructions can not be reordered. So I think the author's statement is wrong under the new JMM.
    More here: http://www.ibm.com/developerworks/library/j-jtp03304/#2.0

  • Can volatile variable be called as static variable for threads?

    I am trying to understand volatile variable, and it's uses. I was thinking of using it to make it shared variable between threads, but not between object instances.
    public class VolatileExample extends Thread {
      volatile int x = 1;
      public void f() {
           x++;
           System.out.println(Integer.toString(x));
        public void run() {
              for(int i = 0; i<20;i++){
                   f();
                   try { Thread.sleep(500); } catch(InterruptedException e) {}
        }now, if I create two threads in main method of the same VolatileExample class, say T1 and T2, how many times would volatile int x be instanciated? would there be just one copy of volatile int x created, no matter howmany threads I create?

    WHICH REMINDS ME: YOU DIDN'T ANSWER MY QUESTION AS TO
    WHETHER YOU UNDERSTAND THREADS' LOCAL COPIES OF
    VARIABLES VS. THE MAIN MEM COPYIn my understanding,
    local copies means each thread gets their own copy of a variable and they play with it separately. changing this variable in one thread does not chage value for another thread.
    main mem copy is the one accessed by all the threads. If one thread changes this value, it is reflected to all other threads using this variable.
    right?
    I tried using voaltile variable as shared variable like this:
    import java.io.*;
    public class VolatileIncrement {
      private int x = 1;
      public void f() {
           x++;
           System.out.println(Integer.toString(x));
      public String toString() { return Integer.toString(x); }
      class MakeThread extends Thread{
           public MakeThread(){
                System.out.println("starting MakeThread thread");
         public void run() {
              for(int i = 0; i<20;i++){
                   f();
                   try { Thread.sleep(500); } catch(InterruptedException e) {}
      public void createT() {
         Thread T2 = new MakeThread();
              T2.start();
         Thread T1 = new MakeThread();
              T1.start();
    }and created another class:
    import java.io.*;
    class TestVolatile
         public static void main(String[] args)
              VolatileIncrement vi = new VolatileIncrement();
              System.out.println("creating threads now...");
              vi.createT();
              System.out.println("Done Testing!!");
    }can this be called as correctly using non-static volatile variable as shared data?

  • Atomic operation and volatile variables

    Hi ,
    I have one volatile variable declared as
    private volatile long _volatileKey=0;
    This variable is being incremented(++_volatileKey)  by a method which is not synchronized. Could there be a problem if more than one thread tries to change the variable ?
    In short is ++ operation atomic in case of volatile variables ?
    Thanks
    Sumukh

    Google[ [url=http://www.google.co.uk/search?q=sun+java+volatile]sun java volatile ].
    http://www.javaperformancetuning.com/tips/volatile.shtml
    The volatile modifier requests the Java VM to always access the shared copy of the variable so the its most current value is always read. If two or more threads access a member variable, AND one or more threads might change that variable's value, AND ALL of the threads do not use synchronization (methods or blocks) to read and/or write the value, then that member variable must be declared volatile to ensure all threads see the changed value.
    Note however that volatile has been incompletely implemented in most JVMs. Using volatile may not help to achieve the results you desire (yes this is a JVM bug, but its been low priority until recently).
    http://cephas.net/blog/2003/02/17/using_the_volatile_keyword_in_java.html
    Careful, volatile is ignored or at least not implemented properly on many common JVM's, including (last time I checked) Sun's JVM 1.3.1 for Windows.

  • Stopping two threads through a volatile variable

    Hello,
    I have a client application receiving messages from a server. As the code is now, a thread is started twice. The thread class is inheriting an isAlive boolean variable used in the while loop in the run method (where the specific processing is performed). When it's time to kill the thread, the isAlive variable is set to false, but at least one of the threads keeps running. From what I understood [how volatile variables work|http://www.javaperformancetuning.com/news/qotm030.shtml] , this should not be happening - one call to the kill() method should make both threads stop, as they are using a synchronized variable value. What am I doing wrong?
    The following code is reduced to the relevant parts (hopefully):
    // this block is executed within a method that processes received messages. There is always two OPT messages received (but with different further parameters), so the thread is started twice.
    if ( receivedMessage == OPT ) {
        thread = new Thread() // sets isAlive to true
        thread.start()
    // run method
    ...public void run() {
           while(isAlive) {
              ... do stuff
    // kill method in the thread superclass
    public void kill() {
        isAlive = false;
    // killing the thread
    thread.kill();

    ... [how volatile variables work|http://www.javaperformancetuning.com/news/qotm030.shtml] ...
    hmm are you sure that stuff at above link is up-to-date?
    I ask because it is dated 2003 but volatile in Java 5 and newer conforms to specification that was finalized in 2004 ([JSR 133 Java Memory Model|http://www.jcp.org/en/jsr/detail?id=133|jcp])

  • Fixing Double-Checked Locking using Volatile

    Oooh - what a scandalous subject title! :)
    Anyhow, I was expanding my knowledge on why the double-checked locking idiom used in Singleton classes fails (after reading that JSR-133 is not going to fix the problem!), when I read http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html and found a spicy section titled "Fixing Double-Checked Locking using Volatile" (at the very bottom of the document).
    As it is quite hard to find information (all sources revisit all the basic problems), I was wondering if anybody could back this up/refute it.
    Just one more thing. I anticipate that many people who are researching this matter would like to have this clarified, so it would be beneficial to keep posts very much on topic. There is already a lot of information available about double locking failures in general.
    The problem this post faces lies in a lot of statements saying "using volatile will NOT fix double-checked locking" that refer (I think) to the current JDK.
    Thanks heaps!

    Volatile only checks that not more than one thread is accessing the variable at the same time (amongst other things of course), so in the example, it could cause problems. Let me explain a little here. Given a situation where two threads wish to aquire the Helper:
    Step 1: Thread 1 enters the method and checks the helper status
    and sees that it is null.
    private volatile Helper helper = null;
    public Helper getHelper() {
      if (helper == null) { // <!-- Thread 1 requires helper, and sees that it is null
         synchronized(this) {
            if (helper == null)
               helper = new Helper();
       return helper;
    }Step 2: Thread 2 enters the method, before the lock can be
    acquired on the this-object and notices that the helper is
    null.
    private volatile Helper helper = null;
    public Helper getHelper() {
      if (helper == null) { // <!-- Thread 2 requires helper also
         synchronized(this) { // and it is still null
            if (helper == null)
               helper = new Helper();
       return helper;
    }Step 3: The first Thread creates a new Helper
    private volatile Helper helper = null;
    public Helper getHelper() {
      if (helper == null) { // <!-- Thread 2 waiting for lock realeas
         synchronized(this) {
            if (helper == null)
               helper = new Helper(); // <!-- Thread 1 creating new Helper
       return helper; //
    }Now for Step 4, there are a few possibilites here. Either Thread 1 returns the helper it created, or Thread 2 can create the new Helper before the Thread 1 returns the Helper. Either way, the result is unwanted.
    private volatile Helper helper = null;
    public Helper getHelper() {
      if (helper == null) {
         synchronized(this) {
            if (helper == null)
               helper = new Helper(); // <!-- Thread 2 creating new Helper
       return helper; // <!-- Thread 1 returning Helper
    }The code can also create interesting situations (deadlocks?) due to the synchronized(this) statement used in a ... creative way in this case.
    I might be wrong of course. Just my �0.02.
    Tuomas Rinta

  • Using a variable in communication channel

    Hi,
    I have a lot of Communication Channels looking for files in the same directory. This directory's path will be changed soon and so I assume I'll have to change all my Communication Channels.
    I was wondering whether there was a means of using a variable for the Source Directory in order to just have to change its value where it is defined and not every where it is used...
    Regards
    Yann

    Hi,
    Is this a sender file adapter? or a receiver file adapter?
    You can make a change / make the receiver file adapter's directory dynamic by setting the value during runtime in the mapping.
    Use  this blog and the code in the blog to acheive this,
    /people/michal.krawczyk2/blog/2005/11/10/xi-the-same-filename-from-a-sender-to-a-receiver-file-adapter--sp14
    Sender File adapter, I dont think this is possible.
    Regards,
    Bhavesh

  • Error in using System Variable

    Dear all,
             I want to use System Variable 225 ( VAT percent (per VAT code) ) which is used in one of document i.e. "VAT Only Invoice".
    When I used it in my Invoice document the following error occurs:
    Printing Error : Invalid Variable number (RPT -6300)(Field:F_XXX) Variable 'XXX'
    Please help me to use this System Variable in my Invoice.
    Note: I have already read "How To Use the PLD Variables File in Release 2007 A" .pdf file.
    can any one tell the meaning of folowing which is in the sheet "vars utilisation" of PLD_Vars_march2007 xls file
    " it means that this variable can be used only under certain repetitive area exclusive numbers (109, 126, 132, 135, 139, 148, 149, 309, 316, 427, 502, 509, 686)
    Regards,
    Ghazanfar
    Edited by: Ghazanfar Ahmed on Jun 18, 2009 12:16 PM

    Hi,
    It is a special variable available for the VAT summary part, not to be used in the rows but in a separate repetitive area.
    To display the respective VAT rates in each row, create a database field instead: Tax Definition - Rate%. It will populate the VAT percentage for you.
    Regards,
    Nat

  • Error in using a variable in filter condition in an Interface

    Hi All,
    I am using a variable in my interface in a filter condition. I have an EMP table of scott schema and want to pull all the records wiht hiredate date lying between 2 dates, incremental pull.For this I have created 2 variables and using them in the filter condition. I am getting an error inthe interface when I run in a package after declaring and refresing the variables.
    com.sunopsis.sql.SnpsMissingParametersException: Missing parameter
         at com.sunopsis.sql.SnpsQuery.completeHostVariable(SnpsQuery.java)
         at com.sunopsis.sql.SnpsQuery.updateExecStatement(SnpsQuery.java)
         at com.sunopsis.sql.SnpsQuery.executeUpdate(SnpsQuery.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.execStdOrders(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.treatTaskTrt(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSqlI.treatTaskTrt(SnpSessTaskSqlI.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.treatTask(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessStep.treatSessStep(SnpSessStep.java)
         at com.sunopsis.dwg.dbobj.SnpSession.treatSession(SnpSession.java)
         at com.sunopsis.dwg.cmd.DwgCommandSession.treatCommand(DwgCommandSession.java)
         at com.sunopsis.dwg.cmd.DwgCommandBase.execute(DwgCommandBase.java)
         at com.sunopsis.dwg.cmd.e.i(e.java)
         at com.sunopsis.dwg.cmd.g.y(g.java)
         at com.sunopsis.dwg.cmd.e.run(e.java)
         at java.lang.Thread.run(Unknown Source)
    Regards,
    Krishna

    Hi Krishna,
    What is the datatype of the Variable lastupdate ?
    In my case
    Variable
    Name : LastUpdateDate
    Datatype : Alphanumeric
    Action : Historize
    Query : select to_char(to_date(sysdate,'DD-MON-YY'),'DD-MON-YY') from sys.dual
    Then in filter I used
    EMP.HIREDATE>to_date('#LastUpdateDate','DD-MON-YY')
    Thanks
    Sutirtha

  • Using a variable as a value in jsp:param

    I was wondering, I have a String variable, vid_1, and want to use a jsp:include and pass that in as one of the parameters. How can I do this? I have to do some testing to make sure vid_1 is valid and set a default if not. It contains a number referring to which video needs to be displayed.
    Is there anyway I can get this value to be used in jsp:param value?
    John

    RahulSharna wrote:
    Well,First thing you haven't pharsed your question properly.
    Anyways as per my understading.
    The first thing is make use of in this case as your defined requirement states you need to make use of variables of both the JSP's which need compile time include not at the runtime.use of
    <%@ include file="url" %>would be more appropriate as you want to use the variable of parent jsp to the child one.
    Anyways if you are thinking to apply a solution using <jsp:include/>
    <jsp:include page="url">
    <jsp:param name="paramName" value="<%=stringVariable>"/>
    </jsp:include>and extract the paramName's corresponding value as a request parameter in other JSP.
    Hope that might answer your question :)
    REGARDS,
    RaHuLRaHul,
    Thanks for the reply. The second example you gave is what I was trying to do. I thought I did exactly what you have there and it was not working. I will check it over again and post back on here when I have a chance.
    For now I was trying to use c:set to save the variable in the request and then using the EL expression ${requestScope.variable} to put it in the <jsp:param> element. I had some things working and others not when I quit. Hopefully tomorrow I can give you a full report and we can get this worked out.
    Maybe my problem is something else? Look at this post of mine:
    http://forum.java.sun.com/thread.jspa?threadID=5236252&tstart=10
    Thanks so much for the help.
    John

  • Using a variable in netsh command to set ip address on NIC

    hi friends
    i wrote an script which gets an input & use that variable to set ip address on NIC. but actually it doesn't set ip address. may you please help me.
    my script contains:
    $VMNumber=Read-Host "please enter your VM number (for example 2)"
    Netsh interface ipv4 set address NIC static 192.168.1.$VMNumber

    1. I do not thing that the use of netsh is a right way.
    2. You will need a table with MAC address in first column and IP address in second to correctly map IP address to computer. MAC addresses are unique identification.
    3. Follow this article including comments and adapt scripts to your task
    http://www.powershellpro.com/powershell-tutorial-introduction/powershell-wmi-methods/
    HTH
    Milos
    hi Milos
    thank a lot for your useful answer.
    but let me say that my need has nothing to do with MAC address.
    in my test lab, i need an script which asks the administrators to enter their VM number & it saves this input as a variable & set is as the last octet in their VM IPV4 Address.
    so can we tell it as a rule that variables we create in powershell, can't be used inside non cmdlets (inside legacy cmd commands) ?

  • Using a variable in a js function argument

    Folks,
    This is very basic, but I still cannot get it...
    I have this js function in an ASP page:function MM_changeProp(objId,x,theProp,theValue) { //v9.0
      var obj = null; with (document){ if (getElementById)
      obj = getElementById(objId); }
      if (obj){
        if (theValue == true || theValue == false)
          eval("obj.style."+theProp+"="+theValue);
        else eval("obj.style."+theProp+"='"+theValue+"'");
    }i don't understand the function, as it was put in automatically by dreamweaver. right now, i am using this onclick event of an image:<div id="apDiv19" onclick="MM_changeProp('apDiv7','','backgroundColor','#FFFF00','DIV')"></div>the #FFFF00 is the color YELLOW. it is being passed to the theValue argument of the js. what i simply want to do is establish a global variable that will house a color string (like #FFFF00), and then use it in the function argument everytime i need the function. something like this:<div id="apDiv19" onclick="MM_changeProp('apDiv7','','backgroundColor',VARIABLE,'DIV')">i do not know how to do two things:
    1) initialize and assign the variable a value, and where to establish it (inside the script tags? in the head? in the body?)
    2) how to use the variable as an argument in the function
    any help greatly appreciated for this novice. thanks!

    ajetrumpet wrote:
    Folks,
    This is very basic, but I still cannot get it...
    I have this js function in an ASP page:This forum is not about ASP nor JavaScript. Please use Google to find an appropriate JavaScript forum.

  • Using a variable in an instance name

    Hey all,
    Simple question:
    I'm trying to use a variable to call on different instance names:
    var picCaller:uint=2;
    material_mc.addChild(pic_""+picCaller+"");
    The code in red is the issue in question.  In this example, I'm trying to add a child called "pic_2", with the number two called from the variable "picCaller"
    Any assistance is greatly appreciated.
    Thanks!

    Just for context, here is what I'm trying to do:
    I have jpegs in my library and I want to add them to the stage when they're needed, so just to add one image, here is the code I have:
    var pic_1=new pic1(0,0);
    var image_1:Bitmap=new Bitmap(pic_1);
    material_mc.addChild(image_1);
    I want to put the above into a loop so that I dont have to repeat those three lines for every image in my library like so:
    var pic_1=new pic1(0,0);
    var image_1:Bitmap=new Bitmap(pic_1);
    var pic_2=new pic2(0,0);
    var image_2:Bitmap=new Bitmap(pic_2);
    var pic_3=new pic3(0,0);
    var image_3:Bitmap=new Bitmap(pic_3);
    var pic_4=new pic4(0,0);
    var image_4:Bitmap=new Bitmap(pic_4);
    var pic_5=new pic5(0,0);
    var image_5:Bitmap=new Bitmap(pic_5);
    var pic_6=new pic6(0,0);
    var image_6:Bitmap=new Bitmap(pic_6);
    var pic_7=new pic7(0,0);
    var image_7:Bitmap=new Bitmap(pic_7);
    the variable "picNum" is the total amount of images that in the library, each one exported as "pic1", "pic2", "pic3" respectively.
    var picNum:uint=7;
    var picCaller:uint=1;
    var  picMC:MovieClip = new MovieClip();
    picMC=this["pic_"+picCaller];
    for (var  i:int = 1; i <= picNum; i=i+1)
         var "pic_"+i = new image_i(0,   0);
         var image:Bitmap = new Bitmap("pic_"+i);
    Thanks so much for your help.

  • Using a variable in SQL to store intermediate results

    I'm new to Crystal Reports, so pardon my ignorance.
    I need to write a SQL statement in Crystal Reports (Ver. 11) that uses results from a query and stores them in a variable for further use in the statement. Something like this:
    DECLARE @my_variable INT;
    SET @my_variable=
    CASE
                    WHEN DATEPART (m,{?Date})<7
                    THEN DATEPART (yyyy,( DATEADD (year,-1, {?Date})))
                    ELSE DATEPART (yyyy,( DATEADD (year,0, {?Date})))
    END
    (Where {?Date} is a date parameter)
    Is it possible to achieve this in the above form or some other form in Crystal Reports?
    Thanks

    Simple answer... When I used the variable, I marked it as a string.  There is an email address setting.

Maybe you are looking for

  • Need help with sharing - Can't see shared playlist

    I have my songs on a Windows 7 Pro 64 bit computer. I turned on home sharing and selected a playlist to be shared. I'm trying access the shared content on a Windows XP and a Vista machine, but I cannot see the shared playlist. The Vista machine can s

  • Having problem with textHeight

    Hi, I'm trying to create a menu like a list. Data are from XML (ASP). The problem is I just can't tell Flash to use the textHeight data for calculating the distance between two items. When I trace the textHeight, the data is correct, but the final lo

  • Any tutorials/demos available for using BPEL alongwith Struts or JSF

    Hi All Are there any sample tutorials/demos available for using BPEL alongwith Struts or JSF ? Thanks Badri

  • Removing "REMINDERS" from Mail sidebar

    Hello, is there a way to remove the right arrow with the REMINDERS from the Mail sidebar?  I have no use for them and it would clean up the list.  Thanks!

  • Is second HDD in Satellite A300D possible?

    Hello. I found in the laptop compartment for a second hard drive, but did not understand whether it pop in a second hard drive. Maybe someone is trying to turn. Thanks in advance. PS: Sorry for English - interpreter)