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?

Similar Messages

  • Can i do the calling on landline numbers for cold ...

    can i do the calling on landline numbers for cold calling purpose by skype

    bhardwaj.ankit8 wrote:
    can i do the calling on landline numbers for cold calling purpose by skype
    Hello,
    Firstly ALWAYS start your own topic. To add to a 3-month old unrelated thread which has been resolved long ago is not a good idea and can mean that your query is overlooked.
    You can call to or within any country using either a valid Subscription  provided that you do so within the Fair Use Policy http://www.skype.com/en/legal/fair-usage/ or with Skype Credit.
    Specifically please note the following clause:
    "The following is a non-exhaustive list of practices  that would NOT be considered Legitimate Use:
    Using subscriptions for telemarketing or call center operations"
    TIME ZONE - US EASTERN. LOCATION - PHILADELPHIA, PA, USA.
    I recommend that you always run the latest Skype version: Windows & Mac
    If my advice helped to fix your issue please mark it as a solution to help others.
    Please note that I generally don't respond to unsolicited Private Messages. Thank you.

  • Using variables for answers to fill-in-the-blank questions

    Hello,
    For fill-in-the-blank questions, one has to provide answers. I want to provide these in the form of (user-created) variables, rather than in the form of fixed strings of characters (so then, as $$var1$$ rather than as 'rabbit'). I haven't been able to get this to work. The enter variable function is indeed available (in the properties panel), but it doesn't actually work (i.e. even if you select a variable to be entered, it doesn't actually get entered).
    Is there a way around the problem?
    1. NB that this same issue holds for text entry boxes (rather than fill-in-the-blank questions). If I could get this to work for text entry boxes, I would use them rather than fill-in-the-blank questions.
    2. One can use variables for answers to multiple choice questions. So I'm hoping I can get it to work for fill-in-the-blank questions as well.
    Thank you in advance. Marvin DuBois

    That would have been my suggestion. I don't have a dedicated blog post, but use TEB's for that kind of questions myself as well. And contrary to the widget/interaction I mentioned before, a TEB is an interactive object, which means it can be validated and there can be a score attached to it. But, it will not help you, since you have to add the correct answers in the same way as for a dropdown list in the FIB question (they are sort of TEB's there). And it is that list that doesn't allow to enter a variable instead of a fixed sequence of characters.
    Which means that you are back to the advanced actions, same as in my blog posts with the widget/interaction.
    Have a workaround (after all I am the workaround Queen) to have reporting, if you need to check only one TEB, described here:
    http://blog.lilybiri.com/report-custom-questions-part-2
    The idea is to use another interactive object that can have a score. In reality I use two instances of that same object: one with score 0 and one with score X and show the right one depending on the conditional action.
    However if you want to have multiple TEB's on the same slide, that have to be checked all with the same advanced action, than you'll need either the Mastery widget by InfoSemantics (only for SWF output) or Javascript.
    Lilybiri

  • My iPhone 4 shows the carrier name, I can go online with my data plan, but there are no bars and I can't make phone calls.

    My iPhone 4 shows the carrier name, I can go online with my data plan, but there are no bars and I can't make phone calls.
    It worked for some time, less than a week, I made phone calls and all, and all of a sudden the problem mentioned above happened. Now I can't make any phone calls. I can go online with it, even with my Data plan, I can go to the app store (of course) but can't make any phone calls.
    Please help, this is frustrating.

    Did you already try the troubleshooting mentioned here? http://www.apple.com/support/iphone/assistant/calls/
    Also try to reset the phone by holding the sleep and home button until the Apple lo comes up again. You will not lose any data doing this.
    Message was edited by: Ingo2711

  • 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

  • BO Webi: How to populate a variable with the set of static values for Graph

    Hi All,
    I have the data: Order number, Order Date, processing time coming from the SAP Bex query in the below format:
    Order No    Order Date    Processing time (Days)
    1                 Jan-2011      4
    2                 Jan-2011      5
    3                 Feb-2011      6
    In BO webi report, I have to report the number of orders which were processed in <1day, <2days, <3days,...<10days in a graphical view. i.e., X-Axis:  <1day, <2days, <3days,...<10days(10 static buckets for the processing days)
    Y-Axis: Number of Orders.
    The graphical output should be like below:
    X-Axis: <1day, <2days, <3days,<4days,<5days,<6days,<7days,<8days,<9days,<10days
    Y-Axis: 0, 0,0,0,1,2,3,3,3,3  (count(Order No)) (Cumulative count)
    I am able to calculate the number of orders individually for each of the 10 buckets. But the problem i am facing is that I am not able to hold the 10 static bucket values in a variable to use it for the x-axis in the Graph, as these 10 static bucket values are not coming from the backend source.
    I would like to know if there is way to populate a variable(to use it for the X-Axis in the graph) with the set of 10 static values.
    Any help would be highly appreciated.
    Thanks,
    Leela

    Hi ,
    I think we can use the variable as X-axis in chart.. but Variable Qulaification should be Dimension.
    can you try this?.
    Using efasion universe
    1) Select month and Sold at (unit price) , then run the query
    2) create the variable V_Month ==If [Month]=1 Then "Month1" Else "Month2"  (Note = Variable Qulaification should be Dimension)
    3) Create the variable V_Sum= sum (Sold at (unit price))
    4) create another variable V_Cumulative_Sum==[V_Sum]+Previous([V_Sum])
    Now add V_Month and V_Cumulative_Sum in table , then convert to chart.. now you can add the variable V_Month as X-axis of the chart.
    Hope this will help:)
    Thanks
    Ponnarasu K

  • What are Parameters? How are they differenet from Variables? Why can't we use variables for passing data from one sequnece to another? What is the advantage of using Parameters instead of Variables?

    Hi All,
    I am new to TestStand. Still in the process of learning it.
    What are Parameters? How are they differenet from Variables? Why can't we use variables for passing data from one sequnece to another? What is the advantage of using Parameters instead of Variables?
    Thanks in advance,
    LaVIEWan
    Solved!
    Go to Solution.

    Hi,
    Using the Parameters is the correct method to pass data into and out of a sub sequence. You assign your data to be passed into or out of a Sequence when you are in the Edit Sequence Call dialog and in the Sequence Parameter list.
    Regards
    Ray Farmer

  • 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?

  • 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])

  • Can not call a static function with-in a instance of the object.

    Another FYI.
    I wanted to keep all of the "option" input parameters values for a new object that
    i am creating in one place. I thought that the easiest way would be to use a
    static function that returns a value; one function for each option value.
    I was looking for a way to define "constants" that are not stored in
    the persistent data of the object, but could be reference each time
    the object is used.
    After creating the static functions in both the "type" and "body" components,
    I created the method that acutally receives the option input values.
    In this method I used a "case" statement. I tested the input parameter
    value, which should be one of the option values.
    I used a set of "WHEN conditions" that called the same
    static functions to get the exact same values that the user should
    pass in.
    When I try to store this new version, I get the error:
    "PLS-00587: a static method cannot be invoked on an instance value"
    It points to the first "when statifc_function()" of the case function.
    This seems weird!
    If I can call the static method from the "type object" without creating
    and instance of an object, then why can't I call it within the body
    of a method of an instance of the object type?
    This doesn't seem appropriate,
    unless this implementation of objects is trying to avoid some type
    of "recursion"?
    If there is some other reason, I can not think of it.
    Any ideas?

    Sorry for the confusion. Here is the simplest example of what
    I want to accomplish.
    The anonymous block is a testing of the object type, which definition follows.
    declare
    test audit_info;
    begin
    test := audit_info(...);
    test.testcall( audit_info.t_EMPLOYER() );
    end;
    -- * ========================================== * --
    create or replace type audit_info as object
    ( seq_key integer
    , static function t_EMPLOYER return varchar2
    , member procedure test_call(input_type varchar2)
    instantiable
    final;
    create or replace type body audit_info
    as
    ( id audit_info
    static function t_EMPLOYER return varchar2
    as
    begin
    return 'EMPLOYER';
    end;
    member procedure test_call(input_type varchar2)
    as
    begin
    CASE input_type
    WHEN t_EMPLOYER()
    select * from dual;
    WHEN ...
    end case;
    end;
    end;
    The error occurs on the "WHEN t_EMPLOYER()" line. This code is only
    an example.
    Thanks.

  • How can I use variable for a package filename and target file inODIFileMove

    I want to use a variable for paths so that when I migrate from Dev to QA to Prod I don't have to do a lot of editing.
    Specifically, I want a variable to be the first part of the path for the filename (\\sundev1\fnd1-hypd1) and join this with the rest (\update\log\*.log or specific filename) using several different objects like the ODIFileMove, ODI OS Command, OS Command, etc.
    Thank you!

    Hi,
    you could set up a database table holding processing parameters (i.e. Column1 - ParamName, Column2 - ParamValue).
    One row could then be ParamName = FilePath, ParamValue = \\<server>\folder\
    So, the refreshing query (attached to a logical schema) would be something like SELECT ParamValue FROM <your table> WHERE ParamName ='FilePath'
    Then, create a variable which can refresh from the database and in the package, drop the variable onto the flow and set it's type to 'Refresh Variable' in the properties.
    Hope this helps.
    geeo

  • Can i Create Output Variable for DB Polling in BPEL 11g?

    Hi Team,
              I want to create the Output Variable for DB Polling,But when i double click on Reply Activity-->Create New Variable it is giving error message like "Can't Create output variable.The Selected operation doesn't have an Output Message".
    My Question is Can we create Output Variable for DB Polling, if Yes tell me the procedure to create the Output variable ?
    Regards,
    Kiran

    Hi Kiran,
    In these scenario generally runtime faults occurs so you can use the CatchAll activity and rethrow activity to complete the instance in error state. Also before the completion of the process if exception occurs you can rollback all the transaction.
    or
    you can use the Fault handling framework:
    Using Fault Handling in a BPEL Process - 11g Release 1 (11.1.1.7)
    Regards,
    Anshul

  • Can we create range variable for Query Key Date

    Hello Gurus,
    Can we create a range variable for Query Key Date ? when I tried to give a range of values for Query Key Date, I am unable to find Range Values option. I found only Single Values.
    so, Please let me know if we can use Range variables for Query Key Date ??
    Thanks in advance,
    Regards,
    Aarthi

    Hi Aarthi,
    This is relevant for the time dependant master data that is being pulled in thw query. Like if you are using a nav attr in the query and this nav attr is time dependant, then which record (from the char master data) is to be pulled into the report, depends upon the key date that you specify.
    The default key date value is the date on which the query is executed, that is <Today>.
    Hope this helps...

  • How to use the dynamical or static variable for ESSBASE cube name?

    Hi Experts,
    When I import ESSBASE Cube into physical layer, the cube name from ESSBASE is created automatically, such as H_Sales.
    I want to use the the static or dynamical variable for replacing the external name. So I try to create the static variable in RPD,such as cubeName, and use the following code
    'VALUEOF(cubeName)' into the textbox of external name.
    However, when I view the report in answer, it will generate the error message: Database VALUEOF(cubeName) does not exist.
    Is it possible to implement this functionality?
    Thanks..

    Hi,
    use <%=odiRef.getSchemaName("D")%>
    D as parameter if it is the Data Schema or W if you need the schema from Work Schema
    Your command will be like:
    select <%=odiRef.getSchemaName("D")%>.GER_LOT_EXEC_ODI('Fluxo', 1, 'C') FROM DUAL
    Works?
    Cezar Santos
    http://odiexperts.com

  • Can we call a static method without mentioning the class name

    public class Stuff {
         public static final int MY_CONSTANT = 5;
         public static int doStuff(int x){ return (x++)*x;}
    import xcom.Stuff.*;
    import java.lang.System.out;
    class User {
       public static void main(String[] args){
       new User().go();
       void go(){out.println(doStuff(MY_CONSTANT));}
    }Will the above code compile?
    can be call a static method without mentioning the class name?

    Yes, why do it simply?
    pksingh79 wrote:
    call a static method without mentioning the class name?For a given value of   "without mentioning the class name".
        public static Object invokeStaticMethod(String className, String methodName, Object[] args) throws Exception {
            Class<?>[] types = new Class<?>[args.length];
            for(int i=0;i<args.length;++i) types[i] = args==null?Object.class:args[i].getClass();
    return Class.forName(className).getDeclaredMethod(methodName,types).invoke(null,args);

Maybe you are looking for

  • Using real instruments on Powerbook G4

    Hi, I've been using garageband on my ibook for over a year now and thought that I would try using it on my sister's PowerBook G4. The program works fine with software instruments, but when I plug my gutiar into it and try to use other real instrument

  • Invalid Class Exception problem

    Hi whenever i try to run this method from a different class to the one it is declared in it throws invalid class exception, (in its error it says the class this method is written in is the problem) yet when i run it from its own class in a temporary

  • Problem with Presenter 9

    After much trial-and-error I've discovered that the Presenter add-in for Powerpoint only works when Powerpoint is opened using RUN AS ADMINISTRATOR. If powerpoint is opened normally without administrator privileges, the add-in becomes disabled. Tryin

  • Yahoo does not display properly in firefox 31.0 but will show correctly in IE. How do I get this fixed?

    I have cleared cookies and cache, updated Firefox to 31.0 but it still keeps happening. I have even accessed my Yahoo email through the ATT site because I have an sbcglobal.net address. Nothing works. I can see my Yahoo email just fine through Intern

  • Study material for 1Z0-147 and 1Z0-151

    Hi all, Can u please suggest some good books for the 1Z0-147 and 1Z0-151 exams, If u can suggest some good sites where I can get latest dumps for these exams. Thanks and Regards Phoenix Edited by: 974398 on Dec 16, 2012 10:36 PM