Are i++, i-- atomic and thread safe for int i

I want to minimize the sync time multiple threads take to contend for a shared pool, which is implemented as a FIFO. My plan is to:
1. Use a int variable "count" to trace the free obj count. Hence eliminates the need of synchonized methods size() and isEmpty()
2. Increment & decrement count when implemeting push() and pop()
3. Minimize the number of statements in synchonized block as possible within push() and pop(), which in this case, excludes count++ and count-- provided these operations are atomic and thread safe
Have I lost something ?

So, may I make a conclusion.
To minimize contention, I use FIFO instead LIFO or stack and build it from scratch without extending from existing Collection-related class
1 public class FIFO {
2 . . private volatile int count;
3 . . private Object head, tail;
4 . . public Object pop() {
5 . . . .synchonized (tail) {
6 . . . . .if (count >= 3) {
7 . . . . . .Object tail_origin = tail;
8 . . . . . .// Re-organizing the linked list skipped
9 . . . . . .synchonized (this) {
10 . . . . . . count--;
11 . . . . . }
12 . . . . . return tail_origin;
13 . . . . }
14 . . . . else {
15 . . . . . throw new PoolEmptyException();
16 . . . . }
17 . . . }
18 . . }
19 . . public void push(Object o) {
20 . . . synchronized (head) {
21 . . . . . // Re-organizing the linked list skipped
22 . . . . . head = o;
23 . . . . . synchonized (this) {
24 . . . . . . count++;
25 . . . . . }
26 . . . }
27 . . }
28 . . public int sizeOf() {
29 . . . return count;
30 . . }
31 }
1. The reason I choose FIFO is to avoid the contention between push() and pop() -- they are NOT declared as synchonized, instead they only lock head and tail respectively. (Sorry I borrow the name push and pop from stack)
2. pop() only works when count >= 3 to avoid head == tail after pop() and hence a further call to push() block concurrent call to pop() and vice versa (see line 5 and 20)
3. The goal is to minimize the time and scope of contention. In line 9 and 23, I lock the whole pool object only when modify count, which is not atomic.
4. This pool is used for a thread pool supporting many concurrent short-lived HTTP request
Have I missed something ?
Thanks a lot!

