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.

Similar Messages

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

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

  • Is the java 1.5 default SAXParser thread safe.

    I used the following code to create a parser and validate my xml data.
    But the following code is causing too many open file issue.
    After doing some analysis I understood that each object of parser is open the file "file://var/app/bea/files/wfinf/xmlschema/WorkflowDecisionResponse.xsd".
    So if I comment the setProperty method it will work fine.
    My question is this parser is thread safe so that I can create single instance of parser and can be shared by all my thread?
    If not can some body suggest a better idea to validate it.
    public static boolean validate(String XMLData){
         SAXParserFactory factory = SAXParserFactory.newInstance();
         factory.setNamespaceAware(true);
         factory.setValidating(true);
         SAXParser parser = factory.newSAXParser();
         parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
         parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", "file://var/app/bea/files/wfinf/xmlschema/WorkflowDecisionResponse.xsd");
           try{
              parser.parse(new InputSource(new StringReader(XMLData)), new DummyHandlerImpl());
           }catch(Exception e) {
               return false;
           return true;
    }

    Hi There,
    I found this thread of yours with no reply from anybody.
    I'm also facing a similar issue. Did you found a solution to this.
    If yes please share.
    Regards,
    Mayank

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

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

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

  • How to know whether a method is thread-safe through the java-doc?

    In some book, it says that SAXParserFactory.newSAXParser() is thread-safe,but in the java-doc,it doesn't say that.
    newSAXParser
    public abstract SAXParser newSAXParser()
    throws ParserConfigurationException,
    SAXExceptionCreates a new instance of a SAXParser using the currently configured factory parameters.
    Returns:
    A new instance of a SAXParser.
    Throws:
    ParserConfigurationException - if a parser cannot be created which satisfies the requested configuration.
    SAXException - for SAX errors.
    I want to know, how to know whether a method is thread-safe?

    System.out is a PrintStream object. None of the methods there use the synchronized modifier, but if you look in the source code, you will find out it is thread-safe, because it will use synchronized blocks whenever it writes some text.
    The source code is in the src.jar file which you can extract.
    I didn't find any comments about that PrintStream is thread-safe in the API.

  • Are methods in the Graphics class Thread Safe

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

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

  • The get() of Vector class, is it thread safe??

    Hi all:
    the get() of Vector class, is it thread safe?? I looked into the API, but no info is available, so any help is appreciated

    You just have to look out when you perform two or more methods on the Vector in sucession. Then it's better to lock on the vector itself. If you for instance access the vector to query whether the size is greater than zero and immediately remove an item while another thread is removing elements from the same vector, you might get a dirty read and call get() on the vector while there are no elements left.

  • Is the isReachable() thread safe ? How to approach it ?

    I've created a ping class which uses InetAddress.isReachable().
    I have 100 devices, with 100 threads which are using the ping object instances simultaneously.
    When one device is not reachable ( it doesn't responde), the next 5 o 10 ping test fail as well.
    I've read that isReachable is not thread safe, is this true ?
    This is the code that performes the ping.
    final long start = System.nanoTime();
    if (InetAddress.getByName(sIp).isReachable(5000)) {
    result=(System.nanoTime() - start) / 1000 / 1000;
    } else {
    result=-1;
    Thanks for your help.

    I am not sure measuring the time in seconds will be very useful unless you are trying to detect very slow response times.
    Do you investigate using broadcast pings i.e. it pings every box at once.
    Why do you have such along timeout?
    Even testing a box on the other side of the world on a decent WAN should be less than 400 ms.
    What do you mean by the next 5 to 10? Do you mean in the same thread or between theads or is it that the boxes that timeout all have the same timeout so they fail at the same time?

  • Is the standard C++ library provided in Solaris 9 thread-safe?

    Hi,
    I cannot find any documentation anywhere that says that the standard C++ library in Solaris 9 (provided by Rogue Wave) is thread safe.
    I have seen evidence that makes me think it is not - however, I was wondering if anyone could provide any insight. If they are not, where could I obtain the libraries that are thread safe?
    The libraries of interest are:
    /lib/sparcv9/libCstd.so.1 &
    /lib/sparcv9/libCrun.so.1
    Thankyou in advance.

    Whether the library is thread safe depends on what you mean by thread safety. Except for the 8 standard iostream objects (std::cin, std::cout, etc.), simultaneous accesses from multiple threads to all objects of standard library types must be synchronized by the user. E.g., it's not safe to read or write the same container object (e.g., std::vector, or std::string) from multiple threads at the same time. The C++ localization library imposes some additional restrictions because of its interactions with the global C locale.

  • Is the Sun JNDI LDAP provider thread safe?

    Hi,
    The JNDI documentation states that the Context implementation is not required to be thread safe although some providers provide thread safety. My question is whether the Sun JNDI LDAP provider is thread safe or do we have to synchronize on the Context instance?
    Thanks

    Read this: http://java.sun.com/j2se/1.3/docs/api/javax/naming/Context.html
    The answer, I think is no you need to synchronize accesses yourself. If you're using it from a servlet container, this should be OK, since each request is on a separate thread.

  • If can think the thread safe variable as another lock method

    Hello,
    Assuming that there are two threads, using a thread safe variable as a signal condition. When the 1st thread calling the GetPointerToVarName() to do something, at the "same time", the 2nd thread need to call  GetPointerToVarName() to modify something, I'd like to know if the 2nd thread can continue the work until the 1st thread call the ReleasePointerToVarName()?
    David

    Thread safe variables can only be accessed by one thread at a time, so while the first one is holding the pointer, the second one waits until the pointer is released.
    This is more rigid than using thread locks, in that a thread could call CmtTryToGetLock remaining free to run even if the lock cannot be acquired (supposing running without the locked object makes sense).
    But it is not clear to me from your question whether you actually want thread safe variable functions to lock or are afraid they will do so...
    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?

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

  • Are the APIs of java.swing.Timer thread-safe?

    As the title.

    They are safe for use with the event thread, as the actionPerformed method is invoked on the event thread,
    so you can make UI changes from your actionPerformed without fear.
    That is their only thread-related-ness, so other than that, I would think they are not thread safe in general.
    : jay

Maybe you are looking for