Are CacheStore's and BackingMapListener's thread safe?

I'm implementing a JMS CacheStore and have a quick question: does Coherence ever attempt to run multiple threads concurrently across a CacheStore instance on a given node?
Reason I ask is that only certain objects are thread-safe in the JMS spec.: Connection Factories, Destinations (i.e. a Queue) and Connections. However Sessions, Producers and Consumers are not.
In order to improve performance, it's recommended (obviously) to try and reuse Sessions/Producers and not recreate them for every message sent. So I'd like to declare them as instance variables in my class and assign them once-only at construction time.
I just wanted to make sure that this would be OK (i.e. Coherence would start multiple threads running across my CacheStore). Anyone any ideas?
(NB. I'm using JMS Connection Pooling to get around this issue at the moment - as the pools are thread-safe and I can close/open them quickly as many times as I like - but this is not a part of the JMS standard, so I end up using vendor-specific classes which I'd rather not do. Likewise I could make many of these non-thread-safe objects use ThreadLocals, but this all seems a bit overkill if it isn't actually required...)
An other issue... :)
What about closing the connection when it's finished with? Again, it's JMS recommended best-practice to do so. How is this best accomplished, seem as though it was Coherence that created the CacheStore instance and my client code has no reference to it? Best I can think of for now is have a static method in my CacheStore class that is kicked off via an invocation-service agent. Again, if anyone has a better idea I'm all ears.
An other issue... :)
Does the same thread-safety hit BackMapListeners? The "receiving" end of my JMS messages is a BackingMapListener based on the Incubator Commons "AbstractMultiplexingBackingMapListener" class. So, does Coherence ever kick off multiple threads across a single BackingMapListener instance, or can I safely have the JMS Session and Consumer left open after construction as class-level members?
Cheers,
Steve

stevephe wrote:
True... But I was rather hoping I could just get someone from Oracle who wrote the stuff to comment instead! :) Don't really want to second-guess this, as there could always be unusual corner-cases that could be difficult to replicate. Still...
I did a bit more testing on my CacheStore this morning. I removed the non JMS-standard "pooling" and just created instance variables for only those items which I know to be thread-safe (ConnectionFactory, Connection and my target queue, a "Destination" in JMS terminology) I now re-get the Session and Producer in each Cachestore method. This makes the code thread-safe and portable. TBH, it hasn't affected performance too much, so I'll leave it as it is for now (and I've put a comment in the code stating that people could move these things to ThreadLocal's if they wanted to further boost performance in their own usage cases and still keep the CacheStore thread-safe.)
As regards the "receiving" end of these published messages, my BackingMapListener does nothing more than register a JMS MessageListener and a "connection.start()" call. This is a very short, one-off call, so shouldn't leave Coherence service threads "hanging" on anything for extended periods.
Cheers,
SteveHi Steve,
to cut things short:
1. Coherence instantiates one cache store per read-write-backing-map, therefore it needs to be thread-safe if you have a thread-pool or use write-behind.
2. If you don't have write-behind then Coherence uses the worker thread to execute the cache store operations.
3. If you have write-behind then generally Coherence uses the write-behind thread (this is a separate thread per write-behind-configured service) to execute the cache store operations, except for erase[All]() operations on cache.remove() or batch remove which cannot be delayed due to consistency reasons and are executed on the worker thread.
If you don't have a thread-pool, replace worker thread with service thread.
I don't know off my head where the refresh-ahead operation executes.
There is a single backing-map-listener per backing map instantiated, therefore it needs to be thread-safe. BackingMapManagerContext is thread-safe, so there is no issue with sharing it across multiple threads executing on a backing-map-listener.
Best regards,
Robert

