Use of Synchronized Keyword / Concurrency

I have a program which makes two Writer threads (they add 1 to a shared
counter), A sampler Thread (like a reader thread � it also displays the
data held by the other thread). I have been playing around with the
synchronised keyword � but I am not sure how to interpret the
results..I'll post the code first....
the shared counter------------------------------
package sycTest;
public class Counter
{public int val = 0;}
the sampler / reader class----------------------
package sycTest;
public class Sampler extends Thread
private Counter c;
private MyThread A, B;
public Sampler ( MyThread A, MyThread B, Counter c ) {
this.A = A;
this.B = B;
this.c = c;
public void run()
while(true)
try { sleep( 1000 ); } catch (Exception x) { }
System.out.println
"A count = " + A.getCount() + ", " +
"B count = " + B.getCount() + ": " +
"A + B count = " + (A.getCount() + B.getCount()) + ", " +
"shared counter = " + c.val
the main class to get things started------------------------------------
package sycTest;
import java.util.Random;
public class Main
public static void main( String[] args )
Counter c = new Counter();
MyThread A = new MyThread( c );
MyThread B = new MyThread( c );
A.start(); B.start();
// create and start Sampler thread in one step
new Sampler( A, B, c ).start();
// main thread waits to read a carriage-return.
try {
     System.in.read();
catch( Exception e ) { }
System.exit(0);
/* rand_sleep function is used to generate "random switching" behaviour
assuming n > 0,
rand_sleep( n ) sleeps a random time between 0 and n millisec.
private static Random rand = new Random();
public static void rand_sleep( int maxms ) {
int ms = rand.nextInt() % maxms; // - maxms < ms < maxms
int amt=(ms + maxms + 1)/2;
try { Thread.sleep(amt); } catch(Exception e) { }
the thread / writer class-------------------------------------------
package sycTest;
public class MyThread extends Thread
private Counter sharedCounter;
public MyThread( Counter c ) { this.sharedCounter=c; }
private int count=0;
public int getCount() { return count; }
public void run() {
while(true)
          // simulate non-critical section by sleeping a "large" amount
          Main.rand_sleep(1000);
          synchronized (sharedCounter) {
          criticalSection();
          //Main.rand_sleep(1000);
          ++count;
private void criticalSection() {
int x=sharedCounter.val + 1;
Main.rand_sleep( 100 );
sharedCounter.val=x;
--the question!
The idea is that running the main methods gives something like
A count=13, B count=10: A + B count=23, shared counter=23
(where A and B are writer threads)
If I take out the synchronised keyword in the MyThread class, things get
much worse...the 'personal' totals of A and B do not equal the total
held in the shared counter rather quickly..
          criticalSection();
          //Main.rand_sleep(1000);
          ++count;
eg
A count=13, B count=10: A + B count=23, shared counter=22
However, adding the synchronised keyword (eclipse suggested
�sharedCounter� as the argument � the notes seem to suggest �this�, but
if I do that the synchronised keyword seems much like the example above...
synchronized (sharedCounter) {
          criticalSection();
          ++count;
this makes it much better...I never saw it get the counts 'wrong'
eg
A count=56, B count=72: A + B count=128, shared counter=128
Now comes the confusing bit...when I add some time between the 2 methods
within the sychonized block...
synchronized (sharedCounter) {
          criticalSection();
          Main.rand_sleep(1000);
          ++count;
Then mismatches appear very quickly, the program behaves very similarly
to when it didn't have the synchronised keyword...
Why is this? Is it because the Sampler class is asking what the values
of the shared and personal counters during the �Main.rand sleep(1000)�
call??
The other question I was hoping someone could help me with, is pointing
out what the difference is between �synchronized (sharedCounter)� and
�synchronized (this)� is in this context. Why does the later not do
anything in this example?
Thanks,
Julian

Hello Julian,
you're Sampler thread reads the different counters without any synchronization. He may call A.getCount() and get 5 back, then yield and then ask for c.val which was increased by A in the meantime. Or A increases it's own counter, then yields and lets the Sampler output nonsense.. ;)
To clear up the confusion surrounding Thread.sleep(long): It would be a waste to do nothing while the thread is sleeping, so another thread gets to play. Since the other MyThread is waiting on sharedCounter's monitor and the sleeping thread still owns it<sup>1</sup> the Sampler thread gets the execution time. Now the sampler gets going and you know the rest.
1: http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.9
EDIT: In future, use code-tags:
class MyClass {
    private int myField;
}will turn into
class MyClass {
    private int myField;
}With kind regards
Ben
Edited by: BenSchulz on Mar 24, 2008 11:45 AM

Similar Messages

  • Use of synchronized keyword with portal services

    Hi,
    Can you confirm me if it is true that a portal service is a Singleton? I mean, when using an instance variable of a portal service I am able to set the value of the instance variable using one client app and get it afterwards using another client app. So we are talking about the same and only instance of the portal service, right?
    If this is true how can I synchronize the access to a portal's service method? I tried to mark
    the method syncronized (in the interface) but then I realized that this issues a compiler error because one can not mark an interface method synchronized. So can I mark the implementation class instead? That is, can I leave the interface without the synchronized keyword for the method and still mark the implementation of the method in the service class as syncronized? Does this work?
    Thanks in advance,
    Diz

    Hi,
    Portal service is not a Singleton, as the name says a service is just provider for services which does not save state between two requests/applications.
    So if you want to save state, then use some session variables to save it.
    In a cluster installation, each server node has its own portal services, so if you save state in service, then your application should save this state on all servers of the cluster.
    So you should change your approch.
    http://help.sap.com/saphelp_nw70/helpdata/en/e3/fab74247e2b611e10000000a155106/frameset.htm
    Greetings,
    Praveen Gudapati
    [Points are always welcome for helpful answers]

  • Use of 'static' keyword in synchronized methods. Does it ease concurrency?

    Friends,
    I have a query regarding the use of 'synchronized' keyword in a programme. This is mainly to check if there's any difference in the use of 'static' keyword for synchronized methods. By default we cannot call two synchronized methods from a programme at the same time. For example, in 'Program1', I am calling two methods, 'display()' and 'update()' both of them are synchronized and the flow is first, 'display()' is called and only when display method exits, it calls the 'update()' method.
    But, things seem different, when I added 'static' keyword for 'update()' method as can be seen from 'Program2'. Here, instead of waiting for 'display()' method to finish, 'update()' method is called during the execution of 'display()' method. You can check the output to see the difference.
    Does it mean, 'static' keyword has anything to do with synchronizaton?
    Appreciate your valuable comments.
    1. Program1
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    end display:
    start update:
    end update:
    2. Program2
    package camel.java.thread;
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    start update:end update:
    end display:

    the synchronized method obtain the lock from the current instance while static synchronized method obtain the lock from the class
    Below is some code for u to have better understanding
    package facado.collab;
    public class TestSync {
         public synchronized void add() {
              System.out.println("TestSync.add()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.add() - end");          
         public synchronized void update() {
              System.out.println("TestSync.update()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.update() - end");          
         public static synchronized void staticAdd() {
              System.out.println("TestSync.staticAdd()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticAdd() - end");
         public static synchronized void staticUpdate() {
              System.out.println("TestSync.staticUpdate()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticUpdate() - end");
         public static void main(String[] args) {
              final TestSync sync1 = new TestSync();
              final TestSync sync2 = new TestSync();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.add();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.update();
              }).start();
              try {
                   Thread.sleep(3000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.staticAdd();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.staticUpdate();
              }).start();
    }

  • Object or Statement Block locking using synchronized keyword in java

    Hi ,
    Can anyone tell me how java is implementing the Object locking and the code block locking mechanism using the 'synchronized' keyword internally??
    Thanks in advance
    Raj

    The JVM implements a concept known as a monitor using a combination of direct implementation and support by the operating system. For more detail, refer to the Java JVM and language specifications.
    Chuck

  • Understanding 'synchronized' keyword

    Hello,
    I have a main class (ClsA.java) that extends JFrame, the frame contains one JButton and one JTextArea.
    When pressing the button x number of threads are created and each thread will write a couple of messages in the JTextArea by using a method in ClsA.java, the method looks like this:
    public void output(String output){
      this.taOutput.append(new java.util.Date(System.currentTimeMillis()) + ":" + output + System.getProperty("line.separator"));
    }everything works fine, but sometimes a few messages from different threads end up on the same line in the JTextArea. To fix this I changed the output method to this:
    public synchronized void output(String output){
      this.taOutput.append(new java.util.Date(System.currentTimeMillis()) + ":" + output + System.getProperty("line.separator"));
    }I have just added the synchronized keyword that will make the the system associates a unique lock with every instance of ClsA (there is only one). This works alomost fine, but when I increase the number of concurrent threads the application freezes(I�m not able to scroll down in the textarea or press the button)? Why does it freeze? I have tried adding notifyAll() at the end of the output method but there is no difference. What am I doing wrong here? The acquisition and release of a lock is done automatically and atomically by the Java runtime system.....but can it still end up in a freeze?!
    Greatfull for any suggestions!
    //Anders =)

    Hi,
    Use
    public void output(String output){
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    taOutput.append(new java.util.Date(System.currentTimeMillis()) + ":" + output + System.getProperty("line.separator"));
    so as to update the text area only in the event thread!
    Roger

  • Use of 'synchronized'

    Hello,
    Is there any difference (other than having to declare a lock object in the second case) between :
    public void synchronized myMethod(){
    doSomething();
    and
    public void myMethod() {
    synchronized(lock) {
    doSomething();
    Thank you.
    Benoit

    it is not only a difference in performance, but one
    version is threadsafe on multiprocessor machines and
    the other is not.
    [snip]
    The reasoning is that the synchronized keyword on a
    method is handled by the jvm as a special case and has
    the capability to do the locking between processors(if
    it's a good jvm). The synchronized block as was
    stated produces byte code (2 of them). Because of
    this, the jvm can't do this additional optimization
    because it cannot possibly lock both processes without
    the chance of deadlock since each process can be
    trying to lock each other after the first byte code,
    but before it finishes the second. So therefore the
    jvm must purposely not synchronize the multiple
    processes.Interesting argument, but it doesn't seem to sit right.
    Taken directly from the JVMS, the two instructions will roughly be...   2  aload_2      // Push local variable 2 (f)
       3  monitorenter // Enter the monitor associated with fhttp://java.sun.com/docs/books/vmspec/2nd-edition/html/Compiling.doc.html#6530
    There is no possibility of deadlock by interleaving any combination of the above two bytecodes, since the monitorenter is defined as a cpu-atomic operation. From the JLS (emphasis added)...
    http://java.sun.com/docs/books/jls/second_edition/html/memory.doc.html#28287
    For the purposes of this chapter, the verbs use, assign, load, store, lock, and unlock name actions that a thread can perform. The verbs read, write, lock, and unlock name actions that the main memory subsystem can perform. Each of these actions is atomic (indivisible).
    I read this as saying that the monitorenter instructions can be assumed to execute serially, since they are atomic operations on the shared memory. Therefore, the second CPU to execute the monitorenter instruction will find the monitor taken, and will wait for it to be released.
    This of course assumes that the two processors share a single memory... else this breaks down to a distributed JVM problem, which will need extra semantics to conform to the JLS and JVMS.
    If you have any links to information on the thread-safe behaviour of java on multi-processor systems, they would be greatly appreciated - the specification means to me that both constructs should be thread-safe, but if there is anecdotal evidence to the contrary...
    Regards,
    -Troy
    PS- There were no reported bugs to this effect that I found in Sun's java bug database

  • Synchronized keyword for simple addition

    Hi, I have a function, as given below
    {noformat}public static void increment() {{noformat}{noformat} a = a + 1; {noformat}{noformat}}
    {noformat}
    This function will be called from multiple threads (a is also a static variable).
    My question is should I use "synchronized" keyword for this method to avoid unpredictable results? Is there a way to wirte this function without using "synchronized" keyword?
    Please suggest.

    Thanks, jwenting. I wanted to confirm that "synchronized" has to be used.
    jwenting wrote:
    yes. Depending of course on what you decide to be "unpredictable" :)you understand what "unpredictable" means here ;)
    jwenting wrote:
    yes, don't use a static variable but a method local one. Of course that will have a totally different effect.Variable "a" should be a class level variable. Yes, local variable has a totally different effect. ;)

  • How to reference a class without using the new keyword

    I need to access some information from a class using the getter, but I don't want to use the new keyword because it will erase the information in the class. How can I reference the class without using the new keyword.
    ContactInfo c = new ContactInfo(); // problem is here because it erases the info in the class
    c.getFirstName();

    quedogf94 wrote:
    I need to access some information from a class using the getter, but I don't want to use the new keyword because it will erase the information in the class. How can I reference the class without using the new keyword.
    ContactInfo c = new ContactInfo(); // problem is here because it erases the info in the class
    c.getFirstName();No.
    Using new does not erase anything. There's nothing to erase. It's brand new. It creates a new instance, and whatever that constructor puts in there, is there. If you then change the contents of that instance, and you want to see them, you have to have maintained a reference to it somewhere, and access that instance's state through that reference.
    As already stated, you seem to be confused between class and instance, at the very least.
    Run this. Study the output carefully. Make sure you understand why you see what you do. Then, if you're still confused, try to rephrase your question in a way that makes some sense based on what you've observed.
    (And not that accessing a class (static) member through a reference, like foo1.getNumFoos() is syntactically legal, but is bad form, since it looks like you're accessing an instance (non-static) member. I do it here just for demonstration purposes.)
    public class Foo {
      private static int numFoos; // class variable
      private int x; // instance varaible
      public Foo(int x) {
        this.x = x;
        numFoos++;
      // class method
      public static int getNumFoos() {
        return numFoos;
      // instance method 
      public int getX() {
        return x;
      public static void main (String[] args) {
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ();
        Foo foo1 = new Foo(42);
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ("foo1.numFoos is " + foo1.getNumFoos ());
        System.out.println ("foo1.x is " + foo1.getX ());
        System.out.println ();
        Foo foo2 = new Foo(666);
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ("foo1.numFoos is " + foo1.getNumFoos ());
        System.out.println ("foo1.x is " + foo1.getX ());
        System.out.println ("foo2.numFoos is " + foo2.getNumFoos ());
        System.out.println ("foo2.x is " + foo2.getX ());
        System.out.println ();
    }

  • Use of 'ME' keyword in ABAP Objects?

    Hi all,
       Can any one please  use of 'ME' keyword in ABAP Objects?
    Thanks,
    Vijay.
    Moderator message: next time, please search for available information before asking.
    Edited by: Thomas Zloch on Sep 16, 2010 5:33 PM

    Hi,
    Please find the description about the ME keyword as per the SAP documentation and help.sap.com.
    Within the implementation of every instance method, an implicitly created local reference variable called me is available, which points to the instance in which the method is currently being executed. The static type of me is the class in which the instance method is implemented.
    Each class implicitly contains the reference variable me. In objects, the reference variable mealways contains a reference to the respective object itself and is therefore also referred to as the self-reference. Within a class, you can use the self-reference me to access the individual class components:
    -To access an attribute attr of your class: me->attr
    -To call a method meth of your class: CALL METHOD me->meth
    When you work with attributes of your own class in methods, you do not need to specify a reference variable. The self-reference me is implicitly set by the system. Self-references allow an object to give other objects a reference to it. You can also access attributes in methods from within an object even if they are obscured by local attributes of the method.
    Regards,
    Sagar

  • Use of Synchronized  in jsp/servlet

    Can any one explain me the use of Synchronized in servlet/jsp which is multithreaded Is this correct synchronized should be used only when we want to pritect Static variable as they have only one copy but in case of instance variable they have seperate copy for each instance so no point of synchronized.
    Thanks in advance

    Hello again,
    Take an external file for instance, you open a input stream to it and read data from it in your Java application. You can't have two threads reading at the same time, and one will likely block or throw an exception.
    A better example is when your threads need to communicate with each other. If they all communicate via a set of variables that can be read and written to by any of them, then they should be synchronized. You should know if your threads need to communicate with each other? If they do not, there is no need for synchronisation.
    What are your threads doing if you don't mind me asking?
    I have to admit, I have had little experience using threads, and I have never needed to use threads in JSP (I don ot directly use servlets).
    Regards,
    Darren

  • Use of final keyword on methods arguements ?

    Hi All,
    Just say I have an input arguement for a method which is an int. If I wanted to access the value stored by the input arguement reference inside an anonymous class that is contained in the method one way would be to pass the input arguement reference to a instance variable of the class that contains the method and use that.
    // Declared at start of  class
    int arrayIndex = 0;
    methodName(nt inputNumber)
        arrayIndex = inputNumber;
        ActionListener task = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                // Accessing here
                anArray[arrayIndex] = 100;
    }Just wondering, I used the final keyword on the the input arguement instead and then used the input arguement directly instead. It seemed to work ok. Is this good programming practice or are there some pitfalls to using this that I'm not aware of?
    (I don't need to change what the input arguement reference points to)
    // Alternate
    methodName(final int inputNumber)
        ActionListener task = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                // Accessing here
                anArray[inputNumber)] = 100;
    }Regards.

    declaring it final guarantees that you will not change the value.Of course it does. That's what it's for. That's what it means. But you're only guaranteeing that to yourself. It doesn't form part of the interface contract so it's no use to anybody else. Which is the bigger picture.
    Whenever i use any anonymous classes i prefer to use the final variables as long as i dont need to change their values.No you don't 'prefer' it, you are forced to do that by the compiler.

  • Use of const keyword in java ?

    Hi All,,
    I want to know the use of const keyword with proper example.
    Many many thx in advance
    Cheers
    Souvik

    I want to know the use of const keyword with proper example.
    There is no proper example, because const is not used in Java. If you want to create a constant, use the final keyword.

  • How to use knowledge base keywords"?

    I have found links to the the knowledge base document "how to use knowledge base keywords" online but all the links lead to a dead end. The document number is 75178, and explains the use of prefixes in the knowledge base keyword search. Has anyone any info on where this page is or if it still exists?
    Thanks
    Nadya

    Apparently, the document's no longer available.

  • Use VB Set keyword with Clone method?

    I am using the TestStand API with Visual Basic 6.0 SP5. Is is necessary to use the Set keyword when calling the Clone method of a PropertyObject? i.e. which is correct:
    Set thePropObj = existingPropObj.Clone("", 0)
    or
    thePropObj = existingPropObj.Clone("", 0)
    Seems the Set keyword would be required, but I am
    running into funny problems with this. I have a step
    that I am trying to create a copy of. (The step contains a call to a LabVIEW VI.) If I omit the Set keyword, execution hangs at the call to Clone. If I include the Set keyword, all information present in the original PropertyObject doesn't seem to get copied to the new one. (Also, oddly enough, if I omit the set keyword, and the step calls a CVI function, everything seems to work
    fine!)
    Anyone have any advice?
    Thanks in advance
    D. LaFosse

    Hello LaFosse,
    You need to use the Set keyword before the clone method statement. However, I have a couple of comments about the code you sent.
    This is the code you sent:
    ' Start up the testStand engine
    Dim theTS As TS.Engine
    Set theTS = New TS.Engine
    ' OK, load in the sequence file I
    ' created. This sequence file
    ' contains nothing more than a call
    ' to a VI in the main stepgroup of
    ' the MainSequence.
    Dim seqFile As SequenceFile
    Set seqFile =
    theTS.GetSequenceFile()
    ' get a handle to the MainSequence
    Dim seq As Sequence
    Set seq = seqFile.GetSequenceByName
    ("MainSequence")
    ' Get a handle to the step that calls
    ' the VI, and a property object for
    ' the step
    Dim theStep As Step
    Set theStep =
    seq.GetStep(0, StepGroup_Main)
    Dim theStepProp As PropertyObject
    Set theStepProp =
    theStep.AsPropertyObject
    ' Create another step. We will attempt
    ' to use Clone to fill in the
    ' properties of this step.
    Dim theOtherStep As Step
    Dim theOtherStepProp As PropertyObject
    Set theOtherStep = theTS.NewStep("",
    TS.StepType_Action)
    Set theOtherStepProp =
    theOtherStep.AsPropertyObject
    ' Call clone...this step will hang.
    theOtherStepProp =
    theStepProp.Clone("", 0)
    Basically the problem is that you are not loading the TypePallete after creating the engine. You shoud include right after the Set theTS = New TS.Engine:
    theTS.LoadTypePaletteFiles
    This should avoid the crash.
    Some Additional comments:
    1. With VB you don't need to create property objects from other objects. All the classes, except the Engine Class, inherit from the Property Object Class. The following Code does the same thing, but without creating propertyobjects directly:
    Sub MySub()
    'Variable Declaration
    Dim theTS As TS.Engine
    Dim seqFile As SequenceFile
    Dim seq As Sequence
    Dim theStep As Step
    Dim theOtherStep As Step
    'Create the Engine
    Set theTS = New TS.Engine
    'Load the Types
    theTS.LoadTypePaletteFiles
    'Get Sequence File
    Set seqFile = theTS.GetSequenceFile()
    'Get Sequence
    Set seq = seqFile.GetSequenceByName("MainSequence")
    'Get Step
    Set theStep = seq.GetStep(0, StepGroup_Main)
    'Clone the Step
    Set theOtherStep = theStep.Clone("", 0)
    'Using the inheritance functionality
    'gets the Step Status
    'Notice that theOtherStep is not a PropertyObject
    'and you can use all the properties and methods that
    'applies to the PropertyObject Class to a Step class
    'in this example
    'Also, in VB when you are typing the statement, you
    'will not see the PropertyObject Class properties and
    'and Methods automatically if the variable is not a
    'PropertyObject type. However, you can still use them
    'as mentioned before
    MsgBox (theOtherStep.GetValString("Result.Status", 0))
    End Sub
    2. When you create or modify sequence files programatically be carefull not to break the license Agreement. You need the development lisence when modifying sequences.
    3. This piece of code is not completed, and you will need to shutdown the engine by the end.
    4. Since you are not handling UI Messages, you will need to be carefull when loading sequences that have the SequenceFileLoad Callback. The engine posts UI Messages when executing this callback. Also when you shutdown the engine, UI Messages are posted. For both operations (Load Sequence and Shuutdown) you may prevent the engine from posting the message (You may check the options parameter for this two methods in TS Programmer Help.)
    5. If you want to run a sequence, again you will need to incorporate in your code the UIMessage Handler part. (You may check the TS Programmer Help->Writing an Application Using the API->UI Messages). Otherwise it may hang since the engine posts UI Messages eventually.
    Regards,
    Roberto Piacentini
    National Instruments
    Applications Engineer
    www.ni.com/support

  • How can see the effect of synchronized keyword

    hi
    I read the follwoing code in some books:
    class W{
    static private int count=0;
    public String name;
    int no;
    private static synchronized int addW(){    return ++count; }
    public W(){ no= addW();  }
    }but I think that synchronized keyword in this code doesn't have an effect, i.e., if we remove it, the output would be ok, can anyone able to change this code such that the output becomes different depend on existance of synchronized keyword.
    thank you

    but I think that synchronized keyword in this code
    doesn't have an effect, i.e., if we remove it, the
    output would be ok,Well, you're mistaken.
    can anyone able to change this
    code such that the output becomes different depend on
    existance of synchronized keyword.No change is necessary. Synchronization is required to ensure proper behavior for the code presented.

Maybe you are looking for