Is ThreadPoolExecutor.execute(Runnable) thread-safe?

Is ThreadPoolExecutor.execute(Runnable) thread-safe, i.e. is it safe
to invoke this method from multiple threads without making any
special arrangements to ensure that not more than one thread is
in the execute() method of the ThreadPoolExecutor object at the same time
(such as synchronizing on the ThreadPoolExecutor object)?
I can find nothing in the Java 6 documentation to say it is thread-safe
(Executor, ExecutorService, ThreadPoolExecutor and package documentation).
Note that I am not asking anything about the actual execution of the Runnables.
I am asking about the act of inserting the Runnables into the thread pool.

Thanks to everyone who replied.
The three example implementations in the interface documentation for Executor, including the one where the Runnable is executed by the invoking thread, are thread-safe but only the last one needs to do anything special (namely make the execute(...) method synchronized) to be thread-safe. It is not clear whether the thread-safety of the first two implementations is conscious or accidental. Even if conscious that would not imply that it is necessary.
I think the published documentation (unless I've missed something) is deficient. The method would not be useless if not thread-safe. I don't think thread-safety is a safe default assumption. I think a package that supports concurrent programming should be clear on where it is thread-safe.
I've had a quick look at the source code in the 1.6 JDK implementation. It makes a serious and plausible effort to be thread-safe. It was written by Doug Lea.
I'm going to assume the method is thread-safe, based on looking at the source code.

Similar Messages

  • Is the ThreadpoolExecutor thread safe?

    Is the ThreadpoolExecutor thread safe? Is it safe to use a ThreadpoolExecutor from a multiple thread contexts?

    If the API documentation says it's thread-safe, then it is. Otherwise you must assume it is not.

  • Can I execute a thread JPanel?

    I want my Jpanel to do a bouncing ball. So I decided to use a thread to update the coordinates regularly. How do I set the panel to visible and at the same time run run()? As you will see, it doesn't work (Code for drawing I haven't placed yet. Instead I placed System.out.println("hello"); to see if it runs):
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.Graphics;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    public class bouncingBall extends JPanel implements Runnable
         private int balls;
         private int ballCount;
         public bouncingBall()
              setSize(500,500);
              addMouseListener(
                   new MouseAdapter()
                        public void mouseClicked(MouseEvent e)
                        public void mousePressed(MouseEvent e)
                        public void mouseReleased(MouseEvent e)
              ExecutorService threadExecutor = Executors.newFixedThreadPool( 1 );
              threadExecutor.execute( Thread.currentThread() );
         public void run()
              while(true)
                   System.out.println("Hello");     
         public void paintComponent(Graphics g)
         public static void main(String args[])
              JFrame cage = new JFrame("Bouncing Balls");
              bouncingBall app = new bouncingBall();
              cage.setSize(app.getSize());
              cage.add(app);
              cage.setVisible(true);
         }

    A JPanel already runs within its own thread... kind
    of.
    Swing usually works with two threads: one that wraps
    up all the displaying objects (this is the one you
    create) and another one (which you have no access
    to), which takes care of all the event handling and
    rendering.
    (Ironically, I said this way to often in the last few
    days:) Avoid multithreading in Swing/AWT! If you need
    anything time based, use the swing timer. If you
    still need other threads, make sure that they don't
    contain any Swing/AWT components, but just update any
    status.
    DON'T !! try to split up your displaying items onto
    several threads! This might cause unpredictable
    lockdowns!What about this new paradigm I'm reading about in the latest Swing books that says there is a flaw in the traditional way of creating a JFrame, e.g.
    JFrame aWindow = new JFrame("title");
    aWindow.setVisible(true);that makes them not thread safe? The new model for creating JFrames says you need to add them to the event queue. That seems to belie your statement that we don't have access to the "other thread' that handles events.
    Actually, below is a Hello World example of the new method for creating a JFrame that I found in the java docs(ugly!). It involves two steps:
    1) Create the JFrame inside a method
    2) Attach the method to the event dispatching thread
    import javax.swing.*;       
    public class HelloWorldSwing {
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("HelloWorldSwing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Add the ubiquitous "Hello World" label.
            JLabel label = new JLabel("Hello World");
            frame.getContentPane().add(label);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }http://java.sun.com/docs/books/tutorial/uiswing/learn/example1.html
    If you still need other threads, make sure that
    they don't contain any Swing/AWT components,
    but just update any status.Can you pass a Swing Component reference to the thread's constructor and call repaint() from inside the thread?

  • Is Executor thread-safe

    Hello,
    Suppose you have an Executor to execute tasks (one of the standard implementations provided by the JDK).
    Is there any risk if you have multiple threads that use the executor to submit or execute tasks?.
    In other words: Is Executor thread-safe?
    I'm not talking about the working threads that execute the tasks.
    I'm talking about the threads that send the tasks to execution.
    Thank you.

    JoseLuis wrote:
    can you please tell me where can I find that kind of facts, because I could not find it in the javadoc.Well, it isn't a requirement for ExecutorServices, but it how the implementations provided by the java.util.concurrent package operate. That fact is stated in the API for ThreadPoolExecutor in several places:
    In the class description:
    Queuing
        Any BlockingQueue may be used to transfer and hold submitted tasks.Then, all the Constructors that take work queues only take BlockingQueues, and the getQueue() method returns a BlockingQueue.
    Finally, there are only 2 implementations of the ExecutorService provided, ThreadPoolExecutor, and ScheduledThreadPoolExecutor, which subclasses ExecutorService (and does not indicate different rules for Queues).
    >
    if you can tell me about a book or official document it would be great.
    thanx again

  • Is thread safe the norm?

    In the Java tutorial - Creating a GUI with JFC/Swing trail - the main methods consist of some code to make the application "thread safe" by scheduleing the job for the event-dispatching thread. I can only guess at the true meaning of this. Other Java books do not take this approach. I actually don't remember the tutoral saying that last time I looked at it (some time ago). I have been using the main method to set up my frame and add to it my GUI class. This seems to always work for me. What do other forum members do and recommend?

    Whenever you write GUI code in Java, you (1) must ensure that changes to GUI objects only happen on the event thread, and (2) should schedule long-running operations on another thread.
    The first rule is simple: GUI objects are not synchronized, and if you try to change one from outside the event thread it may have inconsistent internal state when the GUI thread tries to access it. "Change" may be as simple as setting the contents of a JTextfield, or as complex as rebuilding the model for a JTable.
    If you simply create and display a JFrame from main(), you're generally safe. Until you call setVisible(true), the JFrame isn't actually accessed by the GUI thread. Once you call setVisible(true), the GUI thread takes control of the frame. If that's the last step in your main(), you're OK; for most complex programs, however, that's not the last step. As a result, it's a good habit to build up your frame from within a Runnable that you put on the event thread via SwingUtilities.invokeLater().
    (This last recommendation is a new part of the tutorial. I think it was added as-of 1.5, when show() was deprecated in favor of setVisible(true)).
    As long as your program simply reacts to events generated by your GUI programs, you don't have to worry about any other threads, since those events are distributed on the event thread. However, most real programs interact with the outside world: they read files, make database calls, access app-servers, or whatever. These calls all block the thread that's executing them; if you call them from the event thread, this will freeze your UI.
    So, rule #2 says to execute those potentially blocking operations on another thread (it's a suggestion, rather than an absolute, because you're free to do everything on the event thread as long as you don't mind blocked apps -- most people do mind, however).
    Of course, once you start something running on a separate thread, you need to get the results back to the event thread, which is where rule #1 (which is mandatory) comes in.
    Sun provides the SwingWorker class to help you with this; you can find it linked from the tutorial. Personally, I don't like it (in part because it spins up a new thread for each operation); instead, I use an "AsynchronousOperation" class that I pass to a threadpool for execution.

  • Can use the same thread safe variable in the different processes?

    Hello,
    Can  use the same thread safe variable in the different processes?  my application has a log file used to record some event, the log file will be accessed by the different process, is there any synchronous method to access the log file with CVI ?
    David

    Limiting concurrent access to shared resources can be better obtained by using locks: once created, the lock can be get by one requester at a time by calling CmtGetLock, the other being blocked in the same call until the lock is free. If you do not want to lock a process you can use CmtTryToGtLock instead.
    Don't forget to discard locks when you have finished using them or at program end.
    Alternatively you can PostDeferredCall a unique function (executed in the main thread) to write the log passing the apprpriate data to it.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • Thread-safe design pattern for encapsulating Collections?

    Hi,
    This must be a common problem, but I just can't get my head around it.
    Bascially I'm reading in data from a process, and creating/updating data structuers from this data. I've got a whloe bunch of APTProperty objects (each with a name/value) stored in a sychronized HashMap encapsulated by a class called APTProperties. It has methods such as:
    addProperty(APTProperty) // puts to hashmap
    getProperty(String name) // retreives from hashmap
    I also want clients to be able to iterate through all the APTProperties, in a thread safe manner . ie. they aren't responsible for sychronizing on the Map before getting the iterator. (See Collections.synchronizedMap() API docs).
    Is there any way of doing this?
    Or should I just have a method called
    Iterator propertyIterator() which returns the corresponding iterator of the HashMap (but then I can't really make it thread safe).
    I'd rather not make the internal HashMap visible to calling clients, if possible, 'cause I don't want people tinkering with it, if you know what I mean.
    Hope this makes sense.
    Keith

    In that case, I think you need to provide your own locking mechanism.
    public class APTProperties {
    the add, get and remove methods call lock(), executes its own logic, then call unlock()
    //your locking mechanism
    private Thread owner; //dont need to be volatile due to synchronized access
    public synchronized void lock() {
    while(owner != null) {
    wait();
    th = Thread.currentThread();
    public synzhronized void unlock() {
    if(owner == currentThread()){
    owner = null;
    notifyAll();
    }else {
    throw new IllegalMonitorStateException("Thread: "+ Thread.currentThread() + "does not own the lock");
    Now you dont gain a lot from this code, since a client has to use it as
    objAPTProperties.lock();
    Iterator ite = objAPTProperties.propertyIterator();
    ... do whatever needed
    objAPTProperties.unlock();
    But if you know how the iterator will be used, you can make the client unaware of the locking mechanism. Lets say, your clients will always go upto the end thru the iterator. In that case, you can use a decorator iterator to handle the locking
    public class APTProperties {
    public Iterator getThreadSafePropertyIterator() {
    private class ThreadSafeIterator implements Iterator {
    private iterator itr;
    private boolean locked;
    private boolean doneIterating;
    public ThreadSafeIterator(Iterator itr){
    this.itr = itr;
    public boolean hasNext() {
    return doneIterating ? false : itr.hasNext();
    public Object next() {
    lockAsNecessary();
    Object obj = itr.next();
    unlockAsNecessary();
    return obj;
    public void remove() {
    lockAsNecessary();
    itr.remove();
    unlockAsNecessary();
    private void lockAsNecessary() {
    if(!locked) {
    lock();
    locked = true;
    private void unlcokAsNecessary() {
    if(!hasNext()) {
    unlock();
    doneIterating = true;
    }//APTProperties ends
    The code is right out of my head, so it may have some logic problem, but the basic idea should work.

  • 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

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

  • Thread Safe Issue with Servlet

    I saw the following statement in one of the J2EE compliant server documentations:
    "By default, servlets are not thread-safe. The methods in a single servlet instance are usually executed numerous times simultaneously (up to the available memory limit)."
    I'm quite concerned with this statement for the primary reason that (I'm trying to reason by reading it out loud) servlets are not going to be thread-safe especially when available memory hit really really low!! So, when the application is still having sufficient memory, we will not likely run into concurrency problems, i.e the happy scenario for a short period after server is started. BUT, good things don't last long.. Anyway, hope someone can explain to me with more insights. Thanks.

    Don't worry, memory occupation and thread safety are not related at all.
    In my opinion, the following is the meaning of the statement you quote.
    Since the servlet specification doesn't force any implementation to spawn a new servlet object upon each request (and this should be a real memory hit!), nor to synchronize calls to servlet methods, you should always code your servlet in a "stateless" fashion: you should be aware the same method on the same object could (and probably will) be called concurrently if multiple concurrent client requests are submitted.
    Hope I've been clear enough...

  • What does it mean to be "thread safe"?

    What does it mean to be "thread safe"?
    I am working with a team on a project here at work. Someone here suggested that we build all of our screens during the initialization of the application to save time later. During the use of the application, the screens would then be made visible or invisible.
    One of the objections to that idea was that the swing components (many of which we use) are not thread safe. Can anyone tell me what the relevance of that is?
    Thanks

    To understand why Swing is not thread safe you have to understand a little bit of history, and a little bit of how swing actually works. The history(short version) is that it is nearly impossible to make a GUI toolkit thread safe. X is thread safe(well, sorta) and it's a really big mess. So to keep things simple(and fast) Swing was developed with an event model. The swing components themselves are not thread safe, but if you always change them with an event on the event queue, you will never have a problem. Basically, there is a Thread always running with any GUI program. It's called the awt event handler. When ever an event happens, it goes on an event queue and the event handler picks them off one by one and tells the correct components about it. If you have code that you want to manipulate swing components, and you are not ON the awt thread(inside a listener trail) you must use this code.
    SwingUtilities.invokeLater( new Runnable() {
      public void run() {
        // code to manipulate swing component here
    });This method puts the defined runnable object on the event queue for the awt thread to deal with. This way changes to the components happen in order, in a thread safe way.

  • 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

  • HTTP request/response object not thread safe.

    According to the serlvet spec. Http Request/Response
    are not thread safe. Quoting from the Spec:
    " Implementations of the request and response objects are not guaranteed to be thread safe. This means that they should only be used within the scope of the request handling thread. References to the request and response objects must not be given to objects executing in other threads as the resulting behavior may be nondeterministic."
    This has prompt me to ask the following question.
    For Example I have a servlet which does the following
    request.setAttribute("myVar","Hello");
    The request and response is dispatched(using RequestDispatch.include(request,response)) to another
    servlet which retrieve this attribute i.e request.getAttribute("myVar");
    Is this safe?
    The Spec only said "The Container Provider must ensure that the dispatch of the request to a target
    servlet occurs in the same thread of the same VM as the original request." I take this meaning that the targeting servlet does not have to run in the same thread(only dispatch), otherwise it would be safe.

    To put it another way, you can only have onle thing working on a request at a time. For instance, the ServletContext is available to all servlets running on a server. If you tried to save a particular request to the ServletContext, it would potentially be available to many concurrently running servlets. They could all change whatever in it at the same time. Each servlet is in its own running thread. Hope that helps some.

  • JTextArea: Not thread safe

    I am working on a lobby system with a chat are using Networking, and recently I noticed that occasionally my JTextArea does not append the data I give it, even if I have a System.out.println() directly before which shows me what it is being passed, and it is being passed correct Strings, it is just not appending them.
        Thread updateText = new Thread() {
            public void run()
                for(;;)
                    try {
                        for (int x = 0; x < texts.size(); x++) {
                            System.out.println("ADDED: "+texts.get(x));
                            textArea.append(texts.get(x));
                        texts.clear();
                        scrollToEnd(textArea);
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        };I have an ArrayList texts, which keeps track of what is being typed into the Chat Area. This code displays correctly What I want it to, i.e. "ADDED: Hello guys, etc.", however the JTextArea does not update. Is there something to make the JTextArea thread-safe because I have heard on several sites that JTextAreas are not thread-safe.
    Any help would be greatly appreciated.

    I changed my code to this: and now it does not work at all, i.e., the JTextArea never updates:
        Thread updateText = new Thread() {
            public void run()
                for(;;)
                    try {
                        SwingUtilities.invokeAndWait(update);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (InvocationTargetException ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        Runnable update = new Runnable() {
            public void run()
                try {
                    texts.clear();
                    scrollToEnd(textArea);
                    for (int x = 0; x < texts.size(); x++) {
                        System.out.println("ADDED: " + texts.get(x));
                        textArea.append(texts.get(x));
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        };

  • 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

  • Having a problem streaming video, but not audio, from Amazon Prime through Apple TV.

    I get the audio fine, but no picture when using AirPlay for Amazon Instant Video from iPhone or iPad. It worked before. I have AirPort Extreme and great connectivity.

  • Scheduling a job to clear line items

    Dear All, I am receiving lockboxes , I want to know how to schedule a job so that the items in lockboxes gets applied to open customer line items. best regds Subha

  • Generate file on Server

    I have a JSP and i would like to create file localy and remotly : <%@ page language="java" %> <%@ page import="java.io.*" %> <%! String dcr = request.getParameter("dcr"); String contentTplPath = "";           int DebChaine = dcr.indexOf("Dev_Contrib"

  • ASE  service Syabase SQLServer_"SID" don't start

    Hi, We have shutdown the ASE Server, after that we tried to start it insuccefully. with the msg "The Sybase SQLServer_"SID" service on "host" started and then stopeped.Somme services stop automatically are no in use by other services or programs" We

  • Mac Book Flash web page error message

    Error Message: 'Could not open one or more scenes probably because of low memory' Any ideas? This is a soul cushing impasse in a time sensitive college project. Can anyone help?