Similar Messages

  • Are the service(), doPost() and doGet() methods THREAD-SAFE?

    Please Let Me know If service(), doPost() and doGet() are Thread-safe. If they are not thread safe, How to make them thread-safe?

    Please Let Me know If service(), doPost() and doGet() are Thread-safe. They are not.
    If they are not thread safe, How to make them thread-safe?The best way is to avoid writing code that depends on a servlet's thread safety; i.e., no servlet instance variables - keep everything local to the method. Else, you'll want to learn about synchronization.
    [JavaWorld article - Write thread-safe servlets|http://www.javaworld.com/javaworld/jw-07-2004/jw-0712-threadsafe.html].
    ~

  • Are methods in the Graphics class Thread Safe

    Can methods from the Graphics class (.e.g. drawImage(), drawString(), ect..) be called from any thread? In other words, can two threads that refer to the same Graphics object step on each other methods calls?
    TIA,
    DB
    Edited by: Darth_Bane on Apr 27, 2009 1:44 PM

    No,
    They are GUI activities so you should call them from the Swing Thread ( Event Disptach Thread)
    Now for the JComponent the following are thread safe:
    repaint(), revalidate, invalidate which can be called from any thread.
    Also the listener list can be modified from any thread addListenerXX or removeListenerXX where XX is ListenerType
    Regards,
    Alan Mehio
    London, UK

  • Are static objects thread safe?

    hi,
    i have seen code that looks like this:
    private static TestObject _to;
    static {
    _to = new TestObject();
    if methods within TestObject contain local variables, will local variables inside _to be threadsafe when hit by 2 requests?
    eg.
    User 1 makes a request to:
    _to.setStuff("abc");
    User 2 make a request to:
    _to.setStuff("def");
    Will User 1's now see "def" instead of "abc"?
    thanks
    - Edward Han
    [email protected]

    so what happens to the local variable holder? if 2
    people access the static variable _to and call
    setStuff() one right after the other, is there a
    chance that the first person in will print out what
    the second person in set as the holder?
    Local variables are thread specific and live on an execution stack, and each thread gets its own stack. If there are two threads, there are two stacks, and if both threads are "in" setstuff(), there are two distinct references called "holder" -- one per stack. And regardless of the order in which the threads enter that method, the references themselves are not clobbered. Now, what you see printed is an entirely different issue, as is the case if the "holder" references point to the same (shared) object.
    The key is this: a thread-specific resource is thread safe; a shared (unprotected and/or mutable) resource is not.

  • SSRS - Is there a multi thread safe way of displaying information from a DataSet in a Report Header?

     In order to dynamically display data in the Report Header based in the current record of the Dataset, we started using Shared Variables, we initially used ReportItems!SomeTextbox.Value, but we noticed that when SomeTextbox was not rendered in the body
    (usually because a comment section grow to occupy most of the page if not more than one page), then the ReportItem printed a blank/null value.
    So, a method was defined in the Code section of the report that would set the value to the shared variable:
    public shared Params as String
    public shared Function SetValues(Param as String ) as String
    Params = Param
    Return Params 
    End Function
    Which would be called in the detail section of the tablix, then in the header a textbox would hold the following expression:
    =Code.Params
    This worked beautifully since, it now didn't mattered that the body section didn't had the SetValues call, the variable persited and the Header displayed the correct value. Our problem now is that when the report is being called in different threads with
    different data, the variable being shared/static gets modified by all the reports being run at the same time. 
    So far I've tried several things:
    - The variables need to be shared, otherwise the value set in the Body can't be seen by the header.
    - Using Hashtables behaves exactly like the ReportItem option.
    - Using a C# DLL with non static variables to take care of this, didn't work because apparently when the DLL is being called by the Body generates a different instance of the DLL than when it's called from the header.
    So is there a way to deal with this issue in a multi thread safe way?
    Thanks in advance!
     

    Hi Angel,
    Per my understanding that you want to dynamic display the group data in the report header, you have set page break based on the group, so when click to the next page, the report hearder will change according to the value in the group, when you are using
    the shared variables you got the multiple thread safe problem, right?
    I have tested on my local environment and can reproduce the issue, according to the multiple safe problem the better way is to use the harshtable behaves in the custom code,  you have mentioned that you have tryied touse the harshtable but finally got
    the same result as using the ReportItem!TextBox.Value, the problem can be cuased by the logic of the code that not works fine.
    Please reference to the custom code below which works fine and can get all the expect value display on every page:
    Shared ht As System.Collections.Hashtable = New System.Collections.Hashtable
    Public Function SetGroupHeader( ByVal group As Object _
    ,ByRef groupName As String _
    ,ByRef userID As String) As String
    Dim key As String = groupName & userID
    If Not group Is Nothing Then
    Dim g As String = CType(group, String)
    If Not (ht.ContainsKey(key)) Then
    ' must be the first pass so set the current group to group
    ht.Add(key, g)
    Else
    If Not (ht(key).Equals(g)) Then
    ht(key) = g
    End If
    End If
    End If
    Return ht(key)
    End Function
    Using this exprssion in the textbox of the reportheader:
    =Code.SetGroupHeader(ReportItems!Language.Value,"GroupName", User!UserID)
    Links belowe about the hashtable and the mutiple threads safe problem for your reference:
    http://stackoverflow.com/questions/2067537/ssrs-code-shared-variables-and-simultaneous-report-execution
    http://sqlserverbiblog.wordpress.com/2011/10/10/using-custom-code-functions-in-reporting-services-reports/
    If you still have any problem, please feel free to ask.
    Regards
    Vicky Liu

  • Web service client proxy thread safe?

    Is the jax-ws web service client proxy and port objects thread safe in Weblogic 10.3.4?
    Been searching through the docs but can't find any info on this.

    I have searched and it seems that with cxf it's safe to do something like this.
    Nobody knows if this is safe using metro?

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

  • Thread safe logging class, using final and static

    Hi,
    I'm looking through a logging class (which writes entries to a text file and so on) written by someone else, and I'm trying to determine whether it's thread-safe...
    Essentially the class looks like this:
    public final class Logger {
    private static FileOutputStream fout;
    private static PrinterWriter pout;
    private static final long MaxLength = 100000;
    static {
    /* basically checks size of logfile, if bigger than 100k, then copy it as bak, and start again */
    public void write(String msg) {
    /* write entry into log file */
    public void writeWithTimeStamp(string msg) {
    /* write entry with time stamp into log file */
    Now, I could be wrong, but I don't think that the class is thread-safe is it? in order to be thread-safe, I would have to use synchronized before write() and writeWithTimeStamp(), right?
    My confusion arises from the use of the keyword "final" at the top of the class. This class isn't being inherited (or rather, there's no reason for the class not to be inheritable)... so what is it's purpose, if there is one?!
    And my other question concerns the static block. But I need to describe the current setup first: The Logger class is being use by a file server. File server basically sits there, accepts socket connections from the outside, and takes text files and output them into a local directory. When a new socket connection is created, a new thread is created. As it stands right now, each thread instantiates its own Logger object which seems weird! Bringing me to my question which was, if each thread instantiates its own Logger object, the static block is only ran ONCE, regardless of how many threads (and therefore Logger objects) are created, right??
    And wouldn't it be a better idea to simply create only ONE Logger object and pass it by reference to all newly created threads as they are needed so that all threads access the same and only Logger object? (and therefore utilize sychronization)
    Thanks!

    In JDK 1.4, there are already classes written that do all of that work. Check out the docs for the java.util.logging package. Specifically, check out FileHandler (which can rotate log files if they are greater than a specified size) and LogRecord (which is a standardized way to store logging entries). I believe the class is threadsafe, it doesn't say it isn't. Try it and see. If not, you can easily make a threadsafe wrapper for it (or any class for that matter).
    The online documentation is at:
    http://java.sun.com/j2se/1.4/docs/api/index.html
    If you are curious, the simplest way to make any class threadsafe, if you don't want to or are not able to modify the class code itself is to define another class that calls methods of the original class, but that is synchronized.
    Example:
        // NonThreadSafe.java
        public class NonThreadSafe {
            public NonThreadSafe (String s) {
                // Constructor
            public void SomeMethod (int param) {
                // Do some important stuff here...
            public int AnotherMethod (boolean param) {
                // Do some more important stuff here...
        // ThreadSafeWrapper.java
        public class ThreadSafeWrapper {
            protected NonThreadSafe nts;
            public ThreadSafeWrapper (String s) {
                nts = new NonThreadSafe(s);
            public synchronized void SomeMethod (int param) {
                nts.SomeMethod(param);
            public synchronized int AnotherMethod (boolean param) {
                return nts.AnotherMethod(param);
            public NonThreadSafe GetNonThreadSafe () {
                return nts;
        };Unfortunately, ThreadSafeWrapper isn't derived from NonThreadSafe, so you are somewhat limited in what you can do with it compared to what you could do with NonThreadSafe. AFAIK, you can't override unsynchronized methods with synchronized ones.
    Another thing you could do is just write a method that writes to your logging class, and synchronize just that method. For example:
        // ThreadSafeLogger.java
        public class ThreadSafeLogger {
            public static synchronized void LogMessage (MyLogger log, String msg) {
                log.writeString(msg);
        // In another thread, far, far away:
            ThreadSafeLogger.LogMessage(theLog, "Blah");
            ...Hope that helps.
    Jason Cipriani
    [email protected]
    [email protected]

  • BC4J View not Thread safe, user sessions are using the same view instance

    Hi There,
    We are using BC4J that came with JDeveloper 10.1.2.0.0 with Oracle 10G 10.1.2.0.0.
    I have an BC4J account search view (BC4J AccountSearchView) that users can call to search for an account. So this view could be used by numerous users and pieces of code at the same time. Now my understanding is that each user gets their own instance of the view so changing the view's query should not be an issue (since the view definition is not changing). Under a light load the account search view looks like everyone get there own instance of the view and there expected account search results. But under a heavy user load when we have User A and User B the search query that was for User A will be used by User B. So the user results for one user will get the other users results.
    I do not understand if the view definition is been changed by the other user and is impacting all view instances. How can this occur if it is thread safe?
    I have enclosed the core code for this search.
    If you can help that would be much appreciated, thanks in advance,
    Nigel
    accountSearchView.setQuery(baseSelectQuery+generateWhereClause());
    logger.debug("SearchAccounts Query: "+accountSearchView.getQuery());
    System.out.println("SearchAccounts SQL: "+accountSearchView.getQuery());
    accountSearchView.setPassivationEnabled(false);
    accountSearchView.setForwardOnly(true);
    accountSearchView.executeQuery();
    get attributes for each row result and place in new Java bean objects and return to user.

    Nigel, we've only certified JDeveloper 10.1.2 against the Struts 1.1 with which it ships.
    If there have been any changes in Struts 1.2 to the Struts Request Processor, then this could easily have an impact on the BC4JRequestProcessor's correct functioning, depending on what the changes were.
    My quick look into the issue tells me that the ActionServlet init parameter named mapping in web.xml that we use for the 9.0.3-style BC4J/Struts integration is getting ignored by Struts 1.2. This parameter is used by Struts 1.1 to globally configure a custom ActionMapping subclass which can support additional properties. My quick test shows me that Struts 1.2 is ignoring this setting and so the oracle.jbo.html.struts11.BC4JActionMapping subclass of Struts's default ActionMapping is not getting used correctly as it does in Struts 1.1. This leads to errors when Struts tries to configure its actions in struts-config.xml since the Apache digester tries to set properties on the ActionMapping instance that don't exist (since the BC4JActionMapping has these properties, and it's not being used).
      <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
        <init-param>
          <param-name>mapping</param-name>
          <param-value>oracle.jbo.html.struts11.BC4JActionMapping</param-value>
        </init-param>
      </servlet>This is my quick analysis of what's not out-of-the-box compatible. I don't know enough about the changes in Struts 1.2 to know why this Struts 1.1 feature broke in Struts 1.2, or what the Struts 1.2 way to accomplish the same thing is.
    I'd encourage you to use Worldwide Support's Metalink site and open a TAR for any time-critical issues you need assistance in resolving. Many of us are constantly traveling and only able to sporadically chime in with tips in the forum as our time permits.
    The source of the BC4JRequestProcessor ships with the produce in the ./BC4J/src directory inside the bc4jstrutssrc.zip file.

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

  • Are static nested classes thread-safe?

    There doesn't seem to be any definitive answer to this. Given the following code, is it thread-safe?
    public class SomeMultiThreadedWebController {
    public HttpServletResponse someMethodToExecuteViaWebRequest(HttpServletRequest request) {
        simpleQueryBuilder("SELECT...").addParameter("asdf","asdf").createQuery(EMF.getEntityManager()).executeUpdate();
    protected static class SimpleQueryBuilder {
             private String queryString;
             private Map<String, Object> params = new HashMap<String, Object>();
             public SimpleQueryBuilder(String queryString) {
                  this.queryString = queryString;
             public SimpleQueryBuilder addParameter(String name, Object value) {
                  params.put(name, value);
                  return this;
             public Query createQuery(EntityManager em) {
                  Query query = em.createQuery(queryString);
                  for (Entry<String, Object> entry : params.entrySet()) {
                       query.setParameter(entry.getKey(), entry.getValue());
                  return query;
        public static SimpleQueryBuilder simpleQueryBuilder(String queryString) {
             return new SimpleQueryBuilder(queryString);
    }Forget whether or not someone would do this, as this is just an example. I'm really trying to get at whether or not the instance variables inside the static nested class are thread-safe. Thanks for any responses.

    Hello,
    I believe you understand what you're talking about, but you state it in a way that is very confusing for others.
    Let me correct this (essentially, incorrect uses of the terminology):
    I agree that thread-safe or not is for an operation, for a member, it has some sort of contextual confusion.
    Member has a much broader meaning in the [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.4] . Even "class member" applies to both an attribute, a method, or an inner class or interface.
    I think you mean "member variable" of a class (aka "attribute" or "field"). By the way, static or not is irrelevant to the rest of the discussion.
    For an operation or a member, if there's only one thread could access it atomically in one moment, we could call it thread-safe.Mmm. I was tempted to say yes (I'm reluctant to commit myself). With an emphasis on "_The encapsulating class_ makes this member's usage thread-safe".
    Still, just synchronizing each operation on a member is not enough to make all usages "thread-safe":
    Consider a java.util.Vector: each add/get is synchronized, so it is atomic, fine.
    However if one thread adds several values, let's say 3, one by one, to a vector that initially contains 0 values, and another thread reads the vector's size() (another properly synchronized method), the reader thread may witness a size anywhere among 0, 1, 2, 3, which, depending on the business logic, may be a severely inconsistent state.
    The client code would have to make extra work (e.g. synchronizing on the vector's reference before the 3 adds) to guarantee that the usage is thread-safe.
    Thus any synchronized method(With the limit stated above)
    or immutable member (like primitive type) are thread-safe.
    Additionally for a member, if it's immutable, then it's thread-safe. You mean, immutable primitive type, or immutable object. As stated previously, an immutable reference to a mutable object isn't thread-safe.
    a static final HashMap still have thread-safe issue in practice because it's not a primitive.The underlined part is incorrect. A primitive may have thread-safety issues (unless it's immutable), and an object may not have such issues, depending on a number of factors.
    The put, get methods, which will be invoked probably, are not thread-safe although the reference to map is.Yes. And even if the put/get methods were synchronized, the client code could see consistency issues in a concurrent scenario, as demonstrated above.
    Additional considerations:
    1) read/write of primitive types are not necessarily atomic: section [ §17.7 of the JLS|http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.7] explicitly states that writing a long or double value (2 32-bits words) may not be atomic, and may be subject to consistency issues in a concurrent scenario.
    2) The Java Memory Model explicitly allows non-synchronized operations on non-volatile fields to be implemented in a "thread-unsafe" way by the JVM. Leading way to a lot of unintuitive problems such as the "Double-Checked Locking idiom is broken". Don't make clever guess on code execution path unless you properly synchronize access to variables across threads.
    Edited by: jduprez on Mar 4, 2010 9:53 AM

  • Are servlets thread safe??

    Are servlets thread safe?? if not, then how to make them thread safe.

    Hi,
    servlets aren't thread-safe; you can make them thread-safe by implementing the interface javax.servlet.SingleThreadModel
    From the javadoc:
    public interface SingleThreadModel
    Ensures that servlets handle only one request at a time. This interface has no methods.
    If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet's service method. The servlet container can make this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of servlet instances and dispatching each new request to a free servlet.
    If a servlet implements this interface, the servlet will be thread safe. However, this interface does not prevent synchronization problems that result from servlets accessing shared resources such as static class variables or classes outside the scope of the servlet.

  • Are queries thread-safe ? (continued)

    Hi
    In a previous thread on this topic, it was said that a query can be reused, and why it was good on performance. But a reusable object is not necessarily thread-safe.
    So I ask again. Are queries thread-safe ?
    What about Expressions ?
    Thanks
    JCG

    Yes, they're thread safe, both expressions and Queries. TopLink makes copies of whatever parts of the Query/Expression are needed to be changes in parallel.
    - Don

  • 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

  • Please confirm that stubs are thread-safe

    Can someone please confirm that if one is to invoke the same remote method from more than one thread in a client application that one does not need to get multiple remote stubs for the same RMI server object. As long as the implementation of the remote method is thread safe, everything okay, correct?
    In otherwords, are remote stubs them selves thread safe? I always assumed they were.
    Thanks in advance

    Stubs are threadsafe. The reason is that a second concurrent invocation via the same stub will use a new TCP connection. I took this up with Sun once and the response was along the lines 'if it doesn't say it isn't thread-safe, it's thread-safe'.
    It's the method implementation at the server that isn't thread-safe, unless you make it so.

Maybe you are looking for