Volatile Keyword

I am confused with the keyword "volatile". Few questions.
I have seen two different descriptions for this keyword.
1) Processors store data in their own registers for more efficient use.In Multiprocessor environments, the "volatile" keyword will ensure that a piece of shared data is always picked up from the (common) memory location and not reused from the (private copy) register for that processor.
If this is the case, then dont we require to use this keyword for all class level variables(static) ? Or does putting static keyword ensure this? (A static member is supposed to hold a common copy for all instances - how does it internally work in a multiprocessor environment?)
Is it possible that an instance may be partly serviced by one processor and partly by another in a multiprocessor env? In that case, dont we need to declare all instance variables as "volaile"?
2) "Volatile" keyword ensures that the data is "sequencially consistent" - meaning
if we have --
volatile int a = 5;
volatile boolean flag = true;
Then if flag is set to true, then a will already have been set to 5 always (this means this may not always be the case in the Runtime env, if the keyword is not volatile -- so in multithreading env..there can be problems if global variables are not "volatile"
Am I on the right track? The two descriptions of "volatile" seem very different. Are they both correct? I also read that many JVMS dont implement this as of now..so where do we stand in the use\relevance of this keyword?
Thanks,
Mathew Samuel.

If this is the case, then dont we require to use this
keyword for all class level variables(static) ? Or
does putting static keyword ensure this? (A static
member is supposed to hold a common copy for all
instances - how does it internally work in a
multiprocessor environment?)First, lets correct one of your statements. You say, "A static member is supposed to hold a common copy for all instances" It may seem subtle, but a static variable is associated with the class, not any instance. There doesn't need to be any instances of a class for a static to exist. The point is that there is not a 'copy' for each instance.
In a multi-threaded environment, each thread can cache it's own data. This is for performance. It takes time to keep the threads from interfering with each other.
Is it possible that an instance may be partly serviced
by one processor and partly by another in a
multiprocessor env? In that case, dont we need to
declare all instance variables as "volaile"?If you synchronize access to variables, you don't need to declare things as volatile. volatile isn't used all that often. Mainly, it's for certain situations where full synchrionization is not required.
2) "Volatile" keyword ensures that the data is
"sequencially consistent" - meaning
if we have --
volatile int a = 5;
volatile boolean flag = true;I can't really confirm or deny this.

