Slow performance when multiple threads access static variable

Originally, I was trying to keep track of the number of function calls for a specific function that was called across many threads. I initially implemented this by incrementing a static variable, and noticed some pretty horrible performance. Does anyone have an ideas?
(I know this code is "incorrect" since increments are not atomic, even with a volatile keyword)
Essentially, I'm running two threads that try to increment a variable a billion times each. The first time through, they increment a shared static variable. As expected, the result is wrong 1339999601 instead of 2 billion, but the funny thing is it takes about 14 seconds. Now, the second time through, they increment a local variable and add it to the static variable at the end. This runs correctly (assuming the final increment doesn't interleave which is highly unprobable) and runs in about a second.
Why the performance hit? I'm not even using volatile (just for refernce if I make the variable volatile runtime hits about 30 seconds)
Again I realize this code is incorrect, this is purely an interesting side-expirement.
package gui;
public class SlowExample implements Runnable
     public static void main(String[] args)
          SlowExample se1 = new SlowExample(1, true);
          SlowExample se2 = new SlowExample(2, true);
          Thread t1 = new Thread(se1);
          Thread t2 = new Thread(se2);
          try
               long time = System.nanoTime();
               t1.start();
               t2.start();
               t1.join();
               t2.join();
               time = System.nanoTime() - time;
               System.out.println(count + " - " + time/1000000000.0);
               Thread.sleep(100);
          catch (InterruptedException e)
               e.printStackTrace();
          count = 0;
          se1 = new SlowExample(1, false);
          se2 = new SlowExample(2, false);
          t1 = new Thread(se1);
          t2 = new Thread(se2);
          try
               long time = System.nanoTime();
               t1.start();
               t2.start();
               t1.join();
               t2.join();
               time = System.nanoTime() - time;
               System.out.println(count + " - " + time/1000000000.0);
          catch (InterruptedException e)
               e.printStackTrace();
           * Results:
           * 1339999601 - 14.25520115
           * 2000000000 - 1.102497384
     private static int count = 0;
     public int ID;
     boolean loopType;
     public SlowExample(int ID, boolean loopType)
          this.ID = ID;
          this.loopType = loopType;
     public void run()
          if (loopType)
               //billion times
               for (int a=0;a<1000000000;a++)
                    count++;
          else
               int count1 = 0;
               //billion times
               for (int a=0;a<1000000000;a++)
                    count1++;
               count += count1;
}