Similar Messages

  • Question about EJB and thread safe coding - asking again!

    sorry everyone, no one seems to be interested in helping me on this, so i post it again.
    i have a question about the EJB and thread safe coding. when we build EJBs, do we need to worry about thread safe issue? i know that EJBs are single threaded, and the container manages the thread for us. maybe i am wrong about this. if i wasnot, how can we program the EJB so that two or more instance of EJB are not going to have deadlock problem when accessing data resources. do we need to put syncronization in ours beans, do we even need to worry about creating a thread safe EJB? thanks in advance. the question really bothers me a lot lately.

    sorry everyone, no one seems to be interested in
    helping me on this, so i post it again.Excellent plan. Why not search a little bit on your own instead of waiting for your personal forum slaves to answer your call. See below.
    i have a question about the EJB and thread safe
    coding. when we build EJBs, do we need to worry about
    thread safe issue? Read this: http://forum.java.sun.com/thread.jsp?forum=13&thread=562598&tstart=75&trange=15
    i know that EJBs are single
    threaded, and the container manages the thread for us.
    maybe i am wrong about this. if i wasnot, how can we
    program the EJB so that two or more instance of EJB
    are not going to have deadlock problem when accessing
    data resources. do we need to put syncronization in
    ours beans, do we even need to worry about creating a
    thread safe EJB? thanks in advance. the question
    really bothers me a lot lately.
    Java's Thread Tutorial
    JavaWorld: Introduction to Java threads
    IBM: Introduction to Java threads
    Google: java+threads+tutorial

  • Are static methods in Java thread safe?

    Are static methods in Java thread safe?
    thanks,
    suresh

    if static method use the instance variable
    You mean member variable, where member variables are either class variables (static) or instance variables (non-static).
    then you have to make it thread safe using
    synchronization Not necessarily. Depends on requirements and usage context.
    else in case of local var. it
    is thread safe. Not necessarily. That local variable could refer to an object that's visible to multiple threads.
    Statements like "Local variables are threadsafe but member variables aren't" are an oversimplification.
    Something is threadsafe if it cannot be made to behave incorrectly simply by running it in a multithreaded context. Determining that can be very difficult.

  • What are the delta mechanisms and tables used for  Lo Extraction & COPA

    Hi all
    what are the delta mechanisms and tables used for  Lo Extraction & COPA.
    please explain clealry.
    Thanks & Regards,
    James

    James,
    Please go through Roberto's weblog :
    /people/sap.user72/blog/2005/02/14/logistic-cockpit--when-you-need-more--first-option-enhance-it
    Anyways,
    As you know LO cockpit consists of different modules(MM, PP, SD, etc)
    They are called appl components. Each of them have a number (eg.MM=02) and for each appl comp they might be different Data sources and for each DS they might be different tables. So, unless you be specific we cant tell a specific table for a DS.
    coming to the delta mechanisms, there are " direct delta, queqed delta and serialized delta".
    Copa is based on the oepration concern. it can be created on " accouting based" or "costing based".
    Assign points if helpful
    Kalyan

  • What are the BEST Books and Best websites for java biginners?

    Dear All,
    What are the BEST Books and Best websites for java biginners-Especially for fast learning.
    Thnaks
    KMK

    This is my standard reply:
    [Sun's basic Java tutorial|http://java.sun.com/docs/books/tutorial/]
    [Sun's New To Java Center|http://java.sun.com/learning/new2java/index.html]
    Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    jGuru
    A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch
    To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    [Yawmarks List|http://forums.devshed.com/java-help-9/resources-for-learning-java-249225.html]
    [The Java Developers Almanac|http://www.amazon.com/exec/obidos/tg/detail/-/0201752808?v=glance]
    [http://javaalmanac.com|http://javaalmanac.com]
    Bruce Eckel's [Thinking in Java(Available online.)|http://mindview.net/Books/DownloadSites]
    Joshua Bloch's [Effective Java|http://www.amazon.co.uk/exec/obidos/Author=Bloch,%20Josh]
    Bert Bates and Kathy Sierra's [Head First Java|http://www.amazon.com/exec/obidos/tg/detail/-/0596004656?v=glance ]
    James Gosling's [The Java Programming Language|http://www.bookpool.com/sm/0321349806]
    Gosling is the creator of Java. It doesn't get much more authoritative than this.
    Joshua Bloch and Neal Gafter [Java Puzzlers.|http://www.javapuzzlers.com/]

  • What are the supported Platforms and system requirements for JSE?

    What are the supported Platforms and system requirements for JSE?

    Hi There,
    The following are the system requirements & the support platforms for JSE :-
    * Solaris 9 and 8 Operating Systems (SPARC Platform Edition)
    o UltraSPARC II 450-MHz system with 512 MB of memory and 850 MB of disk space
    o Recommended: UltraSPARC III 750-MHz system with 1 GB of memory and 1 GB of disk space, or higher.
    * Solaris 9 Operating System (x86 Platform Edition)
    o Pentium III 500-MHz system with 512 MB of memory and 850 MB of disk space
    o Recommended: Pentium III 1-GHz system with 1 GB of memory and 1 GB of disk space, or higher
    * Windows 2000 and Windows XP
    o Pentium III 500-MHz system with 512 MB of memory and 850 MB of disk space
    o Recommended: Pentium III 1-GHz system with 1 GB of memory and 1 GB of disk space, or higher

  • With Premiere elements 11, when Publish/Share (saving) a finished video, selecting H.264  .mov file type, what are the recommended Codec and Aspect settings for a crisp video and a small file size?

    With Premiere Elements 11, when Publish/Share (saving) a finished video, selecting H.264  .mov file type, what are the recommended Aspect and Codec settings , for a crisp video with a small file size?

    Gary Krouse
    We will customize a very detailed reply, but
    (a) What are the properties of your source media?
    (b) What did you or the program set as the project preset to match the properties of the source media?
    (c) What specific requirements do you have for this H.264.mov export file?
    File size can be a compromise between bitrate, file size, and quality.
    Thanks.
    ATR

  • Portege R835-P56X : are there no Wifi and soundcard drivers for WIn XP ?

    I have just got a Portege R835-P56X . Are there any Wifi and Soundcard drivers for Windows XP for this laptop ?  I want to downgrade to win XP as I have a huge collection of legacy software which have compatibility issues with WIndows 7. I can't find the required drivers on the Toshiba website, all though there are drivers for webcam or touchpad. I don't understand the reason for having a few drivers for XP but not all the required ones. Surely one can't use a laptop without Wifi or  audio.  

    Portege R835-P56X
    Best to upgrade Home Premium to Professional and then install XP Mode. Works really well here.
       Upgrade to another edition of Windows 7 by using Windows Anytime Upgrade
       Install and use Windows XP Mode in Windows 7
    It's not necessary to have hardware vitualization enabled. See KB977206.
    -Jerry

  • Discussion: AtomicBuffer - lock-free and thread-safe

    Hi,
    Since I'm always interested in discussions, I posted the following code for a lock-free, thread-safe buffer implementation.
    In this case the buffer stores (Message,Throwable, Level) triplets but that's not the point here.
    The interesting parts are addEntry() and getNextSlot(). It's actually the first time, that I tried to make use of the atomic package in a real application.
    I'm looking forward to any kind of valuable comment, may it be criticism or praise :)
    Cheers, Daniel
    * Array-based buffer for storing message-throwable-level triples.
    * Uses CAS for lock-free, thread-safe access.
    * @author dgloeckner
    public class AtomicBuffer {
         private final int mSize;
         private Object[] mMessageBuffer;
         private Throwable[] mThrowableBuffer;
         private Level[] mLevels;
         private AtomicInteger mNextSlot;
         private AtomicInteger mDiscardedMessages;
         public AtomicBuffer(int pSize) {
              super();
              mSize = pSize;
              mMessageBuffer = new Object[pSize];
              mThrowableBuffer = new Throwable[pSize];
              mLevels = new Level[pSize];
              mNextSlot = new AtomicInteger(0);
              mDiscardedMessages = new AtomicInteger(0);
          * Uses CAS for lock-free, thread-safe buffer access.
          * @param pMessage log message
          * @param pThrowable throwable for the message (may be null)
          * @param pLevel log level
         public void addEntry(Object pMessage, Throwable pThrowable, Level pLevel) {
              int lSlot = getNextSlot();
              if (lSlot < mSize) {
                   mMessageBuffer[lSlot] = pMessage;
                   mLevels[lSlot] = pLevel;
                   mThrowableBuffer[lSlot] = pThrowable;
              } else {
                   //Buffer is full
                   mDiscardedMessages.incrementAndGet();
          * Returns the next free slot.
          * Only increments the next slot counter,
          * if free space is left.
          * @return next free slot
         protected int getNextSlot() {
              int lNextSlot = 0;
              //CAS loop checks if the value read from mNextSlot
              //is smaller than the buffer size.
              //If not, the loop returns.
              //If yes, the loop tries to increment mNextSlot using CAS.
              do {
                   lNextSlot = mNextSlot.get();
                   if (lNextSlot >= mSize) {
                        break;
              } while (!mNextSlot.compareAndSet(lNextSlot, lNextSlot + 1));
              return lNextSlot;
         public int getSize() {
              return mSize;
         public int getDiscardedMessages() {
              return mDiscardedMessages.get();
         public Level[] getLevels() {
              return mLevels;
         public Object[] getMessages() {
              return mMessageBuffer;
         public Throwable[] getThrowables() {
              return mThrowableBuffer;
          * Returns the number of filled slots.
          * @return number of filled slots
         public int getFilledSlots() {
              return mNextSlot.get();
    }

    Hi,
    OK, so we were talking about different specifications.
    If you are sure about that before the time you mentioned only writes, and after that time only read(s) will take place, it's an absolutely good situation.
    Sorry, I was very wrong, you're right - some (or most) implementations use hardware CAS. Hey that's a nice feature, isn't it?
    I can see that you are using the loop to determine, whether another thread has accessed the counter (or something similar). I think this technique is great,
    however, you might end up with a thread waiting for a single buffer space, while the others proceed (although this is not likely).
    Anyway, I don't really know why would I want to use a code this complicated.
    What about these lines:
    public void addEntry(Object pMessage, Throwable pThrowable, Level pLevel) {
    int lSlot = mNextSlot.incrementAndGet();
    //So this has incremented the value (now remember to instantiate with -1) atomically, fast, with no locking and no loops
    //Here I don't really worry about the real value of this int, as I only want to know if my entry fits to the buffer
    if (lSlot < mSize) {
    mMessageBuffer[lSlot] = pMessage;
    mLevels[lSlot] = pLevel;
    mThrowableBuffer[lSlot] = pThrowable;
    public int getDiscardedMessages(){
    return mNextSlot.get()-mSize; //but here I can reuse the information (i.e. the difference), which you would have discarded
    }To use this code for general purposes, one could modify it like this:
    <code>...
    //in the constructor:
    fillableSize = pSize;
    mSize = pSize + OVERFLOW; //where OVERFLOW is a number that satisfies the conditions in a given environment
    </code>...
    public boolean isFull(){
    return mNextSlot.get() > fillableSize;
    //I am sure that there is a thread periodically checking / storing the log itself, of which core should be something like this:
    if (currentAtomicBuffer.isFull()){ //or a given time period is exceeded
    AtomicBuffer newAtomicBuffer = new AtomicBuffer(BUFFER_SIZE);
    logThisToDatabase(lastAtomicBuffer); // log the previous one - there should not be any writer threads
    lastAtomicBuffer = currentAtomicBuffer; // this is the preivous one - note that there might be some threads writing to it, but this does not mean any problem
    currentAtomicBuffer = newAtomicBuffer; // from now on, work to the new buffer
    //for monitoring purposes, you still can use getDiscardedMessages: this will inform you if OVERFLOW is set right. Anyway, it should always return 0.However, one might want to catch the interruptedException (thrown in the thread that empties the buffer) and handle it with a last logThisToDatabase call on lastAtomicBuffer and currentAtomicBuffer as well.
    Kind Regards,
    Zoltan

  • What are the username, password and connect string for Designer 6.1.1?

    So that we may better diagnose DOWNLOAD problems, please provide the following information.
    - Server name
    - Filename
    Oracle designer6.1.1
    - Date/Time
    - Browser + Version
    IE 6.0
    - O/S + Version
    Win 98
    - Error Msg
    ORA-12154:TNS:could not resolve service name.
    RME-00220:Fail to connect to repository
    These error messages were shown after I entered system, manager and internal, respectively.

    Hi YungJen Chen,
    There is no general username, password and connect string for
    Designer 6i Release 4.1.1.
    First, you install the client tools using the Installer. See also the
    Designer Installation Guide, Chapter 1, 'Client Side installation'.
    Second, you install the repository into an existing database, using
    the Designer Installation Guide, Chapter 2, 'Server-side installation,
    migration and upgrade'.
    The Installation Guide provides step by step instructions on what
    users you need to create for various purposes. Any database users
    you may need to use such as System or Sys will use the password
    given when you installed the database, or whatever passowrd you
    changed it to since.
    The Installation Guide is available as part of the download, or from
    your Windows Start Menu once the Designer client tools are installed
    or from the Designer Documentation page here on OTN.
    Hope this helps. Regards,
    Dominic Battiston
    Designer/JDeveloper Product Management

  • What are the username, password, and connect string for Designer6i R4.1.1

    As the title, I tried system, manager and internal.
    But it did not work out.
    Thank you for your help.

    Hi YungJen Chen,
    There is no general username, password and connect string for
    Designer 6i Release 4.1.1.
    First, you install the client tools using the Installer. See also the
    Designer Installation Guide, Chapter 1, 'Client Side installation'.
    Second, you install the repository into an existing database, using
    the Designer Installation Guide, Chapter 2, 'Server-side installation,
    migration and upgrade'.
    The Installation Guide provides step by step instructions on what
    users you need to create for various purposes. Any database users
    you may need to use such as System or Sys will use the password
    given when you installed the database, or whatever passowrd you
    changed it to since.
    The Installation Guide is available as part of the download, or from
    your Windows Start Menu once the Designer client tools are installed
    or from the Designer Documentation page here on OTN.
    Hope this helps. Regards,
    Dominic Battiston
    Designer/JDeveloper Product Management

  • What are the disc space and memory requirements for the apps?

    What are the disc-space and memory requirements to run the apps

    Hello John!
    thank you for the info. However, as I have only 1Gb memory and a 32Gb
    solid-state disc, I think that I will stay with Acrobate.com for a while
    longer.
    Regards
    Brianb

  • HT5117 What are the new dpi and pixel rules for ibook cover art?

    Plz tell me the new pixel and dpi requirements for ibooks. Thx

    K T wrote:
    Image dpi has a direct effect on image quality.
    An image has no dpi, only pixels. What has dpi is the display that shows the image.
    The pixel dimensions are an attribute of the image and determine how much information is in the image. The dpi is an attribute of the display and determines how many pixels are displayed in a given area.
    The two values are independent and have nothing to do with each other.
    If a program such as Photoshop or InDesign allows you to specify a dpi setting, it is so it can export an image with pixel dimensions that match the dpi of the target display, so the image appears at a pre-determined physical size. The programs also use the dpi setting so, when you ask to be shown the image at original size, the software can scale the image so it appears at that size even on a display whose dpi does not match the dpi of the target display.
    When you upload a cover image, there is no dpi. There is one and only one thing: the pixel dimensions of the image.
    Michi.

  • What are the userid,password, and host name for oracle 9i?

    HI Guys.
    I am a research student at the University and the I recently downloaded Oracle 9i for my research. But the problems is also with seting it up. Please could you show me the userid, password, and host name for oracle 9i.
    Thanks in advance for your cooperations.
    Malinga R
    [email protected]

    I believe that starting with 9.2, you have to specify different passwords when you install (can't be the default).
    Justin

  • What are the minimum CPU and Memory requirements for R12 Vision instance?

    We are in the process of trying to figure out what the minimum hardware requirements are for installing the R12 Vision instance. This Vision instance would only have 5 or less concurrent users. We may have to order a new server and we are wondering what the minimum CPU and memory would be? Oracle Support will not give us this information.
    We aleady know how much disk space it will need.
    Dan

    Hi,
    See these links.
    A Primer on Hardware Sizing for Oracle E-Business Suite
    http://blogs.oracle.com/stevenChan/2010/08/ebs_sizing_primer.html
    What Are the Minimum Desktop Requirements for EBS?
    http://blogs.oracle.com/stevenChan/2010/09/ebs_pc_clients.html
    Also, please see old threads for similar discussion.
    Hardware Requirements
    http://forums.oracle.com/forums/search.jspa?threadID=&q=Hardware+Requirements&objID=c3&dateRange=all&userID=&numResults=15&rankBy=10001
    Benchmark
    http://forums.oracle.com/forums/search.jspa?threadID=&q=Benchmark&objID=c3&dateRange=all&userID=&numResults=15&rankBy=10001
    Thanks,
    Hussein

Maybe you are looking for