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.

Similar Messages

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

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

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

  • 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

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

  • 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

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

  • Is the Illustrator SDK thread-safe?

    After searching this forum and the Illustrator SDK documentation, I can't find any references to a discussion about threading issues using the Illustrator C++ SDK. There is only a reference in some header files as to whether menu text is threaded, without any explanation.
    I take this to mean that probably the Illustrator SDK is not "thread-safe" (i.e., it is not safe to make API calls from arbitrary threads; you should only call the API from the thread that calls into your plug-in). Does anyone know this to be the case, or not?
    If it is the case, the normal way I'd write a plug-in to respond to requests from other applications for drawing services would be through a mutex-protected queue. In other words, when Illustrator calls the plug-in at application startup time, the plug-in could set up a mutually exclusive lock (a mutex), start a thread that could respond to requests from other applications, and request periodic idle processing time from the application. When such a request arrived from another application at an arbitrary time, the thread could respond by locking the queue, adding a request to the queue for drawing services in some format that the plug-in would define, and unlocking the queue. The next time the application called the plugin with an idle event, the queue could be locked, pulled from, and unlocked. Whatever request had been pulled could then be serviced with Illustrator API calls. Does anyone know whether that is a workable strategy for Illustrator?
    I assume it probably is, because that seems to be the way the ScriptingSupport.aip plug-in works. I did a simple test with three instances of a Visual Basic generated EXE file. All three were able to make overlapping requests to Illustrator, and each request was worked upon in turn, with intermediate results from each request arriving in turn. This was a simple test to add some "Hello, World" text and export some jpegs,
    repeatedly.
    Any advice would be greatly appreciated!
    Glenn Picher
    Dirigo Multimedia, Inc.
    [email protected]

    Zac Lam wrote:
    The Memory Suite does pull from a specific memory pool that is set based on the user-specified Memory settings in the Preferences.  If you use standard OS calls, then you could end up allocating memory beyond the user-specified settings, whereas using the Memory Suite will help you stick to the Memory settings in the Preferences.
    When you get back NULL when allocating memory, are you hitting the upper boundaries of your memory usage?  Are you getting any error code returned from the function calls themselves?
    I am not hitting the upper memory bounds - I have several customers that have 10's of Gb free.
    There is no error return code from the ->NewPtr() call.
         PrMemoryPtr (*NewPtr)(csSDK_uint32 byteCount);
    A NULL pointer is how you detect a problem.
    Note that changing the size of the ->ReserveMemory() doesn't seem to make any difference as to whether you'll get a memory ptr or NULL back.
    btw my NewPtr size is either
         W x H x sizeof(PrPixelFormat_YUVA4444_32f)
         W x H x sizeof(PrPixelFormat_YUVA4444_8u)
    and happens concurrently on #cpu's threads (eg 16 to 32 instances at once is pretty common).
    The more processing power that the nVidia card has seems to make it fall over faster.
    eg I don't see it at all on a GTS 250 but do on a GTX 480, Quadro 4000 & 5000 and GTX 660
    I think there is a threading issue and an issue with the Memory Suite's pool and how it interacts with the CUDA memory pool. - note that CUDA sets RESERVED (aka locked) memory which can easily cause a fragmenting problem if you're not using the OS memory handler.

  • Is the Memory Suite thread safe?

    Hi all,
    Is the memory suite thread safe (at least when used from the Exporter context)?
    I ask because I have many threads getting and freeing memory and I've found that I get back null sometimes. This, I suspect, is the problem that's all the talk in the user forum with CS6 crashing with CUDA enabled. I'm starting to suspect that there is a memory management problem when there is also a lot of memory allocation and freeing going on by the CUDA driver. It seems that the faster the nVidia card the more likely it is to crash. That would suggest the CUDA driver (ie the code that manages the scheduling of the CUDA kernels) is in some way coupled to the memory use by Adobe or by Windows alloc|free too.
    I replaced the memory functions with _aligned_malloc|free and it seems far more reliable. Maybe it's because the OS malloc|free are thread safe or maybe it's because it's pulling from a different pool of memory (vs the Memory Suite's pool or the CUDA pool)
    comments?
    Edward

    Zac Lam wrote:
    The Memory Suite does pull from a specific memory pool that is set based on the user-specified Memory settings in the Preferences.  If you use standard OS calls, then you could end up allocating memory beyond the user-specified settings, whereas using the Memory Suite will help you stick to the Memory settings in the Preferences.
    When you get back NULL when allocating memory, are you hitting the upper boundaries of your memory usage?  Are you getting any error code returned from the function calls themselves?
    I am not hitting the upper memory bounds - I have several customers that have 10's of Gb free.
    There is no error return code from the ->NewPtr() call.
         PrMemoryPtr (*NewPtr)(csSDK_uint32 byteCount);
    A NULL pointer is how you detect a problem.
    Note that changing the size of the ->ReserveMemory() doesn't seem to make any difference as to whether you'll get a memory ptr or NULL back.
    btw my NewPtr size is either
         W x H x sizeof(PrPixelFormat_YUVA4444_32f)
         W x H x sizeof(PrPixelFormat_YUVA4444_8u)
    and happens concurrently on #cpu's threads (eg 16 to 32 instances at once is pretty common).
    The more processing power that the nVidia card has seems to make it fall over faster.
    eg I don't see it at all on a GTS 250 but do on a GTX 480, Quadro 4000 & 5000 and GTX 660
    I think there is a threading issue and an issue with the Memory Suite's pool and how it interacts with the CUDA memory pool. - note that CUDA sets RESERVED (aka locked) memory which can easily cause a fragmenting problem if you're not using the OS memory handler.

Maybe you are looking for

  • New hard drive for mac, how do i move all the old over?

    My partitioned HD on my mac now has too small a partition for the OS 10.3 to run stably. As I believe it is impossible to enlarge the partition OS runs on without erasing the whole HD first I want to put a larger HD into the mac. How can I move every

  • Problem with GHR.PLL

    Hi, I have all PLL in my server except GHR.PLL in my linux server. But I found GHR.PLX Only. Can anybody help how to overcome this and open template form in my client PC. Thanks

  • What else can I use beside Compressor?!

    Compressor is now useless to me. Unknown time remaining will not fix. What else can I use? Anyone know?

  • TS1382 IPOD Classic "clicking" sound - computer won't recognize it now

    IPOD Classic. Was transferring files from iTunes and started hearing a "clicking" sound from iPod. Tried to disconnect. Computer said safe to do so but iPod screen never said ok. iTunes and computer won't recognize it now.Is clicking a hard drive fai

  • Size of applet in Internet Explorer

    Thanx in advance When i run a form through 9iDS it shows the form not in actual size in applet window. How can i make changing in applet size.