Peter__Lawrey wrote:
Your computer has different types of memory
- registers
- level 1 cache
- level 2 cache
- main memory.
- non CPU local main memory (if you have multiple CPUs with their own memory banks)
These memory types have different speeds. Depending on how you use a variable affects which memory it is placed in.Plus you have the hotspot compiler kicking in sometime during the run. In other words for some time the VM is interpreting the code and then all of a sudden its compiled and executing the code compiled. Reliable micro benchmarking in java is not easy. See [Robust Java benchmarking, Part 1: Issues|http://www.ibm.com/developerworks/java/library/j-benchmark1.html]

Similar Messages

  • Slow performance when using cursor with bind variable

    i'm facing the problem mentioned in the subject.
    whenever i use the bind variable it would take more than 5mins to fetch 157 records, but if i hardcode the value ( not using variable ) it would take only 10sec to fetch 157 records.
    can anyone give me some guide to solve this problem? thank you..
    Code :
    DECLARE
    cursor cur1(l_startdate IN varchar2,l_enddate IN varchar2) IS
    select * from shipment ship where ship.insertion_date >= to_date(l_startdate,'DD-MM-YYYY HH24:MI:SS') and ship.insertion_date < to_date(l_enddate ,'DD-MM-YYYY HH24:MI:SS')
    TYPE shipment_aat IS TABLE OF cur1%ROWTYPE INDEX BY PLS_INTEGER;
    l_shpt shipment_aat;
    limit_in INTEGER := 100;
    BEGIN
    v_startdate := '10-06-2008 14:00:00';
    v_enddate := '10-06-2008 17:00:00';
    OPEN C_shpt(v_startdate,v_enddate);
    LOOP --start shipment loop   
    FETCH C_shpt BULK COLLECT INTO l_shpt LIMIT limit_in;
         FOR indx IN 1 .. l_shpt.COUNT
    LOOP
    DBMS_OUTPUT.PUT_LINE('l_shpt value ' || l_shpt(indx).ship_number || '/' || l_shpt(indx).insertion_date);
    END LOOP;
    EXIT WHEN l_shpt.COUNT < limit_in;
    END LOOP; -- end of shipment loop
    CLOSE cur1;
    END;

    When your query takes too long ...

  • Managing Multiple threads accessing  a single instance of a class

    Hi,
    i have to redesign a class, say X, in such a way that i manage multiple threads accessing a single instance of the class, we cannot create multiple instances of X. The class looks like this:
    Class X{
    boolean isACalled=false;
    boolean isInitCalled=false;
    boolean isBCalled=false;
    A(){
    isACalled=true;
    Init(){
    if(!isACalled)
    A();
    B();
    C();
    isInitCalled=true;
    B(){
    if(!isACalled)
    A();
    isBCalled=true;
    C(){
    if(!isACalled)
    A();
    if(!isBCalled)
    B();
    }//end of class
    Init is the method that would be invoked on the single instance of this class.
    Now i cannot keep the flags as instance variables coz different threads would have differrent status of these flags at the same time, hence i can make them local, but if i make them local to one method, the others won't be able to check their status, so the only solution i can think of is to place all the flags in a hashtable local to method INIT AND INITIALIZE ALL OF them to false, as init would call other methods, it would pass the hashtable reference as an additional parameter, the methods would set the flags in the hashtable and it would be reflectecd in the original hashtable, and so all the methods can have access to the hashtable of flags and can perform their respective checks and setting of flags.
    This all would be local to one thread, so there's no question of flags of one thread mixin with the flags of some other thread.
    My question is :
    Is this the best way, would this work?
    In java, everything is pass by value, but if i pass the hashtable reference, would the changes made inside the called method to the hashtable key-value would be visible in the original hashtable declared inside the calling method of which the hashtable is local variable?

    In Java object variables are passed "by copy of reference", and primitive variables "by value".
    The solution with HashMap/Hashtable you suggest is ok, but I think you should read about ThreadLocal class:
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html

  • Multiple threads access the same method.

    Hello,
    I have been trying for a long time to find out multiple threads access the shared data.
    I have written a sample code, there I my intention is that method has to be accessed
    onlny one thread at a time., mean one thread finished the job, then next thread can
    access the shared source. But for this code I am not getting the desired out put what I want. But if I am using synchronized block I am getting the output. Please correct where I got mistake. Please see my code.
    public class TestThread implements Runnable {
         Shared r;
         public TestThread() {
              r = new Shared();
         public static void main(String args[]) {
              Thread t1 = new Thread(new TestThread());
              Thread t2 = new Thread(new TestThread());
              t1.setName("A");
              t2.setName("B");
              t1.start();
              t2.start();
          * (non-Javadoc)
          * @see java.lang.Runnable#run()
         @Override
         public void run() {
              // TODO Auto-generated method stub
              r.count();
    class Shared {
         public synchronized void count() {
              String name = Thread.currentThread().getName();
              System.out.println(name + ":accessed...");
              try {
                   for (int i = 0; i < 5; i++) {
                        System.out.println(name + ": " + i);
              } catch (Exception e) {
                   // TODO: handle exception
    }Thanks
    Bhanu lakshmi.

    It depends on what you synchronize. Non-static methods synchronize on the object, so if you're using several objects, you'll be able to call each from their own thread.
    Make your method synchronized or use only a single object and see the difference.

  • WRT160n v3 has slow connection when multiple users are connected

    As of last night my router has been producing slow connectivity when multiple users are connected to it, but it's perfectly fine when only one user is connected.
    I am on a laptop myself, but we also have a second laptop and a desktop where the modem and router are set up.
    I have upgraded the firmware so that is up to date.
    We have Comcast Fiber Optics so my internet speed is normally quite fast even when all of my computers are connected.
    Some settings that I have that might help resolve the issue:
    I am using DHCP Configuration.
    My Channel Width is set to 20 MHz and I am using Channel 11.
    The Security Mode is set to WPA Personal. I had it on WPA2 Personal but I read that changing to WPA Personal might help and so far it doesn't seem to have done anything.
    I set the Beacon Interval to 50, Fragmentation Threshold to 2304, and RTS Threshold to 2304.
    Everything else is set to the default factory configuration.
    Just today I received a notice that said "Windows has detected an IP Address Conflict", but ever since I reinstalled the Firmware it hasn't come back. I've rebooted both my laptop and the desktop to confirm it hasn't come back as well.
    I consider myself to be computer savy, but I just can't figure out what the problem is as I've tried everything that I could think of including reconfiguring my router and restarting my modem as well. This problem has presented itself in the past before but unfortunately I cannot remember what I did to fix it.

    Try using inSSIDer to help you find the best channel.
    http://www.metageek.net/products/inssider/
    If that doesn't help, you can try disabling WMM.
    Edit:  You should use WPA2 AES security for best performance.

  • When should I use static variable and when should not? Java essential

    When should I use static variable and when should not? Java essential

    Static => same value for all instances of the class.
    Non-static => each instance can have its own value.
    Which you need in which circumstances is completely up to you.

  • InDesign CC 2014 very slow performance when dragging images and changing text

    InDesign CC 2014 very slow performance when dragging images and changing text.
    Running on 2010 Macpro 2.4GHz. 8GB RAM. Any solutions? I've read through many forums on this and tried several fixes.

    Have exact same issue on  my Windows 7 machine. Resetting preferences is a workaround.
    So I start InDesign whilst holding down these keys.
    Ctrl + Alt + Shift (Windows) or Cmd + Ctrl + Opt + Shift (Mac)
    Whilst inDesign is usable again with this fix- I have to do it every time so it trashes all my preferences so NOT GOOD long term fix. Otherwise InDesign freezes and can only be stopped by forcing a quit.
    I have manually deleted the preference files and I have created a brand new admin account - but still no luck - will be onto support tomorrow

  • Multiple threads access Object

    Hi. I have no experience with thread. I just decided to learn it with writing some application. I have not started to do programing yet. I just trying to identify some main problems which I think I will encounter when I start programming.
    And this is my problem. I have 1 parent thread, 4 child threads and one Static Object. For threads constantly a access Static object just for reading. I think I can make it not syncronized because child threads only read the object. The perant thread does a different job. I needs to access this object and change the string which the child object will read. Now I see a problem here. If I make it not syncronized the child threads will get bad data. I just can't get how I can make object locked only when parent thread is using it. If parent does not use it the child can freely read data from it. Any ideas.

    Thanks for your advice. Now I have read the java thread tutorial and I have some understanding how threads are workin. However I am still facing one problem.
    imagine this. I have one Thread Produce and 5 Threads Consumers.
    The produce and Consumer access GlobalString object.
    The produce puts the string into object and consumer reads it.
    The problem is that in order for wait() and notify() to work both methods of GlobalString(getString.,setString) must be syncronized. What I want to achieve is that only setString in syncronized and then when it is done
    all 5 Consumer Threads can run getString at same time. If I make this method Syncronizable it will work much slower. I just want to make sure that reading of that string is fast. Can this be done or not?
    this is my code
    public class GlobalString {
    static String stream = "this is the steam";
    public GlobalString() {
    public synchronized String get() {
    try {
    System.out.println("waiting");
    wait();
    System.out.println("Stop waitng");
    catch (InterruptedException ex) {
    System.out.println(ex.toString());
    return stream;
    public synchronized void set(String set) {
    stream = set;
    notifyAll();
    public class Consumer extends Thread{
    private GlobalString gs = null;
    public Consumer(GlobalString gsa) {
    gs = gsa;
    public void run() {
    try {
    System.out.println("thread 2");
    gs.get();
    System.out.println("thread 2 end");
    catch (Exception ex) {
    System.out.println(ex.toString());
    public class GlobalString {
    static String stream = "this is the steam";
    public GlobalString() {
    public synchronized String get() {
    try {
    System.out.println("waiting");
    wait();
    System.out.println("Stop waitng");
    catch (InterruptedException ex) {
    System.out.println(ex.toString());
    return stream;
    public synchronized void set(String set) {
    stream = set;
    notifyAll();
    public class Producer extends Thread{
    private GlobalString gs = null;
    public Producer(GlobalString gsa) {
    gs = gsa;
    public void run() {
    try {
    Thread.sleep(3000);
    gs.set("test");
    System.out.println("output");
    } catch(Exception e) {
    System.out.println(e.toString());
    }

  • What happens when multiple users access the same servlet?

    Do the users share all the same resources? Or is a new process generated for each user? I have a servlet that builds a string to return to the user and I only have myself to test, so I can't really see what happens when many users access the servlet. Is there a possibility that the string will get screwed up, like when dealing with multiple threads, or do all the users get their own resources and I don't have to worry about that?

    huh? if you can point a test servlet at it, you can point a browser at it (even if the servlet does not serve html it will run)
    try pasting the servlet URL into a web browser
    refreshing multiple browsers repeatedly could provide a manual test

  • Problem with multiple threads accessing the same Image

    I'm trying to draw into one Image from multiple threads. It works fine for a while, but then suddenly, the image stops updating. Threads are still running but the image won't update. I'm using doublebuffering and threads are simply drawing counters into Image with different speed.
    It seems like the Image gets deadlocked or something. Anyone have any idea what's behind this behavior or perhaps better solution to do such thing.
    Any help will be appreciated.

    Sorry Kglad, I didn't mean to be rude. With "No coding
    errors" I meant the animation itself runs with no errors. I'm sure
    you could run the 20 instances with no freezing (that's why I put
    the post :) ) But I'm affraid it is an animation for a client, so I
    cannot distribute the code.
    Perhaps I didnt explain the situation clearly enough (in part
    because of my poor english...).-
    - By 20 instances I mean 20 separated embedded objects in the
    html
    - The animation is relatively simple. A turned on candle, in
    each cycle I calculate the next position of the flame (that
    oscilates from left to right). The flame is composed by 4
    concentric gradients. There is NO loops, only an 'onEnterFrame'
    function refreshing the flame each time.
    - It's true that I got plenty variables at the _root level.
    If that could be the problem, how can I workaround it?
    - It is my first time trying to embed so many objects at the
    same time too. No idea if the problem could be the way I embed the
    object from the html :(
    - The only thing I can guess is that when a cycle of one of
    the object is running, the other 19 objects must wait their turn.
    That would explain why the more instances I run, the worst results
    I get. In that case, I wonder if there's a way to run them in a
    kind of asynchronous mode, just guessing...
    Any other comment would be appreciated. Anyway, thanks a lot
    everybody for your colaboration.

  • Why does the Error: 500 SC_INTERNAL_SERVER_ERROR appear when multiple users access my JSPs but does not occur when only one user accesses my JSPs?

    When multiple users run my JSP application, why do some users get an Error: 500 SC_INTERNAL_SERVER_ERROR for certain JSP pages with the error message No such file or directory. The JSP listed on the Error 500 page varies and is not always the same. When only one user runs my JSP application, the problem does not occur?
    The database connection is held when the user logs in or accesses certain parts of the JSP and then is immediately released. No connections to the database are held.
    We are using Solaris 8 with MU_6 plus recommended patches.
    Enterprise Ultra 250
    iAS 6 SP 3

    Is anything showing up in the KXS or KJS logs?
    It sounds like you might having some kind of thread safety issue with your code. Either that or your guess about running out of database connections.

  • Ridiculously Slow Performance when Movie Scoring - brand new macbook

    Hello there guys ! Sorry for my bad english, i will try to do my best.
    The title almost says it all. I have a brand new Intel Core Duo Macbook (White, 2ghz, 512 ram, I haven't added any extra ram or anything).
    The machine is blazing fast, I am really loving the experience. But when it comes to using a feature I would love to use everyday, it disappointed me. The movie score feature in Garage Band 3. So, I create a very simple movie in iMovie HD 6, capturing video from my fireware camera.
    It is a very simple video, no soundtracks, just the original sound that came with the camcorder footage. No stills, reverse, slow-motion, effects or anything. Plain video with sound, just the way it came from the camcorder.
    The problem is when creating a movie scoring project with that footage in garageband 3 , the performance is RIDICULOUSLY SLOW. I mean, I press space and the movie strats playing after 1,5 seconds, and the video is halting every other second. It is so laggy that when i press space again to stop the video, the motion continues for another 1,5 seconds until it pauses.
    There's absolutely no way to do any work in conditions like that. And the strange thing is that when using garage band to do other stuff, or when working in iMovie with that same movie there's no lag at all. I have even edited 30 minute long videos with effects and soundtracks in iMovie and it was blazing fast, no lag, no halting.
    But in Garagaband even the simplest of all videos gets this ultra-slow performance, and it makes me wonder why.
    - I have tried desabling recording on the audio track in garageband. I have tried to lock the track. I have done all the steps in the optimizing garage band performance in the help. I don't have firevault activated.
    Any help ? Does anyone have a macbook just like mine that is able of doing moving scoring ? Because EVERYTHING ELSE is ultra fast, including video and audio editing, but when movie scoring it *****.
    Apple Macbook 13inch 2.0ghz Core Duo 512 60GB White SuperDrive   Mac OS X (10.4.7)  

    Ha! It's funny really - you say it all yourself; no extra ram, it doesn't come with enough to run Pro Apps and when you start to use the Scoring feature you are accessing two different functions - playing movies and music tracks - movies are always a stress unless they are very small and the Right Codec - so first up - what format is your movie? Do you have Quicktime Pro? if the answer is No - get it, it's not expensive and it gives your machine many extra abilities - you can then convert your footage to something easy to play.
    How many tracks are you working with?
    Get more RAM - MacIntel or MacPro needs 4-6 gigs to multi-task happily - with only the base load of RAM it can't.
    I have a DP 2 Ghz G5, no where near as fast as yours but I have 4.5 GBs of RAM and a fast graphics card with 512Mbs VRAM - this means Motion and FCP can fly.
    We are about to get a MacPro 2.66 Dual with 6 GBs RAM, essential.
    Hope this helps.

  • Accessing static variables

    class Array{
    static int m = 10; // how to access this variable in main()?
    public static void main(String [] args) {
    int m = 45;
    System.out.print(m );
    return ;
    }

    One problem is you are doing stuff in main that should not be done in main.
    Main is always only for kicking a program off and ensuring it cleans up nice when done, that is it. Sooner you figure this out and get into good habits the better.
    Second, you have two m variables, which one do expect to get accessed? But still, getting out of main before doing your computations will make your problem much easier to see and fix, so do that first.
    JSG

  • PrinterException when multiple threads try to print report using JRC

    Iam using Crystal Report's JRC for printing reports, it works fine.
    But the problem araises when i use multiple threads.
    I used the following:
    reportClientDocument.getPrinterOutputController().printReport(.....); to print.
    I get the following exception
    Caused by: java.awt.print.PrinterException: No printer named "\\ch03\printer05" could be found.
    Without multiple thread it works fine.
    I have been scratching my head for days on this problem, any help is very much appreciated..

    If an API doesn't specifically say that it is thread safe then it isn't likely to be thread safe and the only way to approach it is to assume that it isn't.

  • Berkeley DB Java Edition - multiple threads accessing database

    Hi,
    I would like to access (read & write) a Berkeley DB from multiple threads (all same process/jvm).
    Should I use a single com.sleepycat.je.Database object for all threads, or should I create an instance for each?
    Or is there any other way of doing it?
    Thanks

    The Database object may be used by multiple threads, so you can use a single instance or multiple ones, as best suits you. From http://docs.oracle.com/cd/E17277_02/html/java/com/sleepycat/je/Database.html,
    Database handles are free-threaded and may be used concurrently by multiple threads. 'If you read through the javadoc, you'll find other notes on using classes from multiple threads.
    Regards,
    Linda

Maybe you are looking for