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

Similar Messages

  • Is singleton thread safe?

    hello all,
    please help me by answering these questions?
    singleton patterns calls for creation of a single class that can be shared between classes. since one class has been created
    Can singletons be used in a multithreaded environment? is singleton thread safe?
    Are threading problems a consequence of the pattern or programming language?
    thank you very much,
    Hiru

    Hi,
    Before explaining whether a singleton is thread safe
    e i want to explaing what is thread safe here
    When multiple threads execute a single instance of a
    program and therefore share memory, multiple threads
    could possibly be attempting to read and write to the
    same place in memory.If we have a multithreaded
    program, we will have multiple threads processing the
    same instance.What happens when Thread-A examines
    instance variable x? Notice how Thread-B has just
    incremented instance variable x. The problem here is
    Thread-A has written to the instance variable x and
    is not expecting that value to change unless Thread-A
    explicitly does so. Unfortunately Thread-B is
    thinking the same thing regarding itself; the only
    problem is they share the same variable.
    First method to make a program threadsafe-: Avoidance
    To ensure we have our own unique variable instance
    for each thread, we simply move the declaration of
    the variable from within the class to within the
    method using it. We have now changed our variable
    from an instance variable to a local variable. The
    difference is that, for each call to the method, a
    new variable is created; therefore, each thread has
    its own variable. Before, when the variable was an
    instance variable, the variable was shared for all
    threads processing that class instance. The following
    thread-safe code has a subtle, yet important,
    difference.
    second defense:Partial synchronization
    Thread synchronization is an important technique to
    know, but not one you want to throw at a solution
    unless required. Anytime you synchronize blocks of
    code, you introduce bottlenecks into your system.
    When you synchronize a code block, you tell the JVM
    that only one thread may be within this synchronized
    block of code at a given moment. If we run a
    multithreaded application and a thread runs into a
    synchronized code block being executed by another
    thread, the second thread must wait until the first
    thread exits that block.
    It is important to accurately identify which code
    block truly needs to be synchronized and to
    synchronize as little as possible. In our example, we
    assume that making our instance variable a local
    variable is not an option.
    Third Defence:--Whole synchronization
    Here u should implement an interface which make the
    whole class a thread safe on or synchronized
    Thre views are made by Phillip Bridgham, M.S., is a
    technologist for Comtech Integrated Systems.I'm
    inspired by this and posting the same hereWas there a point in all of that? The posted Singleton is thread-safe. Furthermore, some of that was misleading. A local variable is only duplicated if the method is synchronized, a premise I did not see established. Also, it is misleading to say that only one Thread can be in a synchronized block of code at any time because the same block may be using different monitors at runtime, in which case two threads could be in the same block of code at the same time.
    private Object lock;
    public void doSomething() {
        lock = new Object();
        synchronized(lock) {
            // Do something.
    }It is not guaranteed that only one Thread can enter that synchronized block because every Thread that calls doSomething() will end up synchronizing on another monitor.
    This is a trivial example and obviously something no competent developer would do, but it illustrates that the statement assumes premises that I have not seen established. It would be more accurate to say that only one Thread can enter a synchronized block so long as it uses the same monitor.
    It's also not noted in the discussion of local variables vs instance variables that what he says only applies to primitives. When it comes to actual Objects, just because the variable holding the reference is unique to each Thread does not make use of it thread-safe if it points to an Object to which references are held elsewhere.

  • 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;
    }

  • Is abap thread safe? Some question in Singleton pattern in ABAP

    Hi Grus,
    I have a very basic question but really make me headache...
    Recently I am learning the design pattern in ABAP and as you know in JAVA there is a key word "Synchronized" to keep thread safe. But in ABAP, I didn't find any key words like that. So does that mean ABAP is always a single thread language? And I found that there is a way looks like "CALL FUNCTION Remotefunction STARTING NEW TASK Taskname DESTINATION dest" to make multi-thread works. As you can see it use the destination, so does that mean actually the function module is always executed in a remote system, and in every system, it is always single thread?
    Could you help me on the question? Thanks a lot, grus
    And here comes up to my mind another question...It's a little bit mad but I think it may works....What if I set every attribute and method as static in the singleton class...Since as you can see it is already a singleton so every attribute in it should be only one piece. So then I don't even need to implement a get_instance( ) method to return the instance. Just call "class_name=>some_method( )" directly then singleton is achieved...What do you think?
    BR,
    Steve

    Steve,
    I've the same question, few days ago I tried to use the singleton in ABAP. In Java programming is possible to use the same reference in two sessions or programs, sharing attributes, methods and all data, but I could not do in ABAP.
    In my test I created a program with one global class using the singleton pattern, so I expected that when I run my program and see the reference returned after the get_instance method it should be equal to the same program run in another session, but the ABAP will create a new reference and instantiate again.
    So I deduced that the only way to share it between sessions in ABAP is using the ABAP Shared Memory Objects.
    I can be wrong, but I think that ABAP use a thread by user session (Each window) and we can't change it.
    Best regards.

  • Thread safe ?

    Hi
    This code is currently running on my companys server in a java class implementing the singleton pattern:
    public static ShoppingAssistant getInstance() {
        if (instance == null) {
            synchronized (ShoppingAssistant.class) {
                instance = new ShoppingAssistant();
        return instance;
    }1 Is there really a need for synchronizing the method?
    2 If you choose to synchronize it. Why not just synchronize the whole method?
    3 Is this method really thread safe? Is I see it a thread A could be preempted after checking the instance and seing that it is null. Thereafter another thread B could get to run, also see that instance is null and go on and create the instance. Thereafter B modifies some of the instance�s instance variables. After that B is preempted and A gets to run. A, thinking instance is null, goes on and create a new instance of the class and assigns it to instance, thus owerwriting the old instance and creating a faulty state.
    By altering the code like this I think that problem is solved although the code will probably run slower. Is that correct?
    public static ShoppingAssistant getInstance() {
        synchronized (ShoppingAssistant.class) {
            if (instance == null) {
                instance = new ShoppingAssistant();
    }Regards, Mattias

    public class Singleton {
    private static final instance = newSingleton();
    public static Singleton getInstance() {
    return instance;
    }This seems like it's so obviously the standard
    solution, why do
    people keep trying to give lazy solutions? Do they
    expect it to be
    more efficient that this?I can see one possible performance gains with a lazy solution:
    If you use something else in that class (besides getInstance()), but don't use getInstance, then you don't take the performance hit of instantiating the thing.
    Of course, this is dubious at best because how often do you have other static methods in your singleton class? And not use the instance? And have construction be so expensive that a single unnecessary one has a noticeably detrimental impact on your app's performance?

  • How can I use a Selector in a thread safe way?

    Hello,
    I'm using a server socket with a java.nio.channels.Selector contemporarily by 3 different threads (this number may change in the future).
    From the javadoc: Selectors are themselves safe for use by multiple concurrent threads; their key sets, however, are not.
    Following this advise, I wrote code in this way:
             List keys = new LinkedList(); //private key list for each thread
             while (true) {
              keys.clear();
              synchronized(selector) {
                  int num = selector.select();
                  if (num == 0)
                   continue;
                  Set selectedKeys = selector.selectedKeys();
                  //I expected this code to produce disjoint key sets on each thread...
                  keys.addAll(selectedKeys);
                  selectedKeys.clear();
              Iterator it = keys.iterator();
              while (it.hasNext()) {
                  SelectionKey key = (SelectionKey) it.next();
                  if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
                   Socket s = serverSocket.accept();
                   SocketChannel sc = s.getChannel();
                   sc.configureBlocking( false );
                   sc.register( selector, SelectionKey.OP_READ );
                  } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
    //.....Unfortunately synchronizing on the selector didn't have the effect I expected. When another thread select()s, it sees the same key list as the other thread that select()ed previously. When control arrives to serverSocket.accept(), one thread goes ahead and the other two catch an IllegalBlockingModeException.
    I'm not willing to handle this exception, the right thing to do is giving disjoint key sets to each thread. How can I achieve this goal?
    Thanks in advance

    A single thread won't be enough cause after reading data from the socket I do some processing on it that may take long.So despatch that processing to a separate thread.
    Most of this processing is I/O boundI/O bound on the socket? or something else? If it's I/O bound on the socket that's even more of a reason to use a single thread.
    Anyway I think I'll use a single thread with the selector, put incoming data in a queue and let other 2 or 3 threads read from it.Precisely. Ditto outbound data.
    Thanks for your replies. But I'm still curious: why is a selector thread safe if it can't be used with multiple threads because of it's semantics?It can, but there are synchronization issues to overcome (with Selector.wakeup()), and generally the cost of solving these is much higher than the cost of a single-threaded selector solution with worker threads for the application processing.

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

  • Thread safe RMI

    Thread safe RMI.
    My RMI server provides clients with the ability to CRUD data but in order to manage concurrency I did the following.
    1stly I would like to understand correctly the issues of RMI server objects....
    It is my understanding that RMI server can cater for eg 100 clients by spawning 100 threads at random for each client. This process is not managed (thread wise) and the result is that 20 clients wishing to update record A can do so at will? Various steps can be taken from what I gather...
    a) Synchronise (expensive)
    b) implement a lock manager.
    The step I have taken is include a lock manager and I have ensured that all locking an unlocking occur in a singleton server object that manages all sensitive data CRUD operations. Now I use a lock manager but I would like to know what happens if for eg the 1st RMI client dies and has its thread blocking
    all other threads from locking the same record? Does the thread die with the client or is there a counter measure for this? The obvious answer that comes to mind is Object.wait() inside the lock manager?
    The reason I ask was that because all of the locking occurs in a single method call in the Network
    Server's JVM, so is there a need to worry about the RMI connection dying during the middle the locking operation.
    Edited by: Yucca on May 23, 2009 8:14 PM/*
    * @(#)LockManager.java
    * Version 1.0.0
    * 27/03/2009
    import java.util.HashMap;
    import java.util.Map;
    import java.util.logging.Logger;
    import java.util.ResourceBundle;
    class LockManager {
         * The <code>Map</code> containing all the record number keys of currently
         * locked records that pair with the cookie value assigned to them when they
         * are initially locked.
        private static Map<Integer, Long> currentlyLockedMap =
                new HashMap<Integer, Long>();
        private static final Logger LOG = Logger.getLogger("project.db");
         * Locks a record so that it can only be updated or deleted by this client.
         * Returned value is a <code>long</code> that is the cookie value that must
         * be used when the record is unlocked, updated, or deleted.
         * If the specified record is already locked by a different client, then the
         * current thread gives up the CPU and consumes no CPU cycles until the
         * record is unlocked.
         * @param   recNo                   the assigned primary key of the record
         *                                  to be locked for an operation.
         * @param   data                    a <code>Data</code> instance used to
         *                                  check if the record exists before
         *                                  attempting the lock operation.
         * @return                          A <code>long</code> containing the
         *                                  cookie value that must be used when the
         *                                  record is unlocked.
         * @throws  RecordNotFoundException if specified record does not exist or if
         *                                  specified record is marked as deleted
         *                                  in the database file.
        long lock(int recNo, DB data) throws RecordNotFoundException {
            LOG.entering(this.getClass().getName(), "lock", recNo);
            synchronized (currentlyLockedMap) {
                try {
                    while (currentlyLockedMap.containsKey(recNo)
                            && currentlyLockedMap.get(recNo)
                            != Thread.currentThread().getId()) {
                        currentlyLockedMap.wait();
                    // Check if record exists.
                    data.read(recNo);
                    long cookie = Thread.currentThread().getId();
                    currentlyLockedMap.put(recNo, cookie);
                    LOG.fine("Thread " + Thread.currentThread().getName()
                            + "got Lock for " + recNo);
                    LOG.fine("Locked record count = " + currentlyLockedMap.size());
                    LOG.exiting(this.getClass().getName(), "lock", true);
                    return cookie;
                } catch (InterruptedException ie) {
                    throw new SystemException("Unable to lock", ie);
         * Releases the lock on a record. The cookie must be the cookie returned
         * when the record was locked.
         * @param   recNo                   the assigned primary key of the record
         *                                  to be unlocked after an operation.
         * @param   cookie                  the cookie returned when the record was
         *                                  locked.
         * @throws  RecordNotFoundException if specified record does not exist or if
         *                                  specified record is marked as deleted
         *                                  in the database file.
         * @throws  SecurityException       if the record is locked with a cookie
         *                                  other than cookie.
        void unlock(int recNo, long cookie) throws RecordNotFoundException,
                SecurityException {
            LOG.entering(this.getClass().getName(), "unlock",
                    new Object[] { recNo, cookie });
            synchronized (currentlyLockedMap) {
                checkLock(recNo, cookie);
                currentlyLockedMap.remove(recNo);
                LOG.fine("released lock for " + recNo);
                currentlyLockedMap.notifyAll();
            LOG.exiting(this.getClass().getName(), "unlock");
         * Checks if the given record is locked before doing any modification or
         * unlocking for the record.
         * <p/>
         * Checks the <code>Map</code> of record number keys and cookie values
         * to see if it contains the given record number.
         * @param   recNo                   the assigned primary key of the record
         *                                  to be checked if it is locked.
         * @param   lockCookie              the cookie returned when the record was
         *                                  initially locked.
         * @throws  SecurityException       if no lock exists for the record or if
         *                                  the record has been locked with a
         *                                  different cookie.
        void checkLock(int recNo, long lockCookie) throws SecurityException {
            LOG.entering(this.getClass().getName(), "checkLock",
                    new Object[] { recNo, lockCookie });
            // Check if record has been locked
            if (!currentlyLockedMap.containsKey(recNo)) {
                throw new SecurityException(ResourceBundle.getBundle(
                        "resources.ErrorMessageBundle").getString(
                        "lockNotAppliedKey"));
            // Check if record has been locked by different cookie.
            if (currentlyLockedMap.get(recNo) != lockCookie) {
                throw new SecurityException(ResourceBundle.getBundle(
                        "resources.ErrorMessageBundle").getString(
                        "notLockOwnerKey"));
            LOG.exiting(this.getClass().getName(), "checkLock");
    }Edited by: Yucca on May 23, 2009 8:16 PM
    Edited by: Yucca on May 23, 2009 8:18 PM

    It is my understanding that RMI server can cater for eg 100 clients by spawning 100 threads at random for each client.No. It spawns a new thread for every new connection. At the client end, RMI makes a new connection for every call unless it can find an idle connection to the same host that is less than 15 seconds old. So if the client is doing concurrent calls there will be concurrent threads at the server for that client.
    This process is not managed (thread wise)'Managed' meaning what?
    the result is that 20 clients wishing to update record A can do so at will?The result is that an RMI server is not thread safe unless you make it so.
    a) Synchronise (expensive)Compared to a database update the cost of synchronization is trivial.
    b) implement a lock manager. The database should already have one of those, and so does java.util.concurrent. Don't write your own. Personally I would just syncrhonize around the database calls.
    what happens if for eg the 1st RMI client dies and has its thread(a) the client doesn't have a thread, see above. The call has a thread.
    (b) at the server, the call will execute, regardless of the state of the client, until it is time to write the result back to the client, at which point the write will encounter an IOException of some description and the thread will exit.
    blocking all other threads from locking the same record?That can't happen unless you foul up your concurrency management.
    Does the thread die with the clientIt dies with the call.
    is there a need to worry about the RMI connection dying during the middle the locking operation.The server JVM won't notice until it is time to write the call result back, see above.

  • ODBC SQLGetData not thread-safe when retrieving lob

    Hi MaxDB developpers,
    we are in the process of migrating our solution from SapDb 7.4.03.32 to MaxDb 7.6.03.7. We use the ODBC driver on windows, from multi-threaded applications.
    We encountered bugs in the ODBC driver 7.4.03.32 and made our own fixes since we had the sources. I checked if these problems were fixed in 7.6.03.7 and they are allmost addressed, but one:
    when two threads use two different stmt from the same dbc and call simultaneously SQLGetData to retrieve a LONG column, a global variable not protected by a critical section is changed and the application crashes. The variable in cause is dbc_block_ptr->esqblk.sqlca.sqlrap->rasqlldp which is set by pa30bpcruntime and reset by pa30apcruntime during the call to apegetl. Calls to apegetl are protected by PA09ENTERASYNCFUNCTION except in SQLGetData, when it calls pa60MoveLongPos or pa60MoveLong.
    Since MaxDB is a critical feature of our application, we would like to know when this bug can be fixed by SAP. Or maybe could we get access to the sources of sqlod32w.dll 7.6.03.7 to fix it ourselves ?
    Thanks,
    Guillaume

    Hello Guillaume
    Regarding the threaded access to SQLGetData. Of course, it is possible to manage the syncronization as you proposed. However, I'm still not sure, whether this really solves general problems.
    The point is, that the MaxDB-ODBC driver is thread safe for concurrent connections, but not for concurrent statement processing within a single connection. Therefore I would like to ask you how your application accesses data via SQLGetData (due to connections and threads), and what amount of data is usually transfered.
    Regards  Thomas

  • Is XMLProcessor Thread Safe?

    I was wondering if the XMLProcessor.processXSL(xsl, null) method is thread safe?
    What if there were a single instance ( Singleton ), would it be able to handle multiple request without failing?
    Any help or direction would be of great help.
    null

    is vector thread safe ?
    is arraylist thread safe ?
    i want to use any one of thsese without
    Synchronised keyword
    Vector is synchronized but ArrayList is not. This means that two different threads cannot access the same method in a Vector at the same time. An ArrayList can easily be made synchronized and will then behave as a Vector.
    Now synchronized methods don't necessarily lead to thread-safe code. That depends on how the Vector/ArrayList is used. Have a look at the new concurrency package in Java 5. It contains lots of readymade collections with different behaviours. Maybe one will suit your needs and be thread-safe with your usage right out of the box.

  • Thread Safe Testing

    I havn't written much mult-threaded code but I realise it's important when many web round-trips are required.
    How do I design, test and verify that I have a thread-safe application? I don't like relying on the testing statistics of chance unless the odds of failure are 0.0001%!
    Is there a correct way to verify a thread-safe application?

    I agree it is a lofty, though sadly in all probability too time consuming, goal to achieve. However, there are a few pitfalls to watch out for that should get most of the common, pernicious thread safety issues:
    Synchronize data that must be shared. This will involved performance bottle-necks. If the data is read-mostly, consider a Singleton cache. Though pitfalls will always remain here. Data sharing among threads, IMO, is the single greatest issue.
    Use static methods and instances wisely. If an object has instance variables that are used from method to method call (either within the class or from the caller), then state exists for that object. It is inherently a candidate to look at in terms of thead-safety. This class should be created for each logical unit of work that depends on its state. So, do not reuse these classes among threads (or at least provide an init() or reset() method to clear the state). The same applies to static methods. You can safely use a static method from multiple threads if it does not modify other static variables (e.g., changing the state of a static variable).
    Within the Collections API, pay attention to which types are synchronized and which are not. The Javadocs will specify.
    Try to write methods thread-safe. Have them only use the arguments provided in the method's signature.
    Watch for relatively simple race conditions that can easily be spotted.
    static private Singleton INSTANCE;
    private Singleton() {
        super();
        // Now I will fetch values from a database, perhaps taking seconds
    static final public Singleton getInstance() {
          if (INSTANCE == null) {
             INSTANCE = new Singleton();  // what if this takes some time, e.g. database query to get cache values?
          return INSTANCE;
    }Not good. Here's a possible refactoring:
    private static final Singleton INSTANCE;  // bonus, we can now make it final
    static {
       INSTANCE = new SIngleton();  // Occurs only when class is loaded, atomic
    public static final Singleton getInstance() {
      return INSTANCE;  // no race condition
    }The above would be even more applicable and pronounced if you offered a static refresh() method on the instance, say to refresh its cache of data from a database.
    Seems easy, right? The rub is that you need to verify that a given method does not call other methods that are not thread-safe. If every class you design follows the above precepts, then you will probably only be chasing down rarer thread-safety issues.
    - Saish

  • Thread-Safe BC4J Application

    Hello,
    I have an BC4J-based application, based on BC4J9.0.2. I'm considering to upgrade my BC4J library to upper version to make my application more thread-safe.
    How can I make thread-safe application using BC4J? Is there any specific Rule?
    Thank you.

    Hi,
    Its hard to define a single rule since it depends upon how each application is using threads. I have included some thoughts about the most common scenarios for web clients below:
    The BC4J client wizards (datatags, struts, JClient) will help you generate threadsafe applications. The general rule when writing a web client is to ensure that each "user", as represented by an HttpSession instance, has their own ApplicationModule instance. Using the ApplicationModule datatag or the BC4J/Struts framework will guarantee this.
    Beyond this it may also be necessary to coordinate multiple concurrent requests from a single client (imagine a user pounding on the browser refresh button). One approach for solving this problem is to synchronize requests on some sort of session context. The ApplicationModule tag supports a latching mode (see the lock attribute) which performs this by synchronizing access to the SessionCookie (cached in session, used to acquire ApplicationModule instance). Support for latching will also be available in Struts in the 9.0.3.3 and later timeframe.
    Hope this helps,

  • Xerces2 thread-safe?

    Hello
    Since moving from jaxp1.1 to jaxp1.2, I have problems with my application which reads the same XML DOM Document from within several threads (only reading!). This makes me believe that Crimson as the default XML parser of jaxp1.1 was thread-safe, whereas Xerces2 as the default parser of jaxp1.2 isn't. I didn't find any information about thread-safety on the apache site.
    Any comments about that?

    I had collisions when different threads where using the same DocumentBuilder to build DOM at the same time.
    It was a mistake from me: I should not have encapsulated the DocumentBuilderFactory.newInstance() in a singleton, but should have returned a new DocumentBuilderFactory.newInstance() each time!

  • Are SocketFactory implementations thread-safe?

    Hi!
    I'm using a SSLSocketFactory-singleton (SSLSocketFactoryImpl it is I guess) for creating SSLSocket-instances in my application.
    I just wondered whether or not I need synchronization especially for using the createSocket(...)-methods in my multi-threaded application, since I can't look in the code due to restrictions. Another question is whether the answer applies to other SocketFactory implementations.
    Greetings

    georgemc wrote:
    JAVAnetic wrote:
    georgemc wrote:
    Why would you need SocketFactory to be thread-safe anyway?Because, in my multi-threaded application I want to use only one SocketFactory-instance to reduce the overhead of creating one per thread that needs Sockets. So this instance as a shared object used by many threads will need to be synchronized if it is not already thread-safe per se. But all you do with a SocketFactory is ask it for sockets. What issues do you think you'll face with multi-threaded requests for new instances of something? Just because you've got multi-threaded code, doesn't mean everything you use has to be synchronized.I know, but since I don't know what the factory-implementation actually does creating those instances I think it is always worth asking, if I have to synchronize even if it may be true that the design of (the) factory-implementation(s) is in fact thread-safe, which no one until now could tell me for sure.

  • Connection Factory: Should it be made thread-safe?

    Hi,
    I have a web app - running on Tomcat 6, and Struts 1.3.
    It uses DAO for communication between the business logic classes and the Database. The database connections are retrieved from a connection pool managed by Tomcat. There is a ConnectionFactory object - a singleton - that each DAO requests a connection from. The question is, should the method ConnectionFactory.getConnection() be synchronized? If it is no, is it possible for two DAO's to get the same DB Connection from it?
    Thanks.

    there is no need to make it thread safe bacause it is alredy managed by uising cnnection pooling.yes according to your requirement you can configure pool size in tomcat and all the server like glassfish.............

Maybe you are looking for

  • HP slate 21 - no SkyGo in full screen after 4.4.2 update

    Hi there, I updated my HP slate 21 (non pro) to Android 4.4.2 this morning but it has unfortunately resulted in SkyGo not displaying correctly - only the centre 3rd of the screen is displayed (the rest being 'chopped off'). I've tried disabling the n

  • Using Microsoft Outlook to receive a report from ABAP...

    Guys may you please have a look at this coding of myne, i want to send a report as an e-mail(my outlook inbox) but when i execute it nothing is happening if there is any configuration that has to be done please can anyone send me the steps to do that

  • Satellite A110-195 lan crashes

    Hi My satellite a110-195 crashes when i'm sending files to another lan computer. There's nothing wrowng with the other lan computer because i'm also testing it with an a100-906 and works fine. I've formated hard disk and reinstalled windows xp but th

  • Reader Extension Size.

    I have a form that without filtering it by Reader Extension weighs 1 MGB, and after filtering it and giving permissions to export archives and to communicate with Web services grows approximately to 3 MGB. This process is tripling the size of the fil

  • Spool output

    Hi experts, can any one of you help me out in resolving the issue regarding the spool output, right now iam generating a file in spool which has output for more than one page and the output has a blank line between the pages. now my requirement is to