Synchronizing on an int shouldn't be necessairy, should it?

The following example consists of 2 threads that both increment a static int by 1 and decrement it by 1.
Both threads are stopped abruptly after half a second.
What i don't understand is why there are other results possible than 0, 1 or 2.
Synchronizing one a shared object helps but this shouldn't be necessairy. What is going one here?
import java.io.*;
import java.util.*;
public class Test {
    static int a1   = 0;
    public static void main(String[] args) throws Exception {
       Thread t1 = new Thread(new Runnable() {
          public void run() {
             while (true) {a1++; a1--;}
       Thread t2 = new Thread(new Runnable() {
          public void run() {
             while (true) {a1++; a1--;}
       t1.start();
       t2.start();
       Thread.sleep(500);
       t1.stop();
       t2.stop();
       System.out.println("Finished: " +a1);
    } //main
} // Test

Found this:
"In order to provide good performance in the absence
of synchronization, the compiler, runtime, and cache
are generally allowed to reorder ordinary memory
operations as long as the currently executing thread
cannot tell the difference. (This is referred to as
within-thread as-if-serial semantics.) Volatile reads
and writes, however, are totally ordered across
threads; the compiler or cache cannot reorder
volatile reads and writes with each other.
Unfortunately, the JMM did allow volatile reads and
writes to be reordered with respect to ordinary
variable reads and writes, meaning that we cannot use
volatile flags as an indication of what operations
have been completed."
http://www-106.ibm.com/developerworks/java/library/j-j
tp02244.html#6.0
So it looks like it can be done at any level :(
/KajActually, that looks like it prohibits reordering a++/a-- if a is volatile, which the OP said he did.
I've also heard though, that the JMM is broken and that some VM's don't implement volatile correctly. I don't know which ones and what problems they have, but that may have something to do with what he's observing.

Similar Messages

  • Shouldn't the 7800 should have 512MB RAM?

    Hi all,
    I was just wondering, the 7800GT in my Quad only has 256MB of Video RAM, and this is the standard version that Apple offers. However, according to the nVidia website, all 7800 cards (including the Mac version) ship with 512MB.
    What's the deal?
    Thanks,
    -Travis

    Nvidia had 4 versions of the G70 chip on 2 different PCBs.
    The GT version was on a distinct PCB and used 20 Pixel Pipes and ran at 400/500 Mhz.
    The GTX came in 2 different versions, 256 Meg & 512 Meg , on a PSB slightly longer than the GT one. These had 24 Pixel pipes. The 256 Meg version ran around 430/1200 while the 512 version was ultra-rare & used expensive 1.1ns RAM. This coupled with hand-picked primo cores allowed this card to run at 550/1700. This jump in RAM speed represents a significant bandwidth jump.
    Neither of these GTX card were offered for Mac by Apple or Nvidia.
    The final version of the G70 was the Quadro, which uses same PCB as the GTX cards and thus also has 24 Pixel pipes, but runs around 470/1300.
    Thus, there was a faster G70 than our Quadro.
    The 7900 has followed a similar naming scheme with it's G71 processor, with the change that speeds for GPU have jumped 100 Mhz or so and all of the cards now have 24 Pixel Pipes.
    Have a read at Barefeats.com. Some BRILLIANT folks have managed to get the Mega 512 card running in Mac
    And you can always hope that Apple will give the PPC a 21 Gun Salute with a 7950 upgrade as a swan song.

  • Synchronized methods trouble

    hey guys,
    I was under the impression that when u use synchronized methods, when a thread calls it any other threads calling it have to wait. If thats true then can someone help me and point out why my threads aren't waiting :(.
    import java.util.*;
    public class cannibal implements Runnable {
        private static int nonCannibal = 0;
        cannibal(){}
        public synchronized void eat(){
            boolean flag = false;
            try{
                while(nonCannibal == 0){
                    if(flag == false){
                        System.out.println("A cannibal waits in the darkness...");
                        flag = true;
                    wait();
            }catch(InterruptedException e){
                System.out.println("Some Exception!");
            nonCannibal--;
            System.out.println("Cannibal just ate someone in the woods!");
            System.out.println(nonCannibal +" survivors left!");
        public synchronized void dontEatMe(){
            nonCannibal++;
            notify();
            System.out.println("Unsuspecting person ventures to far out in the woods!");
        public synchronized void run(){
            Random generator = new Random();
            int x = generator.nextInt(2);
            if(x == 0){
                //System.out.println("Cannibal was just summoned!");
                eat();
            }else if(x == 1){
               // System.out.println("Unsuspecting Person just summoned!");
                dontEatMe();
         public static void main(String[] args) {
            Thread []x = new Thread[10];
            for(int i = 0; i < 10; i++){
                x[i] = new Thread(new cannibal());
                x.start();
    try{
    Thread.currentThread().sleep(3000);
    }catch(InterruptedException e){

    Demo:
    import java.util.Random;
    class Account {
        private int balance;
        public synchronized void deposit(int amount) {
            if (amount < 0) throw new IllegalArgumentException();
            System.out.println("increasing balance " + balance + " by " + amount);
            balance += amount;
            notifyAll();
        public synchronized void withdraw(int amount) throws InterruptedException {
            if (amount < 0) throw new IllegalArgumentException();
            while (balance < amount) {
                wait();
            System.out.println("decreasing balance " + balance + " by " + amount);
            balance -= amount;
    class Depositer implements Runnable {
        private Account account;
        public Depositer(Account account) {
            this.account = account;
        public void run() {
            try {
                Random rnd = new Random();
                for(int i=0; i<10; ++i) {
                    account.deposit(rnd.nextInt(100));
                    Thread.sleep(1000);
            } catch(InterruptedException e) {
                e.printStackTrace();
    class Withdrawer implements Runnable {
        private Account account;
        public Withdrawer(Account account) {
            this.account = account;
        public void run() {
            try {
                Random rnd = new Random();
                for(int i=0; i<10; ++i) {
                    account.withdraw(rnd.nextInt(200));
            } catch(InterruptedException e) {
                e.printStackTrace();
    class MainClass {
        public static void main(String[] args) {
            Account acct = new Account();
            Withdrawer out = new Withdrawer(acct);
            Depositer in = new Depositer(acct);
            new Thread(out).start();
            new Thread(in).start();
    }

  • Thread synchronizing for dummies

    Hello all and thanks for your time,
    I am trying to do something very easy to make sure I can get synchronized working the right way before I upgrade it into a larger program. All I am trying to do (very stupid and pointless example) is to have only one thread at a time running a certain function. Here is my example:
    Main program:
    import java.io.*;
    public class Test{
      public static void main(String args[]){
        try{
          Test2 a = new Test2(1,1);
          Test2 b = new Test2(2,2);
          a.start();
          b.start();
        }catch(Exception e){
          System.out.println("Error in main");
    Other class:
    import java.io.*;
    import java.lang.*;
    public class Test2 extends Thread{
      int timing = 0;
      int threadNum = 0;
      public Test2(int _timing, int _threadNum){
        timing = _timing;
        threadNum = _threadNum;
      public synchronized void print(int threadNu){
        try{
          System.out.println("threadNum is: " + threadNum);
          for(int i=0;i<10;i++){
            System.out.println("Thread " + threadNum + " reporting in");
            sleep(timing*500);
        }catch(Exception e){
          System.out.println("Error in method priint " + e);
      public void run(){
        try{
          print(threadNum);
        }catch(Exception e){
          System.out.println("Error in thread");
    }The results I recieve are not what I would expect. I am getting random output (like a good thread), but I want all Thread 1 first followed by all Thread 2. Any ideas on the mistake I am making?

    Hi,
    you do not make a mistake, you might habe the wrong expectations.
    Your programm creates and starts two threads, which are then running independently. There is absolutely no reason, why thread 2 should wait for thread 1 to complete.
    You would explicitely have to code for that waiting, e.g. by synchronizing both threads on a common object. Then only one thread could run at the same time. If you do not synchronize, they run concurrently.

  • Casting int to a byte -- retreiving the lowest 8 bits

    Yo, thought i'd try to open up some debate on this topic. I wrote a data feed that needed to grab the lower 8 bits out of an int, so i wrote what i believed to be the standard way of doing this, which was effectively
    public static byte intToByte( int c ) {
            return (byte) (c & 0xff);
    }A colleague looking through my code asked whether the & 0xff was necessary, and did i believe that there was any value of c for which it made a difference, as he believed that this was equivalent to just
    return (byte)c; My immediate thought was worrying about byte in java being signed, and having data screwed up, so i ran some tests.. and on every value i tried (byte)c is indeed equivalent to (byte)( c & 0xff ).
    My argument was to be that (byte)( c & 0xFF ); is great code to read as a maintainer, because it;'s immediately obvious that you are strictly interested in the lowest 8 bits of the int, and nothing else is of importance, and a simple (byte)c; can look naive and make every developer looking at the code for the first time think it's incorrect.
    However, i knew his comeback would be that the datafeed has an overriding need for speed, so i ran some tests comparing the repeated operation of (byte)c to (byte)(c & 0xff ) over a range of 100,000 numbers (test repeated several times to obviate startup times). It turned out that doing the & 0xff added about 30% to execution time on my machine (java 1.5 on WinXP). That's quite a severe penalty for a very common operation! I think i'm going to change the code to cast straight to a byte and leave a big comment beforehand explaining how it's equivalent to (byte)(c & 0xff );
    This got me wondering how it was implemented in the core java libraries though, since OutputStream has a method to write a byte that actually takes an int parameter. How does this work? Most of the lowest level OutputStream implementations seem to end up going to native to do this (understandably), so i dug out ByteArrayOutputStream. This class does optimise away the & 0xFF and is roughly
        public synchronized void write(int b) {
                �
                buf[count] = (byte)b;
                �
        }No problems with that, so writing to these babies will be fast. But then i started wondering about the methods of DataOutputStream, which is heavily used by use for serialising (a great deal of) internal data flow. Unfortunately in this class there are a lot of redundant & 0xFFs:
    public final void writeShort(int v) throws IOException {
            out.write((v >>> 8) & 0xFF);
            out.write((v >>> 0) & 0xFF);
            incCount(2);
    public final void writeInt(int v) throws IOException {
          out.write((v >>> 24) & 0xFF);
          out.write((v >>> 16) & 0xFF);
          out.write((v >>>  8) & 0xFF);
          out.write((v >>>  0) & 0xFF);
          incCount(4);
    }[The v >>> 0 seems to be optimised out at runtime and i get no execution time difference between ( v >>> 0)  & 0xff that and ( v & 0xff ) so i got no problems with that]
    which again seems ok on inspection because the code looks tidy and clean and easy to understand, but i need to hit these things very heavily so would rather they were 30% faster than easy to read. Interestingly they've taken an entirely different approach for writing out a long value:
    public final void writeLong(long v) throws IOException {
            writeBuffer[0] = (byte)(v >>> 56);
            writeBuffer[1] = (byte)(v >>> 48);
            writeBuffer[2] = (byte)(v >>> 40);
            writeBuffer[3] = (byte)(v >>> 32);
            writeBuffer[4] = (byte)(v >>> 24);
            writeBuffer[5] = (byte)(v >>> 16);
            writeBuffer[6] = (byte)(v >>>  8);
            writeBuffer[7] = (byte)(v >>>  0);
            out.write(writeBuffer, 0, 8);
            incCount(8);
    }both using a private buffer field for the writing before squirting it all out, and not bothering to mask the lower 8 bits. It seems strange that writeLong appears optimised, but writeInt and writeShort are not.
    What does everyone else think? Are there any other heavy users of DataOutputStream out there that would rather have things written faster? I guess i'm going to be writing my own version of DataOutputStream in the meantime, because we're writing so much data over these and i'm in an industry where milliseconds matter.

    To my knowledge, in your situation, the & 0xFF is not necessary. I believe that the most common use of the mask in this case is actually to treat the lower 8 bits as an unsigned integer. For example:
    int value = 65530;
    int anotherValue = value & 0xFF; // anotherValue == 250Anyway, the case space is small enough that I just brute forced your problem. Under v1.5.0_07 on Linux, (byte)i and (btye)(i & 0xFF) are definitely the same:
    for (int i=Integer.MIN_VALUE;i<Integer.MAX_VALUE;i++)
        byte a = (byte)i;
        byte b = (byte)(i & 0xFF);
        if (a!=b) System.out.println(i);
    byte a = (byte)(Integer.MAX_VALUE);
    byte b = (byte)(Integer.MAX_VALUE & 0xFF);
    if (a!=b) System.out.println(Integer.MAX_VALUE);Perhaps the & 0xFF was in response to some older bug or other behavior.

  • A question about synchronized Lists...

    If I have a synchronized list, and I have a synchronized block in one thread with a lock on that list (synchronized(List)) am i supposed to be able to add an item to that list directly (using the List.add() method) from another thread while I'm still in the synchronized block previously described?
    I have some code here where I tried to test that and the answer that I got is that it is possible while (I believe) it's not possible theoretically speaking.
    import java.util.*;
    public class Warehouse implements Runnable{
         List<String> items = Collections.synchronizedList(new ArrayList<String>());
    //     List<String> items = new ArrayList<String>();
         public static void main(String[] args){
              Warehouse w = new Warehouse();
              Manager m = new Manager(w);
              Thread one = new Thread(w);
              Thread two = new Thread(m);
              one.start();
              two.start();
         public void add(String t){
              synchronized(items){               
                   for(int i=0; i<2; ++i){
                        System.out.println("Warehouse added item...");
                        try{
                        Thread.sleep(500);
                        }catch(InterruptedException ie){
                             ie.printStackTrace();
                   items.add(t);
                   items.notify();
         public void run(){
              for(int i=0; i<1; ++i){
                   synchronized(items){
                        while(items.isEmpty()){
                             try{
                             System.out.println("Warehouse waiting...");
                             items.wait();
    //                         System.out.println("Warehouse after waiting...");
                             for(int j=0; j<2; ++j){
                                  System.out.println("Warehouse after waiting...");
                                  try{
                                  Thread.sleep(500);
                                  }catch(InterruptedException ie){
                                       ie.printStackTrace();
                             }catch(InterruptedException ie){
                                  ie.printStackTrace();
    class Manager implements Runnable{
         Warehouse w;
         public Manager(Warehouse w){
              this.w = w;
         public void run(){
              for(int i=0; i<1; ++i){               
                   System.out.println("Manager Adding item...");
                   w.add("articulo");                              
                   for(int j=0; j<5; ++j){
                        w.items.add("jeje");
                        try{
                        Thread.sleep(500);
                        }catch(Exception ex){ex.printStackTrace();}
                        System.out.println("Manager adding to items");
                   System.out.println("Manager finished with warehouse...");
    }Output:
    Warehouse waiting...
    Manager Adding item...
    Warehouse added item...
    Warehouse added item...
    *Warehouse after waiting...*
    *Manager adding to items*
    *Warehouse after waiting...*
    *Manager adding to items*
    Manager adding to items
    Manager adding to items
    Manager adding to items
    Manager finished with warehouse...The code in "bold" (with the tokens) isn't supposed to happen concurrently as I understand it since the "warehouse after waiting" statement it's in the synchronized block with a lock on the items list and the "manager adding to items" statement is adding an item to that list through a direct reference to that list...

    When the manager thread notifies the items (warehouse thread), the warehouse thread does not have to wake up automatically, it has to compete for the items lock then wait for its Thread context to execute. Which means that the manage is able to continue to execute - adding to items manually, and eventually sleep()ing. When the manager thread sleeps that is a good place for a Thread context switch, and if the JVM takes that opportunity to do so, then the warehouse thread regains the lock and would prevent further access to items. But at some point the Thread context will switch again (probably when warehouse thread goes to sleep). Now the manager thread can wake up, print that it is working because that code is not protected by any synchronized lock. Then when it attempts to add to items again it blocks. Another thread context switch allows the warehouse to complete its work, finish up, and release the items lock. Manager can then get the lock on items and finish its work. The results would be exactly as you display them. Here is a possible walk-through of the threading paths taken:
    Thread == Warehouse
    i = 0
      lock on items
        items.isEmpty == true
          print "Warehouse is waiting"
          items.wait (unlock items)
    /* CONTEXT SWITCH */
    Thread == Manager
    i = 0
      print ""Manager Adding item..."
      locking items
        i = 0
          printing "Warehouse added item..."
          sleeping 500
        i = 1
          printing "Warehouse added item..."
          sleeping 500
        i ! < 2
        locking items
          adding to items
        unlocking items
        notifying items (wait will unlock eventually)
      unlocking items
      j = 0
        locking items
          adding to items
        unlocking items
        sleeping 500
    /* CONTEXT SWITCH */
    Thread == Warehouse
          items.wait (regain lock and get context)
          j = 0
            prinitng "Warehouse after waiting..."
            sleeping 500
    /* CONTEXT SWITCH */
    Thread == Manager
        sleeping 500 is done
        printing "Manager adding to items"
      j = 1
        locking items (blocking until items is available)
    /* CONTEXT SWITCH */
    Thread == Warehouse
            sleeping 500 is done
          j = 1
            printing "Warehouse after waiting..."
          j ! < 2
        itemse ! isEmpty
      unlocking items
    i ! < 1
    /* End of Warehouse Thread */
    /* CONTEXT SWITCH */
    Thread == Manager
        locking items (lock available)
          adding to itemes
        unlock items
        sleeping 500
        printing "Manager adding to items"
      j = 2
        locking items
          adding to itemes
        unlock items
        sleeping 500
        printing "Manager adding to items"
      j = 3
        locking items
          adding to itemes
        unlock items
        sleeping 500
        printing "Manager adding to items"
      j = 4
        locking items
          adding to itemes
        unlock items
        sleeping 500
        printing "Manager adding to items"
      j ! < 5
      printing "Manager finished with warehouse..."
    i ! < 1
    /* End of Manager Thread */So the theory an practice are the same - you can not access the items object when it is locked by another thread. The problem is that your test does not demonstrate when locks are held and released - some of the output you expect to be protected is not and so you mis-interpret the code.

  • Problems with synchronizing an element in an array

    I have a class that extends ArrayList. I have another class called "Elem" that works as elements for the ArrayList. Multiple threads will work on this list.
    When I get an element from the ArrayList I would like to lock only this element so another thread can delete other elements in the list.
    I have made this method for getting and locking an element:
         public String get(int id)
              String res ="No such file, try command list";
              int size = this.size();
              for (int i = 0; i<size;i++)
                   Elem ifo = (Elem)this.get(i);
                   if(ifo.getId() == id)
                        synchronized(ifo)
                             try {
                                  Thread.sleep(4000);
                             } catch (InterruptedException e) {
                                  e.printStackTrace();
                             res = ifo.getData() + " Received";
                        break;
              return res;
         }I have made the operation last for 4 seconds because I test if the object is locked with the follwing delete method:
         public synchronized String del(int id)
              String res =" no file";
              int size = this.size();
              for (int i = 0; i<size;i++)
                   Elem ifo = (Elem)this.get(i);
                   if(ifo.getId() == id)
                        super.remove(ifo);
                        res = ifo.getId() + " deleted!";
                        break;
              return res;
         }But when I run the program and start reading an element that I try to delete at the same time it gets deleted! Why does the "del" method not block until the element has been read?

    Ok here is what I am trying to do.
    1) Thread 1 get an element from list A. At the SAME
    time thread 2 deletes a different element from list
    A.Everything I've said still applies. What do you mean "at the SAME time"? And why does it have to be "at the SAME time"? What if whatever triggers cause the two actions happen "at the SAME time," but the actual actions happen a millisecond apart?
    currently only serial execution works, since all the
    methods on the list are synchronized.Again, anytime you're accessing shared data from multiple threads, you must synchronize. That syncing may be very, very brief--say just to atomically update a counter or "available" bitmap or something, but if there's shared data--such as a bitmap that keeps track of which slots are used--read/updates, like "find an available one, mark it used, and give me its index"--must be atomic, so there must be some synchronization.
    Or else different threads get different sections of the array assigned to them.

  • 'synchronized' method problem

    Hi, I want to listen to your opinion on using 'synchronized' on
    a huge method. I know it will degrade performance alot. However, in some cases it may be inevitable using 'synchrnoized' keyword on big method. Of course, there is 'synchronized' block also available in Java, but it is not a solution in some cases. For example, in below code
    interface Condition {
    boolean isCorrect();
    class Foo {
    int value = 0;
    void addCondtition(Condition c) ;
    synchronized boolean increaseCount(int quantity)
    //loop through all added Conditions and executes each
    Condition's isCorrect();
    //if all Conditions are true then increase value as much as the
    received quantity
    In above example, while checking all added conditions, it is possible
    the 'value' is updated by other threads in multi-threaded program by calling increaseCount. Also, if added Conditions are refering to the 'value' to determine, then the 'value' should not be updated in the middle of Condition checking process.
    Solution to protect 'value' from other thead is 'synchronized' on increaseCount. I can't come up any other solution. But problem is
    since multiple Conditions can be added, execution time of the increaseCount method can significantly increased.
    Does anyone have better solution to avoid 'synchronized' on such a huge method?

    Hi, I want to listen to your opinion on using
    'synchronized' on
    a huge method. I know it will degrade performance
    alot. That's a rather common, unfounded and generally inaccurate assumption you've got there. It's true that it will adversely affect performance but not necessarily by "a lot".
    However, in some cases it may be inevitable
    using 'synchrnoized' keyword on big method. Of
    course, there is 'synchronized' block also available
    in Java, but it is not a solution in some casesThat's technically not true, but I understand what you mean.
    . For
    example, in below code
    interface Condition {
    boolean isCorrect();
    lass Foo {
    int value = 0;
    void addCondtition(Condition c) ;
    synchronized boolean increaseCount(int quantity)
    //loop through all added Conditions and
    executes each
    Condition's isCorrect();
    /if all Conditions are true then increase value as
    much as the
    received quantity
    In above example, while checking all added
    conditions, it is possible
    the 'value' is updated by other threads in
    multi-threaded program by calling increaseCount.
    Also, if added Conditions are refering to the 'value'
    to determine, then the 'value' should not be updated
    in the middle of Condition checking process.
    Solution to protect 'value' from other thead is
    'synchronized' on increaseCount. I can't come up any
    other solution. But problem is
    since multiple Conditions can be added, execution
    time of the increaseCount method can significantly
    increased.
    Does anyone have better solution to avoid
    'synchronized' on such a huge method?In your example there isn't an obvious alternative. Refactoring your design might create some opportunities. Perhaps you'd be better served by explaining to us what you're hoping to achieve rather than trying to discuss one specific method's implementation.

  • Understanding synchronized

    I have a class that extends ArrayList that has the following two methods:
         public synchronized String getFile(int id)
              try
                   Thread.sleep(4000);
              catch (InterruptedException e){e.printStackTrace();}          
              String res = this.get(id);
              return res;
         public synchronized void delFile(int id)
                      super.remove(id);
         }I have made the get operation take 4 seconds to test the concurrency of the program. When a thread calls getFile the delFile methods is locked until the getFile returns.
    I thought that it was only the called synchronized method that would be locked and that the other synchronized methods would be free.
    Will a call to a synchronized method in a class lock all other synchronized methods in the same class?

    A synchronized method acquires a monitor before it executes.
    For a class (static) method, the monitor associated with the Class object for the method's class is used.
    For an instance method, the monitor associated with this (the object for which the method was invoked) is used.
    Therefore, in your example, if a given object's monitor has been acquired (e.g. by calling getFile method), then any call to other synchronized method on the same object (e.g. delFile) will wait for the monitor to be released.
    You can use synchronized blocks instead, to achieve another behaviour (e.g. by specifying another object for the lock.)

  • Synchronized execution of threads

    How do I synchronize the execution of two threads?
    I am using two threads, the main thread to handle input and output, and a secondary thread to execute third party procedural code.
    The main thread has to wait for commands from the procedural thread and then relay those to the client.
    While the client has control, the procedural thread has to wait and vice versa. I couldn't get this to work yet.
    Below is the simplest example I could extract from the code. I have tried it with java.util.concurrent as well but couldn't pause the main (servlet) thread with that, only threads in the thread pool.
    Your help will be greatly appreciated!
    Here is the code :
    [http://connexioncafe.info/java/SyncExample.java|http://connexioncafe.info/java/SyncExample.java]
    Thank you in advance!

    I'll try and post the code in three parts:
    * This is a simulation of a server.  It has two threads:
    * [1] main thread used for input and output (in this case communication with command line client).
    *      it could be a servlet in practice
    * [2] and a procedural thread for executing third party code (e.g. PHP)
    * The main thread start the procedural thread
    *      *the main thread waits
    * the procedural thread reads a stack, one item at a time
    * if the command in the stack is an input or output command
    * *the procedural thread sets the command on the main thread
    * *the procedural thread notifies/wakes up the main thread [A]
    * *the procedural thread waits
    * the main thread is woken up by the procedural thread [A]
    * *it executes the command as set by the procedural thread
    * *it sets the result on the message variable
    * *it notifies/wakes up the procedural thread
    * *the main thread waits for the next command from the procedural thread [B]
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    public class SyncExample {
    //a simple int value that is visible by both threads used for messaging
    public int message = -1;
    //a command that is passed between threads either executing on the client or server side
    public int command = -1;
    //all the possible commands
    public static final int DO_INPUT = 1;
    public static final int DO_OUTPUT = 2;
    public static final int DO_QUIT = 3;
    public static final int DO_STORAGE = 4;
    public static final int DO_PROCESS = 5;
    //commands with an int value greater or equal to SERVER_SIDE executes on the server side
    public static final int SERVER_SIDE = 3;
    //a lock used to wait() the procedural thread
    public final Object procLock = new Object();
    //a lock used to wait() the main thread
    public final Object mainLock = new Object();
    //a lock used to sync message value between threads
    public final Object msgLock = new Object();
    //a lock used to sync command value between threads
    public final Object cmdLock = new Object();
    //========================================================================== Procedural Thread
    public class ProcThread extends Thread {
    //some third party code that will be executed by this thread
    private AlgorithmI aProc;
    //some functions that will be used to execute the third party code
    private final SysFunctions sysFunctions;
    public ProcThread(AlgorithmI aProc, SysFunctions sf) {
    this.aProc = aProc;
    this.sysFunctions = sf;
    @Override
    public void run() {
    int cmd = 0;
    for (int i = 0; i < aProc.getStack().length; i++) {
    cmd = aProc.getStack();
    if (cmd >= SERVER_SIDE) {
    switch (cmd) {
    case DO_STORAGE:
    sysFunctions.storage();
    break;
    case DO_PROCESS:
    aProc.calculate();
    break;
    default:
    break;
    } else {
    setCommand(cmd);
    //TODO: RESUME MAIN THREAD SO THAT IT CAN COMMUNICATE WITH CLIENT
    synchronized (mainLock) {
    mainLock.notify();
    //TODO: PAUSE THIS PROCEDURAL THREAD UNTIL MAIN THREAD HAS COMPLETED THE COMMAND
    synchronized (procLock) {
    try {
    procLock.wait();
    } catch (InterruptedException ex) {
    //interrupted
    switch (cmd) {
    case DO_INPUT:
    aProc.setValue(getMessage());
    break;
    case DO_OUTPUT:
    break;
    default:
    break;
    * An interface that has to be implemented by third party procedures
    public interface AlgorithmI {
    public void calculate();
    public int[] getStack();
    public void setValue(int message);
    //written by someone else which I do not have control over
    public class ThirdPartyProcedure implements AlgorithmI {
    //just two values that will be added together
    private int value1 = 0;
    private int value2 = 0;
    // an array of commands that will be executed by ProcThread
    private int[] stack = {
    SyncExample.DO_STORAGE,
    SyncExample.DO_INPUT,
    SyncExample.DO_STORAGE,
    SyncExample.DO_INPUT,
    SyncExample.DO_STORAGE,
    SyncExample.DO_PROCESS,
    SyncExample.DO_STORAGE,
    SyncExample.DO_OUTPUT,
    SyncExample.DO_QUIT};
    public synchronized void setValue(int value) {
    if (value1 == 0) {
    value1 = value;
    } else {
    value2 = value;
    public void calculate() {
    setMessage(value1 + value2);
    public int[] getStack() {
    return stack;
    // continued below...
    Edited by: datahpile on Aug 20, 2010 6:27 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Question on synchronized method / block and Thread Cache

    Hi all,
    I came across a blog post at http://thejavacodemonkey.blogspot.com/2007/08/making-your-java-class-thread-safe.html which is talking about making Java classes thread safe. But, I was surprised to see that a thread can have my class' instance variable in its cache. Also, I have couple of questions on the things posted in the blog. I want to get the opinion from Java experts here.
    1. Given the example class
    class MyClass{
         private int x;
         public synchronized void setX(int X) { this.x = x; }
         public synchronized int getX() { return this.x; }
    Having the following instructions in two threads won't guarantee that it will print 1 and 2 as other thread can get the slot and call setX to modify the value - Am I right?
    obj is an MyClass Instance available to both the threads
    Thread 1:
    obj.setX(1);
    System.out.println(obj.getX());
    Thread 2:
    obj.setX(2);
    System.out.println(obj.getX());
    It will print 1 and 2 (in any order) only if I synchronize these calls on "obj" as follows - Is my understanding correct or ???
    Thread 1:
    synchronized(obj)
    obj.setX(1);
    System.out.println(obj.getX());
    Thread 2:
    synchronized(obj)
    obj.setX(2);
    System.out.println(obj.getX());
    2. If my understanding on point 1 (given above) is right, What the blog-post says is wrong as I cannot even expect my thread 1 to print 1 and thread 2 to print 2. Then, again a question arises as why a thread cache has a object's instance variable value in its cache and need to make my instance variable volatile. Can anyone explain me in detail? Won't the thread always refer the heap for Object's instance variable value?
    Thanks in advance,
    With regards,
    R Kaja Mohideen

    your basic understanding (as far as i can understand what you've written) seems to be correct. if you run your first 2 threads, you can get "11", "12", "21", or "22" (ignoring newlines). if you run your second 2 threads, you can get "12" or "21".
    i'm not sure i follow your second point about your thread's "cache". i think you are asking about the visibility of changes between threads, and, no, there is not concept of a shared "heap" in the memory model. basically, (conceptually) each thread has its own working memory, and it only shares updates to that memory when it has to (i.e. when a synchronization point is encountered, e.g. synchronized, volatile, etc). if every thread was forced to work out of a shared "heap", java on multi-core systems would be fairly useless.

  • Why is int?

    Hi I am learning java at moment. I don't understand why is int not char instead in the method indexOf(int char) under String class.
    cheers

    It may have a reason to be, but it's a mystery for me.
    Also this argument type from
    java.io.ByteArrayOutputStream is a mystery:
    * Writes the specified byte to this byte array output
    stream.
    * @param   b   the byte to be written.
    public synchronized void write(int b) {  // Why is int
    instead of byte?
    int newcount = count + 1;
    if (newcount > buf.length) {
    byte newbuf[] = new byte[Math.max(buf.length
    .length << 1, newcount)];
    System.arraycopy(buf, 0, newbuf, 0, count);
    buf = newbuf;
    buf[count] = (byte)b;
    count = newcount;
    That is for consistency. read returns an int, as it has to be able to return -1 to indicate no data available, so it makes sense for write to be able to handle data direct from a read, without having to cast it. It's convenience, rather than good design, though.
    RObin

  • Pbroblems with Synchronized methods --- please help

    ** One Thread calls a synchronized method using an object (obj1) of a Class (Class name - meth_class) and occupies the monitor of that particular object (obj1). Then no other Thread can call that particular synchronized method or any other synchronized method of the object (obj1) of a Class (Class name - meth_class). **
              IF THE ABOVE DEFINITION IS TRUE PLEASE HELP ME OUT WITH THE FOLLOWING:
    Please go through the code below:-
    class meth_class
              volatile boolean valueset=false;
              int var;
              synchronized int get()
                        if (!valueset)
                                  try
                                            wait();
                                  catch (InterruptedException e)
                                            System.out.println("Consumer interrupted");
                        System.out.println("Get - " + var);
                        valueset=false;
                        notify();
                        return var;
              synchronized void put(int x)
                        if (valueset)
                                  try
                                            wait();
                                  catch (InterruptedException e)
                                            System.out.println("Producer interrupted");
                        this.var=x;
                        System.out.println("Put - " + var);
                        valueset=true;
                        notify();
    class producer implements Runnable
              meth_class obj;
              Thread thrd;
              producer(meth_class x)
                        obj=x;
                        thrd=new Thread(this, "Producer");
                        thrd.start();
              public void run()
                        int var=0;
                        while(true)
                                  obj.put(var++);
    class consumer implements Runnable
              meth_class obj;
              Thread thrd;
              consumer(meth_class x)
                        obj=x;
                        thrd=new Thread(this, "Consumer");
                        thrd.start();
              public void run()
                        while(true)
                                  obj.get();
    class main_thrd
              public static void main(String args[])
                        meth_class obj=new meth_class();
                        new producer(obj);
                        new consumer(obj);
                        System.out.println("Press Control-C to stop");
    My Questions are:
    1.     class main_thrd creates two objects as ?new producer(obj)? and ?new consumer(obj)?. Now both these objects creates 2 threads and try to call two different Synchronized methods of same CLASS ? ?meth_class? through a single object by the name of ?obj? created in class main_thrd. Now as ?new producer(obj)? object is created first in the class main_thrd, the Thread created by it enters the monitor of object (obj) and locks it. Then as per the rule the Thread created by ?new consumer(obj)? object never gets to occupy the monitor of the object (obj) because Producer is in an infinite loop. BUT THEN WHY WE HAVE ? GET - ** ? VALUES PRINTED IN THE OUTPUT.
    Please any one help me out,
    (THANKS FOR ALL YOUR HELP)

    Now as ?new producer(obj)? object is called first in the class main_thrd, the Thread created by it enters the monitor of object (obj) and locks it.Though new producer(obj) is called first, it is not necessary that the thread created by it gets the lock of object(obj) first. This is false
    assumption.
    Next, even if we assumed that it gets the lock of given object first,
    while(true)
        obj.put(var++);
    }The lock of Object(obj) is released when the obj.put(var++) returns and any one can get hold of lock of the Object(obj) at that instant.
    In fact, next time obj.put(var++) is called, it will have to wait until it can get lock of the given object.

  • SAP PI conceptual best practice for synchronous scenarios

    Hi,
    <br /><br />Apologies for the length of this post but I'm sure this is an area most of you have thought about in your journey with SAP PI.
    <br /><br />We have recently upgraded our SAP PI system from 7.0 to 7.1 and I'd like to document  best practice guidelines for our internal development team to follow.
    I'd be grateful for any feedback related to my thoughts below which may help to consolidate my knowledge to date.
    <br /><br />Prior to the upgrade we have implemented a number of synchronous and asynchronous scenarios using SAP PI as the hub at runtime using the Integration Directory configuration.
    No interfaces to date are exposes directly from our backend systems using transaction SOAMANAGER.
    <br /><br />Our asynchronous scenarios operate through the SAP PI hub at runtime which builds in resilience and harnesses the benefits of the queue-based approach.
    <br /><br />My queries relate to the implementation of synchronous scenarios where there is no mapping or routing requirement.  Perhaps it's best that I outline my experience/thoughts on the 3 options and summarise my queries/concerns that people may be able to advise upon afterwards.
    <br /><br />1) Use SAP PI Integration Directory.  I appreciate going through SAP PI at runtime is not necessary and adds latency to the process but the monitoring capability in transaction SXMB_MONI provide full access for audit purposes and we have implemented alerting running hourly so all process errors are raised and we handle accordingly.  In our SAP PI Production system we have a full record of sync messages recorded while these don't show in the backend system as we don't have propogation turned on.  When we first looked at this, the reduction in speed seemed to be outweighed by the quality of the monitoring/alerting given none of the processes are particularly intensive and don't require instant responses.  We have some inbound interfaces called by two sender systems so we have the overhead of maintaing the Integration Repository/Directory design/configuration twice for these systems but the nice thing is SXMB_MONI shows which system sent the message.  Extra work but seemingly for improved visibility of the process.  I'm not suggesting this is the correct long term approach but states where we are currently.
    <br /><br />2) Use the Advanced Adapter Engine.  I've heard mixed reviews about this functionaslity, there areh obvious improvements in speed by avoiding the ABAP stack on the SAP PI server at runtime, but some people have complained about the lack of SXMB_MONI support.  I don't know if this is still the case as we're at SAP PI 7.1 EHP1 but I plan to test and evaluate once Basis have set up the pre-requisite RFC etc. 
    <br /><br />3) Use the backend system's SOAP runtime and SOAMANAGER.  Using this option I can still model inbound interfaces in SAP PI but expose these using transaction SOAMANAGER in the backend ABAP system.  [I would have tested out the direct P2P connection option but our backend systems are still at Netweaver 7.0 and this option is not supported until 7.1 so that's out for now.]  The clear benefits of exposing the service directly from the backend system is obviously performance which in some of our planned processes would be desirable.  My understanding is that the logging/tracing options in SOAMANAGER have to be switched on while you investigate so there is no automatic recording of interface detail for retrospective review. 
    <br /><br />Queries:
    <br /><br />I have the feeling that there is no clear cut answer to which of the options you select from above but the decision should be based upon the requirements.
    <br /><br />I'm curious to understand SAPs intention with these options  -
    <br /><br />- For synchronous scenarios is it assumed that the client should always handle errors therefore the lack of monitoring should be less of a concern and option 3 desirable when no mapping/routing is required? 
    <br /><br />- Not only does option 3 offer the best performance, but the generated WSDL is ready once built for any further system to implement thereby offering the maximum benefit of SOA, therefore should we always use option 3 whenever possible?
    <br /><br />- Is it intended that the AAE runtime should be used when available but only for asynchronous scenarios or those requiring SAP PI functionality like mapping/routing otherwise customers should use option 3?  I accept there are some areas of functionality not yet supported with the AAE so that would be another factor.
    <br /><br />Thanks for any advice, it is much appreciated.
    <br /><br />Alan
    Edited by: Alan Cecchini on Aug 19, 2010 11:48 AM
    Edited by: Alan Cecchini on Aug 19, 2010 11:50 AM
    Edited by: Alan Cecchini on Aug 20, 2010 12:11 PM

    Hi Aaron,
    I was hoping for a better more concrete answer to my questions.
    I've had discussion with a number of experienced SAP developers and read many articles.
    There is no definitive paper that sets out the best approach here but I have gleaned the following key points:
    - Make interfaces asynchronous whenever possible to reduce system dependencies and improve the user experience (e.g. by eliminating wait times when they are not essential, such as by sending them an email with confirmation details rather than waiting for the server to respond)
    - It is the responsibility of the client to handle errors in synchronous scenarios hence monitoring lost through P-P services compared to the details information in transaction SXMB_MONI for PI services is not such a big issue.  You can always turn on monitoring in SOAMANAGER to trace errors if need be.
    - Choice of integration technique varies considerably by release level (for PI and Netweaver) so system landscape will be a significant factor.  For example, we have some systems on Netweaver 7.0 and other on 7.1.  As you need 7.1 for direction connection PI services we'd rather wait until all systems are at the higher level than have mixed usage in our landscape - it is already complex enough.
    - We've not tried the AAE option in a Production scenarios yet but this is only really important for high volume interfaces, something that is not a concern at the moment.  Obviously cumulative performance may be an issue in time so we plan to start looking at AAE soon.
    Hope these comments may be useful.
    Alan

  • How to divide two int numbers and get a fraction ?

    I am dividing two int numbers and the result should be a fraction but I am always getting a zero
    set @result= @num1/@num2  
    when num1=50 and num2=100

    I am dividing two int numbers and the result should be a fraction but I am always getting a zero
    set @result= @num1/@num2  
    You can either one of the values as a decimal or float type, or just multiply one of the values by 1.0.
    set @result= @num1/@num2*1.0
    Dan Guzman, SQL Server MVP, http://www.dbdelta.com

Maybe you are looking for

  • Cannot send webmailwod from iCloud on laptop (Windows)ndows)

    For 9 months I am using my laptop running on Windows (no mailprogram) for receiving and sending mails. All in a sudden message cannot send this mail at the moment. On my Iphone I still can send mails. I checked my browser (firefox), my virusscan AVAS

  • Acrobat 9 pro install error!

    So I got my licensed version of acrobat 9 finally only to get this stupid error. Unstalled and installed twice obvioulsly did not work. I have had nothing but problems with Adobe CS5 and OSX 10.6.4 this is starting to get old... I refuse to call Adob

  • Function Module Extraction!! Please HELP!!

    Hi Experts, This is my first project in BW. Please help!! The existing function module using 3 tables to extract (Full update) data. Now, I have to enable the delta for this generic extractor. I have seen RSA3_GET_DATA_SIMPLE (nothing specified for D

  • EDI/IDocs for WMS

    Hi all, I need sample code and processing steps for EDI-IDocs for WMS concept.

  • Send view/ table in email

    Am trying to send an email from apex with a view, but I dont know how to include it in the mail body... This what I use as process when click on button... DECLARE CURSOR EMP_CURSOR IS SELECT email FROM employee; l_id NUMBER; BEGIN FOR Emp_REC IN EMP_