Similar Messages

  • Does JRockit support the volatile keyword?

    Does JRockit support the volatile keyword? If yes, since what version of JRockit is it supported? Will it also be supported on JRockit for Linux.

    A M wrote:
    Does JRockit support the volatile keyword? If yes, since what version of JRockit is it supported? Will it also be supported on JRockit for Linux.AFAIK JRockit always has and always will, including (but not limited to)
    the Linux builds of JRockit.
    However, the actual behaviour of "volatile" hasn't been that well
    defined until Java 5.0, so our interpretation of what volatile should
    mean may or may not have been consistent with SUN's interpretation of
    what volatile should mean.
    Have you been having problems with using volatile? What are you using
    it for in that case? Since volatile might not do what you think it
    does, using locking could be better...
    Regards //Johan

  • About the volatile keyword

    I am learning about the volatile keyword.
    Does it depend on the VM whether the threads do cache its member variables into memory or not even if the volatile keyword is used? Because in my examlpe below the variable "b" is not volatile and it is beeing used in an infinite loop till some other thread change the variable to false. When it happens, the loop stops and I expected that the variable "b" would only be read once since it is not volatile and the loop would never stop.
    Could somebody explain? :-)
    public class VolatileExample {
        public VolatileExample(){
            T1 t1 = new T1();
            new Thread(t1, "T1").start();
            T2 t2 = new T2(t1);
            new Thread(t2, "T2").start();
        class T1 implements Runnable{
            public boolean b = true; // should be read once if not volatile?
            public T1(){
            public void run() {
                while(b){
                    System.out.println("true");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                System.out.println("false");
        class T2 implements Runnable{
            private T1 r;
            public T2(T1 r){
                this.r = r;
            public void run() {
                try {
                    Thread.sleep(5000);
                    r.b = false; // Here is where I change the other thread´s variable to false
                } catch (InterruptedException ex) {
        public static void main(String[] args){
            new VolatileExample();
    }

    Roxxor wrote:
    Thanks for your answer!
    So a rule of thumb would be: "when sharing a variable among different threads, it should be declared volatile"?I wouldn't say that.
    An absolute rule, however, is, "When sharing a variable among concurrently executing threads, if at least one of the threads will be writing that variable, and if at least one other thread needs to see the writer's update, then you *must* declare the variable volatile or synchronize all access to it."
    That is a bare minimum, of course. By itself, it doesn't guarantee your data will be consistent in a multithreaded context.
    I don't use volatile all that often, because all it does is make writes visible, provide a simple memory barrier, and provide atomicity for doubles and longs. Usually there are more complex requirements that lead to needing synchronization or the classes in java.util.concurrent, and then these end up giving me what volatile would have, plus more.

  • Use of volatile

    public class MyClass {
         public static void main(String[] a) throws InterruptedException {
              new Thread(new A(),"thread1 ").start();
              Thread.sleep(500);
              new Thread(new A(),"thread2 ").start();
    class A implements Runnable {
         volatile int value = 0;
         public void run() {
              value++;
              System.out.println(Thread.currentThread().getName() + value);
    }Hi, I tried running this code with value being both volatile and not, but I get the same answer each time. Both threads turn value to 1. Shouldn't volatile make it 1 then 2?
    I tried the same thing but making value static, in which case it works as I thought it would have worked with volatile. I'm not too sure what volatile does anymore, could somebody please help clarify all this for me?
    Thanks.

    public class MyClass implements Runnable {
         Other o = new Other();
         public static void main(String[] a) throws InterruptedException {
              MyClass m = new MyClass();
              new Thread(m,"thread1 ").start();
              Thread.sleep(500);
              new Thread(m,"thread2 ").start();
         public void run() {
              o.value++;
              System.out.println(Thread.currentThread().getName() + o.value);
    class Other {
         volatile int value;
    }I looked at this one a bit longer, and I came up with this new example. Is this case more likely to need the volatile keyword as a precaution (as the variable in question is in an indepedent class)?
    Any help on this topic would be really appreciated. I looked up several websites on volatile, but none really clarified the use of volatile (actually, I don't recall whether any mentioned that the caching problem doesn't always happen!).
    Thanks.

  • Use of volatile modifier

    can any one explain me the use of volatile modifier

    What does volatile do?
    This is probably best explained by comparing the effects that volatile and synchronized have on a method. volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessors using those two keywords:
    int i1; int geti1() {return i1;}
    volatile int i2; int geti2() {return i2;}
    int i3; synchronized int geti3() {return i3;}
    geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.
    On the other hand, geti2() effectively accesses the value of i2 from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.
    Well if volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3() does the following:
    1. The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).
    2. The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory (JVMs can use dirty sets to optimize this so that only "dirty" variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).
    3. The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
    4. (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
    5. The thread releases the lock on the monitor for object this.
    So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.
    I got the above information from the below link......
    http://www.javaperformancetuning.com/news/qotm030.shtml
    and also we can describe the volatile modifier as
    Volatile� A volatile modifier is mainly used in multiple threads. Java allows threads can keep private working copies of the shared variables(caches).These working copies need be updated with the master copies in the main memory.
    But possible of data get messed up. To avoid this data corruption use volatile modifier or synchronized .volatile means everything done in the main memory only not in the private working copies (caches).( Volatile primitives cannot be cached ).
    So volatile guarantees that any thread will read most recently written value.Because they all in the main memory not in the cache�Also volatile fields can be slower than non volatile.Because they are in main memory not in the cache.But volatile is useful to avoid concurrency problem.
    This above information i got from
    http://cephas.net/blog/2003/02/17/using-the-volatile-keyword-in-java/
    Thats all i think you understood what a volatile modifier is.And if you got any doubts still in Java you can reach me to [email protected]
    With Regards,
    M.Sudheer.

  • Volatile at low level

    Dear All,
    I should be grateful if you could explain to me the meaning of the volatile keyword in terms of what happens at JVM level and the need for it. I am aware that long and double types are treated as 2 words and volatile atomicizes operations with those primities, but what about atomicized ints in a multi-threaded program? What sort of optimization takes place inside the JVM?
    I should like to thank you in advance for your help.
    Luca
    PS. Please don't take anything for granted, cause I have just about started on the JVM architecture.
    thank you

    This is actually a subtle topic because the existing JVMs generally do not implement the semantics correctly and it is in the process of being revised anyway.
    This article contains some useful references [warning: they will not be easy reading]:
    http://www.javaworld.com/javaworld/javaqa/2003-02/01-qa-0214-threadsafe.html

  • The "Volatile" Puzzle

    Need a simple example code that works differently with and without "volatile".
    I understand the need for 'volatile' keyword and what it does in java. However, I also vaguely remember reading that this is no longer necessary. i.e., the compiler and jvm of these days takes care of local caching and memory writes very smartly. I tried several examples to see if I can reproduce a case where existence of 'volatile' really makes a difference. But, all my attempts went in vain.
    Here is an example:
    package volatilekw;
    public class Thread1 extends Thread{
    volatile int answer = 0;
    public void setAnswer(int i) {
    answer = i;
    @Override
    public void run() {
    for (int i=0;i<100;i++) {
    System.out.print(answer);
    try {
    sleep(10);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    package volatilekw;
    public class Thread2 extends Thread{
    private Thread1 t = null;
    public Thread2(Thread1 t) {
    this.t = t;
    @Override
    public void run() {
    for (int i=0;i<100;i++) {
    try {
    sleep(10);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    if (i == 1)
    t.setAnswer(1);
    package volatilekw;
    public class Gotgo {
    public static void main(String[] args) {
    Thread1 t1 = new Thread1();
    Thread2 t2 = new Thread2(t1);
    t1.start();
    t2.start();
    Irrespective of whether the "answer" is volatile or not, the output is same with JDK 1.6. I ran several times and even tried decrementing sleep value. If my understanding goes right, the writes of thread2 on answer might not be visible to thread t1 until it caches it. But, this is never the case.
    Is there a good example that demonstrate that 'volatile' does make a difference? I am looking for a piece of code when run with and without 'volatile' gives two different outputs.

    853929 wrote:
    Need a simple example code that works differently with and without "volatile".Impossible to produce reliably. Without volatile, some things can happen, depending on timing, the OS's scheduler, the underlying hardware, other processes running, the JVM implementation, etc., but there's no guarantee that those things ever will happen. However, it's generally bad if they do, so volatile is one way of ensuring that they don't.
    I understand the need for 'volatile' keyword and what it does in java. However, I also vaguely remember reading that this is no longer necessary. i.e., the compiler and jvm of these days takes care of local caching and memory writes very smartly.Nope. The use-case for volatile is still there.
    Volatile was never strictly necessary. We've always been able to accomplish what volatile does by syncing every access to the variable in question. However, when all you need is that all threads see the same copy, and you don't have other atomicity issues to deal with, volatile can save some runtime overhead relative to syncing, and, more importantly, it can make for less cluttered code.
    I tried several examples to see if I can reproduce a case where existence of 'volatile' really makes a difference. But, all my attempts went in vain.Try a multi-cpu box, with not much else happening on it, create as many threads as there are CPUs, and have all threads run a loop from 0 to 10,000 or 100,000,00 or millions that does nothing more than x++ on some shared member variable.
    With volatile, and N threads and a count up to M, you'll see a final value of N x M.
    Without volatile, you might see a value less than N x M.

  • Reason for "volatile" modifer?

    I've read a chapter on the use of threads in Java in one of my reference books.
    Here's a quote:
    "The instance variable topofStack in class StackImpl is declared volatile, so that read and write operations on this variable will access the "master" value of this variable, and not any copies, during runtime"
    Where would these "copies" come from?? Don't all thread share the same data and program code in the same memory?
    Thanks in advance for any clarification...

    Where would these "copies" come from?? Don't all
    thread share the same data and program code in the
    same memory?
    Nope. Each thread has its own copy of each variable, and every now and then it synchronizes with the shared "main" memory. A synchronized block says to a thread: Before entering this section of code, overwrite your local copy of variables reachable form within this block, with the values in main memory; Before leaving this section of code, write those values back to main memory. Since no two threads can access the same synchronized block at the same time, synchronization (if used properly) guarantess that all threads read all variables in a consistent state.
    The volatile keyword basically means that all access to the declared variable should be via main memory.
    This might not be completely technically accurate, but it should get the point accross. I first learned about it myself after reading an article on JavaWorld about the pitfalls double-checked locking. You can read it here:
    http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html

  • When is volatile needed?

    I know you need to use the volatile keyword when multiple threads might be accessing a primitive or reference without external synchronization. Suppose your class implements Runnable and has one member variable, a final int. The constructor takes an int and simply assigns it to the one member variable. You dump it into an ExecutorService with submit()--do you need to use volatile to make sure that the other threads see the assigned value of the int? The int is only assigned once in the constructor.
    It would seem to me the logical answer here is no; the VM would enforce a memory barrier between unassigned variables turning into assigned variables, but I'm just making sure, since what I've found doesn't really clarify this for me.

    Just out of curiosity, suppose the field was
    non-final. Would volatile still not be needed?If the value never changes, and if you don't let a reference leak out of the constructor, then I'm not sure if you'd need volatile.
    In general, it's possible for one thread to set a value, and another thread to never see it, if there's no syncing and no volatile. I thought that something in the new JMM prevented that in this particular case--i.e., a constructor, but I'm not sure if that's true, or what the details are.
    The answer should be here: http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.4

  • Volatile and object atomicity

    Hi,
    I'm reading the sun concurrency tutorials and am unable to understand how the 'atomicity' is enfored on object when volatile modifier is applied to it. A sample program suggests me that two threads can be in two different methods of a 'volatile' object and modify the 'state' of the object.
    With this observation I'm not understanding how 'volatile' keyword forces atomicity for an object.
    Here is the sample code I've written to verify this along with the result when executed on my machine here.
    In the code that follows -
    VolatileClass - A single volatile instance of this class would be used by two threads.
    IncrementThread - Increments the state of the VolatileClass instance.
    DecrementThread - Decrements the state of the VolatileClass instance.
    My expectation is that as the VolatileClass object is declared as a volatile variable, two threads should not enter the same object. I understand that methods are not synchronized, but the volatile keyword should guarantee the atomicity.
    Any thoughts?
    public class Main {
         private static class VolatileClass {
              int nonVolatileInt = 0;
              public int increment() {
                   try {
                        System.out.println("Increment slept...");
                        Thread.sleep(500L);
                        System.out.println("Increment woke");
                   } catch (final InterruptedException e) {
                        System.out.println("Increment Resuming...");
                   return ++nonVolatileInt;
              public int decrement() {
                   try {
                        System.out.println("Decrement slept...");
                        Thread.sleep(100L);
                        System.out.println("Decrement woke");
                   } catch (final InterruptedException e) {
                        System.out.println("Decrement resuming...");
                   return --nonVolatileInt;
              // VolatileClass
         private static class IncrementThread implements Runnable {
              VolatileClass memberVolatileClass;
              public IncrementThread(final VolatileClass volatileClass) {
                   memberVolatileClass = volatileClass;
              @Override
              public void run() {
                   for (int i = 0; i < 10; i++) {
                        System.out.println("Increment: "
                                  + memberVolatileClass.increment());
              // IncrementThread
         private static class DecrementThread implements Runnable {
              VolatileClass memberVolatileClass;
              public DecrementThread(final VolatileClass volatileClass) {
                   memberVolatileClass = volatileClass;
              @Override
              public void run() {
                   for (int i = 0; i < 10; i++) {
                        System.out.println("Decrement: "
                                  + memberVolatileClass.decrement());
              // DecrementThread
         static volatile VolatileClass volatileClass = new VolatileClass();
         public static void main(final String[] args) {
              final Thread incrementThread = new Thread(new IncrementThread(
                        volatileClass));
              final Thread decrementThread = new Thread(new DecrementThread(
                        volatileClass));
              incrementThread.start();
              decrementThread.start();
              // main
    }The result of the code is
    Increment slept...
    Decrement slept...
    Decrement woke
    Decrement: -1
    Decrement slept...
    Decrement woke
    Decrement: -2
    Decrement slept...
    Decrement woke
    Decrement: -3
    Decrement slept...
    Decrement woke
    Decrement: -4
    Decrement slept...
    Increment woke
    Increment: -3
    Increment slept...
    Decrement woke
    Decrement: -4
    Decrement slept...
    Decrement woke
    Decrement: -5
    Decrement slept...
    Decrement woke
    Decrement: -6
    Decrement slept...
    Decrement woke
    Decrement: -7
    Decrement slept...
    Decrement woke
    Decrement: -8
    Increment woke
    Decrement slept...
    Increment: -7
    Increment slept...
    Decrement woke
    Decrement: -8
    Increment woke
    Increment: -7
    Increment slept...
    Increment woke
    Increment: -6
    Increment slept...
    Increment woke
    Increment: -5
    Increment slept...
    Increment woke
    Increment: -4
    Increment slept...
    Increment woke
    Increment: -3
    Increment slept...
    Increment woke
    Increment: -2
    Increment slept...
    Increment woke
    Increment: -1
    Increment slept...
    Increment woke
    Increment: 0

    I underlined the critical parts that you missed, namely that all the non-atomic actions are on non-volatile longs and doubles.
    Or perhaps you missed my use of the word volatile in the part that you quoted and said you disagree with.
    kilyas wrote:
    >
    2. Every read and write of a volatile variable is guaranteed atomic, including doubles and longs, which are 64 bits. If the underlying hardware does that in two 32-bit steps, the JVM must ensure that the executing code sees only the before or after value, not the intermediate half-and-half.
    [http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.7]
    [http://java.sun.com/docs/books/jvms/second_edition/html/Threads.doc.html#22258]
    [http://java.sun.com/docs/books/jvms/second_edition/html/Threads.doc.html]
    The bold part is what I am differing with. In his book "Java Concurrency in Practice" Brian Goetz writes in Section 3.1.2
    +"the JVM is permitted to treat a 64-bit read or write as two separate 32-bit operations. If the reads and writes occur in different threads, it is therefore possible to read a nonvolatile long and get back the high 32 bits of one value and the low 32 bits of another"+
    Something similar is mentioned here @ http://java.sun.com/docs/books/jvms/second_edition/html/Threads.doc.html
    *8.4 Nonatomic Treatment of double and long Variables*
    +If a double or long variable is not declared volatile, then for the purposes of load, store, read, and write operations it is treated as if it were two variables of 32 bits each; wherever the rules require one of these operations, two such operations are performed, one for each 32-bit half. The manner in which the 64 bits of a double or long variable are encoded into two 32-bit quantities and the order of the operations on the halves of the variables are not defined by The Java Language Specification.+
    This matters only because a read or write of a double or long variable may be handled by an actual main memory as two 32-bit read or write operations that may be separated in time, with other operations coming between them. Consequently, if two threads concurrently assign distinct values to the same shared non-volatile double or long variable, a subsequent use of that variable may obtain a value that is not equal to either of the assigned values, but rather some implementation-dependent mixture of the two values.+
    An implementation is free to implement load, store, read, and write operations for double and long values as atomic 64-bit operations; in fact, this is strongly encouraged. The model divides them into 32-bit halves for the sake of currently popular microprocessors that fail to provide efficient atomic memory transactions on 64-bit quantities. It would have been simpler for the Java virtual machine to define all memory transactions on single variables as atomic; this more complex definition is a pragmatic concession to current hardware practice. In the future this concession may be eliminated. Meanwhile, programmers are cautioned to explicitly synchronize access to shared double and long variables.
    According to the Java Language Specification [JLS 2005], Section 17.7, "Non-atomic Treatment of double and long"
    +... this behavior is implementation specific; Java virtual machines are free to perform writes to long and double values atomically or in two parts. For the purposes of the Java programming language memory model*, a single write to a non-volatile long or double value is treated as two separate writes: one to each 32-bit half.* This can result in a situation where a thread sees the first 32 bits of a 64 bit value from one write, and the second 32 bits from another write.+
    Edited by: jverd on Aug 9, 2010 11:48 AM
    Edited by: jverd on Aug 9, 2010 11:49 AM

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

  • Problem with adding text to a syntax document

    Hello,
    I am trying to write an editor with syntax highlighting option.
    The syntax document works fine but on a slow computer
    after loading a huge document it is impossible to write fluently.
    I think the method highlightKeyword() is not the problem because it highlights still only one line.
    The problem seems to be the rootElement.Has anybody an idea how to make the rootElement faster
    working?
    I also tried to use threads (such as http://ostermiller.org/syntax/editor.html) for inserting text, but then the document is highlighted very slowly.
    Can anybody help me?
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SyntaxTest extends DefaultStyledDocument
         Element rootElement;
         String wordSeparators = ",:;.()[]{}+-/*%=<>!&|~^@? ";
         Vector keywords = new Vector();;
         SimpleAttributeSet keyword;
         public SyntaxTest()
              rootElement= this.getDefaultRootElement();
              keyword = new SimpleAttributeSet();
              StyleConstants.setForeground(keyword, Color.blue);
              keywords.add( "abstract" );
              keywords.add( "boolean" );
              keywords.add( "break" );
              keywords.add( "byte" );
              keywords.add( "case" );
              keywords.add( "catch" );
              keywords.add( "char" );
              keywords.add( "class" );
              keywords.add( "continue" );
              keywords.add( "default" );
              keywords.add( "do" );
              keywords.add( "double" );
              keywords.add( "else" );
              keywords.add( "extends" );
              keywords.add( "false" );
              keywords.add( "final" );
              keywords.add( "finally" );
              keywords.add( "float" );
              keywords.add( "for" );
              keywords.add( "if" );
              keywords.add( "implements" );
              keywords.add( "import" );
              keywords.add( "instanceof" );
              keywords.add( "int" );
              keywords.add( "interface" );
              keywords.add( "long" );
              keywords.add( "native" );
              keywords.add( "new" );
              keywords.add( "null" );
              keywords.add( "package" );
              keywords.add( "private" );
              keywords.add( "protected" );
              keywords.add( "public" );      
              keywords.add( "return" );
              keywords.add( "short" );
              keywords.add( "static" );
              keywords.add( "super" );
              keywords.add( "switch" );
              keywords.add( "synchronized" );
              keywords.add( "this" );
              keywords.add( "throw" );
              keywords.add( "throws" );
              keywords.add( "true" );
              keywords.add( "try" );
              keywords.add( "void" );
              keywords.add( "volatile" );
              keywords.add( "while" );
         public void insertString(int offset, String str, AttributeSet a) throws BadLocationException
              super.insertString(offset, str, a);
              int startOfLine = rootElement.getElement(rootElement.getElementIndex(offset)).getStartOffset();
              int endOfLine = rootElement.getElement(rootElement.getElementIndex(offset+str.length())).getEndOffset() -1;
              //highlight the changed line
              highlightKeyword(this.getText(0,this.getLength()), startOfLine, endOfLine);
         public void remove(int offset, int length) throws BadLocationException
              super.remove(offset, length);
              int startOfLine = rootElement.getElement(rootElement.getElementIndex(offset)).getStartOffset();
              int endOfLine = rootElement.getElement(rootElement.getElementIndex(offset+length)).getEndOffset() -1;
              //highlight the changed line
              highlightKeyword(this.getText(0,this.getLength()), startOfLine, endOfLine);
         public void highlightKeyword(String content,int startOffset, int endOffset)
              char character;
              int tokenEnd;
              while (startOffset < endOffset)
                   tokenEnd = startOffset;
                   //find next wordSeparator
                   while(tokenEnd < endOffset)
                   character = content.charAt(tokenEnd);
                        if(wordSeparators.indexOf(character) > -1)
                             break;
                        else
                             tokenEnd++;                    
                   //check for keyword
         String token = content.substring(startOffset,tokenEnd).trim();
                        if(keywords.contains(token))
                   this.setCharacterAttributes(startOffset, token.length(), keyword, true);
         startOffset = tokenEnd+1;
         public static void main(String[] args)
              JFrame f = new JFrame();
              JTextPane pane = new JTextPane(new SyntaxTest());
              JScrollPane scrollPane = new JScrollPane(pane);
              f.setContentPane(scrollPane);
              f.setSize(600,400);
              f.setVisible(true);

    I don't think the root element is the problem. Syntax highlighting is just plain slow for a large file. Here is an example, you can use for comparison purposes, that does [url http://www.discoverteenergy.com/files/SyntaxDocument.java]syntax highlighting. It is very slow when loading large files into the text pane, but works reasonably when modifying the contents of the text pane.

  • New improvement for Java syntax

    Hi developers
    I develop in java each day and the new project that I am envolved uses too much multithreading. So i thought that a litle improvement could be made on java syntax.
    When two threads uses the same class attribute we must synchronize the access to this.
    class myClass {
    private int myAtribute = 0;
    thread1: We must access the attribute synchronized....
    shynchronized (this) {
    myAttribute = 1;
    thread2: The same....
    synchronized (this) {
    myAttribute = 3;
    thread2: But if i don't care.... :-(
    myAttribute = 4;
    Ok, that is the problem.
    I thought to solve this the java language must give us the chance to declare attributes in the way...
    private synchronize int myAttribute = 0;
    to be only accesed by sinchronized methods or by synchronized blocks in order to force interpreter to check if any method access this attribute without being synchronized in compiling time.

    In your example, wouldn't the volatile keyword normally suffice?
    private volatile int myAttribute = 0;Graeme

  • Passing values to different thread

    how to pass value to diffent threads?
    this code dosen't work. the only path that was processed is the "sDirList[1]="//10.81.86.55/ANC_DATA$/";"
    public static void main(String[] args){
            sDirList[0]="//10.81.86.55/LOG_FIT$/";
            sDirList[1]="//10.81.86.55/ANC_DATA$/";
             setIndex(0);
             (new Thread(new ListFile())).start();
             setIndex(1);
             (new Thread(new ListFile())).start();
    class ListFile() extends thread{
    private int ndx=0;
    public setIndex(int i){
      ndx=1
    //open path with the current index
    }

    If you two threads are sharing variables, then they must be declared as 'volatile'. If you use volatile, then the variables will be stored in main memory, rather in thread specific memory. That means adding volatile keyword should solve the issue.

  • Actual Benefits of final methods and final parameters

    I know that a lot of this depends on the JVM and the actual code, but I was wondering what the actual real world advantage was of using final methods and final parameters.
    I use a business and data layer for my program to interact with the database. So all of the methods in these classes are public and static. I was just wondering if it would be benefical to make all of these methods final and all of the parameters final also. I won't ever be making subclasses of these classes, so is this worth doing?
    Thanks,
    Dave Johansen

    On the point of final, this should always be a design decision. That is, does it make sense to allow your class to be overridden? Making classes and/or methods final is a big barrier to future enhancements and extendability - so only make soemthing final if you haver a specific reason for doing so.
    Any performance issues should not take a high precedence in this decision - and in any case the difference in making something final will be non-existant for all practical purposes.
    How about volatile?
    I get the meaning of synchronized but
    volatile?Volatile is a keyword that tells the JVM it can't optimize / inline serctions of code that use certain variables. You may not realise it, but the JVM takes your bytecode and chops them up and re-arranges them at runtime, to boost performance. This can sometimes have dangerous consequences in a mutlithreaded environment, so by adding the volatile keyword you are saying to the JVM (or specifically HotSpot) not to perform any "code magic".
    Here's a simple example:
    public class TestClass {
        private boolean check = false;
        public void setTrue(){
            check = true;
        public void check(){
            check = false;
            if(check){
                System.out.println("Will this ever print?");
    }Obviously the string will never print in a single threaded environment. However, in a multithreaded environment, is is possible that a thread could call setTrue() between another thread setting the value to false and performing the if() check. The point is that due to runtime optimization, Hotspot may realise that check is always false, so completely remove the code section with the if block. so regardless of the value of the boolean, the code may never be entered.
    One solution is to declare the boolean check as volatile. This tells the JVM that such optimizations are not allowed and then it is entirely possible for the string to be printed.
    One curiousity, off-topic:
    is there a way for jvms instantiations to see each
    other?Have you looked into RMI?

Maybe you are looking for

  • User not able to download new mail

    I have a user that is unable to fetch new mail as of Oct 10. Nothing has changed on his computer. He can view new emails on webmail/iphone, just not on his computer. The iphone has the same exact config as his computer. I have trashed his mail's plis

  • Crystal Reports Duplexing issues after upgrading to SP5

    Our Application Software Vendor uses Crystal Reports XI as their reporting tool.  Recently we upgraded our application software which included upgraded from CR XI SP3 to SP5.  Since then we've experianced problems printing some of the reports in DUPL

  • Media Foundation support

    Hi, I want to develop a driver for FMLE. And I want to know whether it supports Windows Media Foundation drivers. Thank you Ravindra

  • P2vhd and error loading operating system

    I used p2vhd to create a windows server 2003 server to a vhd file.  I have done in this in the past wihtout any issue but it seems this time when i load the vhd i get the message.  error loading operating system.  Any idea why this is?

  • New iTunes Doesn't Start In Windows XP Pro

    I downloaded new iTunes and now it doesn't open at all. I have unistalled and installed it back many times, including with the help of Apple Support through the phone and I still cannot make it work. The previous version was working perfectly fine. I