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]

Similar Messages

  • Using Thread in Helper Class Used By MDB

    Using Thread in Helper Class Used By MDB
    I am writting one Message driven bean (MDB) which will be deployed on
    weblogic 6.1.
    In MDB.onMessage I create instance of helper class.
    call it's method HelperClass.doSomething(s1,s2)
    in doSomething I start new thread
    checks if thread is alive
    when thread is dead return flag
    run method of helper class does following
    1. opens socket connection to some server
    2. writes some data to it
    3. read some data from it
    4. depending on response set flag
    I want to know whether this approach is corect.
    Specially when weblogic recommends not to use threads (or be extreamly
    careful about thread handling) .
    Following is code..
    MessageDrivenBeanClass{
         puboic void onMessage(Message msg){
              String s1 = "s1";
              String s2 = "s2";
              HelperClass helper = new HelperClass();
              boolean flg = helper.doSomething(s1,s2);
    HelperClass implements Runnable {
         String s1;
         String s2;
         boolean flg = false;
         public void HelperClass(){}
         public boolean doSomething(String s1, String s2){
              this.s1 = s1;
              this.s2 = s2;
              Thread t1 = new Thread(this);
              t1.start();
              while(true)
              if(!t1.isAlive())
                   break;
              return flg;
         public void run(){
              // do actual processing
              if(something)
                   flg = true;
              else
                   flg = false;

    What is the purpose of creating an extra thread in this scenario (if your
    code is going to wait until thread terminates anyway) ?
    Also, creating new threads can be expensive, so it is always better to use
    thread pool and not to create new thread every time.
    And,
    Thread t1 = new Thread(this);
    t1.start();
    while(true)
    if(!t1.isAlive())
    break;
    is going to waste ALOT of CPU time. t1.join() will work much better.
    sk <[email protected]> wrote:
    Using Thread in Helper Class Used By MDB
    I am writting one Message driven bean (MDB) which will be deployed on
    weblogic 6.1.
    In MDB.onMessage I create instance of helper class.
    call it's method HelperClass.doSomething(s1,s2)
    in doSomething I start new thread
    checks if thread is alive
    when thread is dead return flag
    run method of helper class does following
    1. opens socket connection to some server
    2. writes some data to it
    3. read some data from it
    4. depending on response set flag
    I want to know whether this approach is corect.
    Specially when weblogic recommends not to use threads (or be extreamly
    careful about thread handling) .
    Following is code..
    MessageDrivenBeanClass{
         puboic void onMessage(Message msg){
              String s1 = "s1";
              String s2 = "s2";
              HelperClass helper = new HelperClass();
              boolean flg = helper.doSomething(s1,s2);
    HelperClass implements Runnable {
         String s1;
         String s2;
         boolean flg = false;
         public void HelperClass(){}
         public boolean doSomething(String s1, String s2){
              this.s1 = s1;
              this.s2 = s2;
              Thread t1 = new Thread(this);
              t1.start();
              while(true)
              if(!t1.isAlive())
                   break;
              return flg;
         public void run(){
              // do actual processing
              if(something)
                   flg = true;
              else
                   flg = false;

  • Native library NOT thread safe - how to use it via JNI?

    Hello,
    has anybody ever tried to use a native library from JNI, when the library is not thread safe?
    The library (Windows DLL) was up to now used in an MFC App and thus was only used by one user - that meant one thread - at a time.
    Now we would like to use the library like a "server": many Java clients connect the same time to the library via JNI. That would mean each client makes its calls to the library in its own thread. Because the library is not thread safe, this would cause problems.
    Now we discussed to load the library several times - separately for each client (for each thread).
    Is this possible at all? How can we do that?
    And do you think we can solve the problem in this way?
    Are there other ways to use the library, though it is not thread safe?
    Any ideas welcome.
    Thanks for any contributions to the discussion, Ina

    (1)
    has anybody ever tried to use a native library from
    JNI, when the library (Windows DLL) is not thread safe?
    Now we want many Java clients.
    That would mean each client makes its calls
    to the library in its own thread. Because the library
    is not thread safe, this would cause problems.Right. And therefore you have to encapsulate the DLL behind a properly synchronized interface class.
    Now the details of how you have to do that depends: (a) does the DLL contain state information other than TLS? (b) do you know which methods are not thread-safe?
    Depending on (a), (b) two extremes are both possible:
    One extreme would be to get an instance of the interface to the DLL from a factory method you'll have to write, where the factory method will block until it can give you "the DLL". Every client thread would obtain "the DLL", then use it, then release it. That would make the whole thing a "client-driven" "dedicated" server. If a client forgets to release the DLL, everybody else is going to be locked out. :-(
    The other extreme would be just to mirror the DLL methods, and mark the relevant ones as synchronized. That should be doable if (a) is false, and (b) is true.
    (2)
    Now we discussed to load the library several times -
    separately for each client (for each thread).
    Is this possible at all? How can we do that?
    And do you think we can solve the problem in this
    way?The DLL is going to be mapped into the process address space on first usage. More Java threads just means adding more references to the same DLL instance.
    That would not result in thread-safe behavior.

  • How can I Access the Flash "Slide class" using flex and ActionScript 3?

    Hi,
    I hope someone can help me solve a problem...
    I'm using the flex SwfLoader to load a flash side
    presentation as follows...
    <mx:SWFLoader id="ss_slides" source="ss_slides.swf"
    width="320" height="240"/>
    I would like to access the flash "Slide Class" using flex so
    I can make the following call...
    Slide.gotoNextSlide();
    Anyone know how I can do that?
    Would it be through the SwfLoader Object?
    Is there another way?
    F.Y.I. Here is a snippets about the Slide class from the
    Flash 8 help...
    Using the Slide class (Flash Professional only)
    You use the methods and properties of the Slide class to
    control slide
    presentations you create using the Screen Outline pane for a
    Flash Slide
    Presentation, to get information about a slide presentation
    (for example, to
    determine the number of child slides contained by parent
    slide), or to navigate
    between slides in a slide presentation (for example, to
    create "Next slide" and
    "Previous slide" buttons).
    You can also use the built-in behaviors that are available
    in the Behaviors
    panel to control slide presentations. For more information,
    see Adding controls
    to screens using behaviors (Flash Professional only) in Using
    Flash.
    Thanks,
    Chris S.

    Hi Chris,
    You cannot access the methods of the Flash 8 movie from Flex.
    And you can't do it the other way around either.
    The only way to communicate is to create a LocalConnection on
    each side.
    M.

  • SharePoint 2013 - Office 365 Custom Rating(0-5) Sharepoint Hosted App SetRating Reputation Class using Javascript and CSOM

    I have created the list and enabled the rating feature. I want to display the List items and rate individual items from an App.  I can able to create and bind the rating control through CSOM associated with the Rating Value.  But I unable to rating
    when I click rating star button. I am using the below code for clicking through JavaScript
    function SetRating(webUrl, listId, itemId, ratingElementId) {
    hostWebContext = new SP.AppContextSite(context, hostWebUrl);
    var listPrograms = hostWebContext.get_web().get_lists().getByTitle("MyList");
    context.load(listPrograms);
    var RatingValue = 5;
    EnsureScriptFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation',
    function () {
    var rating = Microsoft.Office.Server.ReputationModel.Reputation.setRating(hostWebContext, listId, itemId, RatingValue);
    context.executeQueryAsync(Function.createDelegate(this, this.RatingSuccess), Function.createDelegate(this, this.RatingFailure));
    While executing this script I got error like get 0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'addQuery'
    * Which Context we have to use for this case? AppWeb / HostedWeb
    * Is there any way to update the rating control value at runtime?
    Please help us to find out the solution.
    Thanks.

    Hi Elie,
    Since this forum is discussing about Developing Apps for Office 2013, and your issue is more related about Exchange development. I will move this thread to the more related forum.
    Reference:
    https://social.msdn.microsoft.com/Forums/en-US/home?forum=exchangesvrdevelopment
    Thanks for your understanding.
    Best Regards,
    Edward
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Fill Child Class using C# and SCOM dlls

    Hello,
    We have requirement to run some c# tool and that tool insert the data to scom database. Can anyone please help me to achieve this.
    the structure is as below.
    1. Base class (this class is having "Source" as Windows.Computer)
      and Base class will be filled by Discovery
    2. Child class (Base class is the "Source" for this child class)
    now the c# tool has to fill the Child class.
    Thanks in advance.
    regards,
    Mahadevan.G

    Just try to get property Base.
    Vladimir Zelenov | http://systemcenter4all.wordpress.com

  • Thread-safe Singleton

    Hi,
    I want to create a thread safe singleton class. But dont want to use the synchronized method or block. One way i could think of was initializing the object in static block. This way the instance will be created only once. But what if instance becomes null after some time. How will it get initialized again. Can anyone help me in creating a thread safe singleton class.
    Also i would really really appreciate if some one can point me to a good tutorial on design patters, I searched on google.. Found many.. But not finding any of them satisfying.
    Thanks

    tschodt wrote:
    Balu_ch wrote:
    kilyas wrote:
    Look into the use of volatile instead of synchronized, however the cost of using volatile is comparable to that of synchronizingCan you please explain in detail Google can.
    Google ( [java volatile vs synchronized|http://www.google.com/search?q=java+volatile+vs+synchronized] ).
    Hi, I think we need to use both (volatile and synchronized). Can some please explain how "volatile" alone can be used to ensure thread safe singleton? Below is the code taken from wikipedia
    public class Singleton {
       // volatile is needed so that multiple thread can reconcile the instance
       // semantics for volatile changed in Java 5.
       private volatile static Singleton singleton;
       private Singleton()
       // synchronized keyword has been removed from here
       public static Singleton getSingleton(){
         // needed because once there is singleton available no need to acquire
         // monitor again & again as it is costly
         if(singleton==null) {
           synchronized(Singleton.class){
              // this is needed if two threads are waiting at the monitor at the
              // time when singleton was getting instantiated
              if(singleton==null)
              singleton= new Singleton();
       return singleton;
    }

  • [SOLVED] Singleton thread safe

    If I have a singleton object where all instance and class variables are thread safe objects, is that object thread safe?
    Edited by: 888903 on Oct 3, 2011 8:30 PM

    888903 wrote:
    If I have a singleton object where all instance and class variables are thread safe objects, is that object thread safe?First, "all instance and class variables are thread safe objects" cannot be true, because variables are not objects. Presumably you meant to say that these variables refer to threadsafe objects.
    As for your question, no, you cannot say that a given object is threadsafe just because all its member variables are. It depends on the semantics of your class, and what it needs to be atomic. For example, take the following class:
    public class Person {
      private String firstName;
      private String lastName;
      public String getName() {
        return firstName + " " + lastName;
      public void updateName(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }Here, we have a class like what you describe. (The fact your case involves a singleton is irrelevant.) My String member variables are threadsafe, but my Person class is not. If I start with "Joe Smith" and then later I call person.updateName("Fred", "Jones"), another thread could call getName() after I've updated the first but before the last, so he'd see "Fred Smith", which is incorrect. He should see only "John Smith" or "Fred Jones", not an intermediate value.

  • 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

  • Vector is not  a Thread safe so where be use it and why?

    Can anyone tell me
    When Vector is not a Thread safe so where be use it and why?

    Suppose you use a Vector<Listener> to store your list of listeners. While the Vector class is thread-safe, which means that its methods can be called without additional synchronization without risk of corrupting the Vector data structures, iterating a collection involves "check-then-act" sequences, which are at risk of failing if the collection is modified during iteration. Let's say there are three listeners in your list at the start of iteration. As you iterate through the Vector, you repeatedly call size() and get() until there are no more elements to retrieve, as in Listing 1:
    Listing 1. Unsafe iteration of a Vector
    Vector<Listener> v;
    for (int i=0; i<v.size(); i++)
    v.get(i).eventHappened(event);
    But what happens if, just after you call Vector.size() for the last time, someone removes a listener from the list? Now, Vector.get() will return null (which is correct, because the state of the vector has changed since you last checked), and you will throw a NullPointerException when you try to call eventHappened(). This is an example of a check-then-act sequence -- you check to see if any more elements exist, and if so, you get the next element -- but in the presence of concurrent modification, the state could have changed since the check.
    I read that at IBM sites
    Thanks in advance for clearing my doubts...

  • When ever I use Adobe reader 11 with a USB device, I cannot safe remove the USB device and get the following message (or similar one) in system log:  The application \Device\HarddiskVolume1\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe with pr

    When ever I use Adobe reader 11 with a USB device, I cannot safe remove the USB device and get the following message (or similar one) in system log:  The application \Device\HarddiskVolume1\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe with process id 6620 stopped the removal or ejection for the device USB\VID_05DC&PID_C75C\20131215015821328FC8.
    I am running on Windows Server 2012 R2 in Desktop Experience mode.
    Any ideas?
    Roger

    In addition to that symptom, I discovered that even though I had closed all Adobe Reader sessions, the processes kept running and used up 90%+ of my CPU.

  • Thread safe do-all class

    Hi,
    I'm new to Java programming and I've read through the forums and the numerous technical documents Sun has provided on how to make a GUI thread-safe. With what I've been able to understand, I created some template classes to handle the proper creation of JFrames, so I don't have to worry about playing with threads all the time. (I am operating under the assumption that invokeLater should handle the creation of all frames, not just the first window of the application).
    Since I'm not completely confident I've grasped the point, I was wondering if someone could look at this code to see if I've got the right idea. Your help would be much appreciated.
    Test.java
    import frames.*;
    public class Test
         public static void main(String args[])
              FrameOptions frameOpts = new FrameOptions("Options Window", 300, 400, true);
    frames\FrameOptions.java
    package frames;
    public class FrameOptions extends FrameTemplate
         public FrameOptions(String title, int width, int height, final boolean visible)
              super(title, width, height);
              javax.swing.SwingUtilities.invokeLater     (     new Runnable()
                                                 public void run()
                                                      createAndShow(visible);
         public void createAndShow(boolean visible)
              //Add all Swing components here.
              finishCreateAndShow(visible);
    frames\FrameTemplate.java
    package frames;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    public class FrameTemplate extends JFrame
         public FrameTemplate(String title)
              super(title);
         public FrameTemplate(String title, int width, int height)
              super(title);
              doSize(width, height);
         private void doSize(int width, int height)
              Dimension d = new Dimension(width, height);
              setMinimumSize(d);
              setPreferredSize(d);
         protected void finishCreateAndShow(boolean visible)
              pack();
              setVisible(visible);
    }

    OK, makes sense now.
    For anyone else who may be new and wondering about this, this can be summed up as follows.
    Summary 1:
    If you create new frames from things such as menu events, you do not need to use invokeLater. Events are automatically done in the GUI thread/event dispatching thread. But if you're spawning these things from main() (or anything else not running in the EDT), you do.
    If you're ever unsure of which thread a block of code is running in, just drop a System.out.println(javax.swing.SwingUtilities.isEventDispatchThread()); into it.
    Summary 2:
    Don't use those classes I wrote. They're rather pointless unless you're spawning all of your frames from main, which I suspect most people would not be doing.
    Thanks for the clarification.
    public static void main(String args[])
    is run in a separate thread (separate from the GUi
    i thread). So if you need to do painting or other
    swing stuff from inside the main method, just use an
    invoke later. If you create a new frame from the GUI
    thread, you don't need to invoke later. Only if you
    do it from the main method (or some other non-GUI
    thread). Hope that helps

  • 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

  • Coherence SimpleParser class is not thread safe?

    Coherense has very convinent XML utility class, which we use it a lot within our Coherence related applications.
    But we encounter some mysterious lock up (maybe deadlock?) issue and identified that it might be that the com.tangosol.run.xml.SimpleParser class is not thread safe.
    We are using tomcat 6 and spring 2.0.6.
    One of the webapp has 2 bean which implements InitializingBean interface.
    Bean A's afterPropertiesSet() method will use com.tangosol.run.xml.XmlHelper.loadXml method to parse a XML file.
    Bean B's afterPropertiesSet() method will acts as a tcp extend client and retrieve some data from a coherence cluster. Which I believe coherence will also use it's XML utility class when parsing the configuration files.
    We encounter tomcat lockup (which never finish startup webapp deployment porcess) randomly like 1 out of 2 or 3 tries.
    Use jconsole and connect to tomcat we can see that the main thread stuck in SimpleParser class. Here is the thread dump.
    Name: main
    State: RUNNABLE
    Total blocked: 156 Total waited: 0
    Stack trace:
    com.tangosol.run.xml.SimpleParser.instantiateDocument(SimpleParser.java:150)
    com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:115)
    - locked com.tangosol.run.xml.SimpleParser@f10c77
    com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:71)
    com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:84)
    com.tangosol.run.xml.XmlHelper.loadXml(XmlHelper.java:109)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1201)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1171)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:425)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
    - locked java.util.concurrent.ConcurrentHashMap@dee55c
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:287)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
    - locked java.lang.Object@d21555
    org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:244)
    org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:187)
    org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:49)
    org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3830)
    org.apache.catalina.core.StandardContext.start(StandardContext.java:4337)
    - locked org.apache.catalina.core.StandardContext@1c64ed8
    org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
    - locked java.util.HashMap@76a6d9
    org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
    org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
    org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:825)
    org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:714)
    org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:490)
    org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
    org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
    org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
    org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    - locked org.apache.catalina.core.StandardHost@1c42c4b
    org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
    - locked org.apache.catalina.core.StandardHost@1c42c4b
    org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    - locked org.apache.catalina.core.StandardEngine@37fd24
    org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    org.apache.catalina.core.StandardService.start(StandardService.java:516)
    - locked org.apache.catalina.core.StandardEngine@37fd24
    org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    - locked [Lorg.apache.catalina.Service;@1cc55fb
    org.apache.catalina.startup.Catalina.start(Catalina.java:566)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
    org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
    After we add the depends-on tag to enforce bean B wait on bean A to finish initialization, we no longer encounter the lockup during tomcat startup.
    We suspect that maybe SimpleParser class is not thread safe and will cause potential deadlock issue.
    Edited by: user639604 on Jun 22, 2009 10:36 AM

    While it doesn't show up as deadlock, I believe it probably is, as evidenced by these two threads:
    "Timer-0" prio=10 tid=0xcb9a2800 nid=0x454b in Object.wait() [0xcb6e0000..0xcb6e10a0]
       java.lang.Thread.State: RUNNABLE
         at com.tangosol.run.xml.SimpleParser.instantiateDocument(SimpleParser.java:150)
        at com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:115)
         - locked <0xf44e52f0> (a com.tangosol.run.xml.SimpleParser)
         at com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:71)
         at com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:99)
         at com.tangosol.run.xml.XmlHelper.loadXml(XmlHelper.java:129)
         at com.tangosol.run.xml.XmlHelper.loadXml(XmlHelper.java:95)
         at com.tangosol.run.xml.XmlHelper.loadXml(XmlHelper.java:72)
         at com.tangosol.util.ExternalizableHelper.<clinit>(ExternalizableHelper.java:4466)
         at com.evidentsoft.opcache.coherence.OPCacheCoherenceStorage.retrieve(OPCacheCoherenceStorage.java:341)
         at com.evidentsoft.opcache.coherence.OPCacheCoherenceStorage.retrieve(OPCacheCoherenceStorage.java:420)
         at com.evidentsoft.opcache.OPCacheManager.find(OPCacheManager.java:68)
         at com.evidentsoft.logserver.coherence.ClusterDetector.detectNewClusters(ClusterDetector.java:97)
         at com.evidentsoft.logserver.coherence.ClusterDetector.access$000(ClusterDetector.java:19)
         at com.evidentsoft.logserver.coherence.ClusterDetector$1.run(ClusterDetector.java:67)
         at java.util.TimerThread.mainLoop(Unknown Source)
         at java.util.TimerThread.run(Unknown Source)
    "main" prio=10 tid=0x08059000 nid=0x4539 in Object.wait() [0xf7fd0000..0xf7fd11f8]
       java.lang.Thread.State: RUNNABLE
         at com.tangosol.run.xml.SimpleParser.instantiateDocument(SimpleParser.java:150)
         at com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:115)
         - locked <0xf44ecd90> (a com.tangosol.run.xml.SimpleParser)
         at com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:71)
         at com.tangosol.run.xml.SimpleParser.parseXml(SimpleParser.java:84)
         at com.tangosol.run.xml.XmlHelper.loadXml(XmlHelper.java:109)
         at com.evidentsoft.coherence.util.ClusterConfigurator.generateConfigFile(ClusterConfigurator.java:319)
         at com.evidentsoft.coherence.util.ClusterConfiguratorProxy.afterPropertiesSet(ClusterConfiguratorProxy.java:51)
         at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1201)
         at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1171)
         at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:425)
         at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
         at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
         - locked <0xd65efb88> (a java.util.concurrent.ConcurrentHashMap)
         at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
         at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
         at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:287)
         at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
         - locked <0xd65efc28> (a java.lang.Object)
         at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:244)
         at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:187)
         at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:49)
         at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3830)
         at org.apache.catalina.core.StandardContext.start(StandardContext.java:4337)
         - locked <0xd6092f60> (a org.apache.catalina.core.StandardContext)
         at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
         - locked <0xd54ff278> (a java.util.HashMap)
         at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
         at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
         at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:825)
         at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:714)
         at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:490)
         at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
         at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
         at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
         at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
         - locked <0xd54ff1e8> (a org.apache.catalina.core.StandardHost)
         at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
         - locked <0xd54ff1e8> (a org.apache.catalina.core.StandardHost)
         at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
         - locked <0xd4fa60b8> (a org.apache.catalina.core.StandardEngine)
         at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
         at org.apache.catalina.core.StandardService.start(StandardService.java:516)
         - locked <0xd4fa60b8> (a org.apache.catalina.core.StandardEngine)
         at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
         - locked <0xd4f17ea0> (a [Lorg.apache.catalina.Service;)
         at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
         at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)The reason it isn't showing up as a deadlock in the thread dump is that the ExternalizableHelper static initializer isn't completing, so the other thread (blocking it) is waiting indefinitely on that class to become available.
    Peace,
    Cameron Purdy | Oracle Coherence

  • 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

Maybe you are looking for