Are queries thread-safe?  (read on)

I have a singleton class in a multithreaded environment. This singleton has a single private instance for each database query being used.
For parameterized queries, the argument vector is passed into the session.executeQuery() call when a thread executes a query.
My question is: Do the DatabaseQuery (subclasses) objects change state once they are "set up", or does the session simply READ what it needs from a query, and bind any parameters outside of the query object?
I would like to avoid having to instantiate a query object every single time the query needs to be executed. Reuse would save a lot of performance headaches.
Thanks,
Bret

Not only need you only instantiate a query once, but after you execute it for the first time TopLink doesn't need to prepare it again either.
That is the benefit to using parameters. Each time the SQL is the same but the query is different.

Similar Messages

  • Are queries thread-safe ? (continued)

    Hi
    In a previous thread on this topic, it was said that a query can be reused, and why it was good on performance. But a reusable object is not necessarily thread-safe.
    So I ask again. Are queries thread-safe ?
    What about Expressions ?
    Thanks
    JCG

    Yes, they're thread safe, both expressions and Queries. TopLink makes copies of whatever parts of the Query/Expression are needed to be changes in parallel.
    - Don

  • Are servlets thread safe??

    Are servlets thread safe?? if not, then how to make them thread safe.

    Hi,
    servlets aren't thread-safe; you can make them thread-safe by implementing the interface javax.servlet.SingleThreadModel
    From the javadoc:
    public interface SingleThreadModel
    Ensures that servlets handle only one request at a time. This interface has no methods.
    If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet's service method. The servlet container can make this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of servlet instances and dispatching each new request to a free servlet.
    If a servlet implements this interface, the servlet will be thread safe. However, this interface does not prevent synchronization problems that result from servlets accessing shared resources such as static class variables or classes outside the scope of the servlet.

  • Are Queues thread safe

    Hi all,
    Are Queues thread safe i.e. are enqueue, dequeue etc atomic?
    I'm looking to use Queues to transfer object states between concurrent loops, but am concerned whether I need to protect access via a semaphore.
    Thanks
    Phill
    Solved!
    Go to Solution.

    Hi all,
    I've been discussing transfering the state of an object between concurrent loops here and was hoping to use a single element queue.
    I'm still a little worried about a context switch while I'm updating the status of the object in the area highlighted.
    Would I still need a semaphore lock to ensure the data integrity of the queue between the flush and enqueue in case the data loop sneaks in and tries to read the queue?

  • Are HttpSessions thread-safe?

    When multiple users submit a request on the same servlet, they will each access a different HttpSession, which is thread-safe.
    However, it seems possible that a single user can issue multiple requests at around the same time (ie. multiple browser windows or simply clicking the same link twice) for which the browser would provide the same session tracking info (cookie etc.). In this case, is it possible that the two requests would be handled in two separate threads, but access the same HttpSession simultaneously?
    If this is possible, what are common methods for protecting against it?
    (eg. synchronize on the session object per page?)

    Normally the container assigns each received request to a thread and executes it. If two requests are sent by a browser, then it is up to the browser to disregard the response to the first request (using sequence numbers). I have examined the Servlet 2.3 specification and can't find any mention that the servlet container is required to detect several requests for the same page from the same client while the earlier request(s) are still executing, and to terminate the earlier request(s) first! Of course this is an area where different brands of servlet container could behave differently, but to terminate a thread's execution without warning seems questionable (not to mention non-compliant with the standards). The discussion you refer to seems a little strange, and it didn't really conclude on solid ground...
    The JSP test page I used is as follows.
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
    <%@ page info="TEST" %>
    <%! static int x = 0; %>
    <%-- synchronized (session) { --%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>TEST</title>
    </head>
    <body>
    <%
    String x1 = (String) session.getAttribute("x");
    if (x1 == null)
    x1 = "" + x++;
    else
    x1 += "(" + x++ + ")";
    session.setAttribute("x", x1);
    %>
    Initial value is "<%= x1 %>".
    <br>
    <%
    Thread.currentThread().sleep(10000); // Make it easier to reproduce the race condition
    String x2 = (String) session.getAttribute("x");
    x2 += "[" + x++ + "]";
    session.setAttribute("x", x2);
    %>
    Final value is "<%= x2 %>".
    </body>
    </html>
    <%-- } --%> // synchronized (session)
    When I submit the first request and resend the request a couple of seconds later, the browser (NS7/IE6) shows only the result of the second request, and takes about 10 seconds (the two requests are executing concurrently).
    Initial value is "(0)(1)".
    Final value is "(0)(1)[2][3]".
    When I do the same thing with the synchronization enabled, I get the following result, and it take around 20 seconds for the second page to arrive (since the two requests are serialised by the servlet).
    Initial value is "(0)[1](2)".
    Final value is "(0)[1](2)[3]".
    /Cheers, Ross.

  • Are clusters thread safe?

    If one thread assigns a new value to a cluster while another thread reads it via a local variable, could the reading thread get part of the old value and part of the new value? Or are cluster operations atomic?
    Does this behavior- whatever it is- apply to cRIO FPGA and controller platforms as well as desktop systems? Does it apply in multiprocessor systems?
    Thanks,
    -Ron

    tst wrote:
    When you have a UI control, writing to it or reading to it will be done in one atomic operation, so reading from the control you won't get half of the old values and half of the new values.
    However, as Jeff mentioned, this is a good way to create race condition and is usually a sign of trying to use LabVIEW as you would C. There are better ways to handle data.
    Here's a made-up example. I'm not interested in a specific solution to this problem; I'm interested in the general question of clusters' atomicity in multithreaded or multiprocessing environments.
    Suppose I have a thread that monitors a serial GPS unit and derives two values: a floating point time correction, in seconds (GPS time - platform time), and a boolean indicating whether the GPS unit is providing a good signal, i.e. whether the time correction is valid. This thread stores these values in a cluster using Bundle by Name, so in theory both values are stored at the same time. This thread writes to the cluster, but does not read it.
    The other threads (or however LabVIEW divides up the processing) read this cluster using Unbundle by Name, so in theory each thread reads both values at the same time. These other threads do not write to the cluster. It is not critical that all the threads read the same values from the cluster, but it is critical that each thread reads the boolean that agrees with the float it reads, i.e. that the thread doesn't read an invalid time correction and think it's valid.
    It sounds like you're saying that this does in fact work, even if the threads are running on different cores. Is my understanding correct? I realize I can play it safe and use a semaphore. I'm just wondering if I need to.

  • Are static nested classes thread-safe?

    There doesn't seem to be any definitive answer to this. Given the following code, is it thread-safe?
    public class SomeMultiThreadedWebController {
    public HttpServletResponse someMethodToExecuteViaWebRequest(HttpServletRequest request) {
        simpleQueryBuilder("SELECT...").addParameter("asdf","asdf").createQuery(EMF.getEntityManager()).executeUpdate();
    protected static class SimpleQueryBuilder {
             private String queryString;
             private Map<String, Object> params = new HashMap<String, Object>();
             public SimpleQueryBuilder(String queryString) {
                  this.queryString = queryString;
             public SimpleQueryBuilder addParameter(String name, Object value) {
                  params.put(name, value);
                  return this;
             public Query createQuery(EntityManager em) {
                  Query query = em.createQuery(queryString);
                  for (Entry<String, Object> entry : params.entrySet()) {
                       query.setParameter(entry.getKey(), entry.getValue());
                  return query;
        public static SimpleQueryBuilder simpleQueryBuilder(String queryString) {
             return new SimpleQueryBuilder(queryString);
    }Forget whether or not someone would do this, as this is just an example. I'm really trying to get at whether or not the instance variables inside the static nested class are thread-safe. Thanks for any responses.

    Hello,
    I believe you understand what you're talking about, but you state it in a way that is very confusing for others.
    Let me correct this (essentially, incorrect uses of the terminology):
    I agree that thread-safe or not is for an operation, for a member, it has some sort of contextual confusion.
    Member has a much broader meaning in the [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.4] . Even "class member" applies to both an attribute, a method, or an inner class or interface.
    I think you mean "member variable" of a class (aka "attribute" or "field"). By the way, static or not is irrelevant to the rest of the discussion.
    For an operation or a member, if there's only one thread could access it atomically in one moment, we could call it thread-safe.Mmm. I was tempted to say yes (I'm reluctant to commit myself). With an emphasis on "_The encapsulating class_ makes this member's usage thread-safe".
    Still, just synchronizing each operation on a member is not enough to make all usages "thread-safe":
    Consider a java.util.Vector: each add/get is synchronized, so it is atomic, fine.
    However if one thread adds several values, let's say 3, one by one, to a vector that initially contains 0 values, and another thread reads the vector's size() (another properly synchronized method), the reader thread may witness a size anywhere among 0, 1, 2, 3, which, depending on the business logic, may be a severely inconsistent state.
    The client code would have to make extra work (e.g. synchronizing on the vector's reference before the 3 adds) to guarantee that the usage is thread-safe.
    Thus any synchronized method(With the limit stated above)
    or immutable member (like primitive type) are thread-safe.
    Additionally for a member, if it's immutable, then it's thread-safe. You mean, immutable primitive type, or immutable object. As stated previously, an immutable reference to a mutable object isn't thread-safe.
    a static final HashMap still have thread-safe issue in practice because it's not a primitive.The underlined part is incorrect. A primitive may have thread-safety issues (unless it's immutable), and an object may not have such issues, depending on a number of factors.
    The put, get methods, which will be invoked probably, are not thread-safe although the reference to map is.Yes. And even if the put/get methods were synchronized, the client code could see consistency issues in a concurrent scenario, as demonstrated above.
    Additional considerations:
    1) read/write of primitive types are not necessarily atomic: section [ §17.7 of the JLS|http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.7] explicitly states that writing a long or double value (2 32-bits words) may not be atomic, and may be subject to consistency issues in a concurrent scenario.
    2) The Java Memory Model explicitly allows non-synchronized operations on non-volatile fields to be implemented in a "thread-unsafe" way by the JVM. Leading way to a lot of unintuitive problems such as the "Double-Checked Locking idiom is broken". Don't make clever guess on code execution path unless you properly synchronize access to variables across threads.
    Edited by: jduprez on Mar 4, 2010 9:53 AM

  • Are page flows thread safe?

    Are pageflows thread safe? As in, can I have object level variables that
    don't need to be synchronized?
    Thanks

    Yes page flows are thread safe.

  • Need thread safe way to access read-only objects

    I have been working on a lot of projects and all the developers agree that they want thread safe code when called by many threads. It's rare developers are making statement like: "Data are not corrupted often so don't bother" or "It's not thread safe, but that will not often create issues".
    In TopLink client session itself is thread safe but not the persistent object themselves. Via client session, if you want thread safe access you need to put a lock on CacheKey and it's not a public/supported API. So the only thread safe access is via unit of work.
    We would like fast access to objects. We have a batch process that just need read-only access to objects. We need to read via unit of work to get thread safe access. But we just need the clone when we read via unit of work, we don't need the backup for change detection.
    However, TopLink doesn't have a mean to do that.
    Please push implementation of Bug5998333[WANT THREAD SAFE AND CORRECT ISOLATION WITH OBJECTS FROM ADDREADONLYCLASS]
    In Hibernate, by design, all access are always thread safe. Accessing read-only object just create one copy (a clone), no backup needed.
    Oracle claims that TopLink is fast. I wonder if their performance testing code is thread safe, so access objects via unit of work or they take the shortcut of accessing objects from client session. Also, reliable performance comparison should use conform in unit of work.

    As you stated the UnitOfWork offers you your desired functionality, you would just like an improvement in performance.
    In TopLink 10.1.3 (or 11g preview) you have a few options:
    - Use a UnitOfWork an live with the slight overhead of the back copies (it will only add 5-30 % overhead to your processing)
    - Instead use an isolated client session, this will not require any cloning or backup clones, but also does not allow any caching.
    - Use change tracking, TopLink added attribute-level change tracking in 10.1.3, when used the UnitOfWork does not create backup clones. In 10.1.3 it was mainly used for CMP and requires code generation, but you could implement or weave the code yourself. In TopLink 11g, change tracking is weaved by default with JPA and the weaver can also be used with POJO objects.
    I agree that having a feature to mark an object as transactionally read-only would be desirable, it seems like you have logged the enhancement. You could try escalting the enhancement through Oracle support, but since it is an enhancement and not a bug, it is probably beyond what support offers. You may wish to investigate services, or potentially join the open source Eclipse EclipseLink project which the next version of TopLink is being developed under and take part in the feature yourself.

  • Are the service(), doPost() and doGet() methods THREAD-SAFE?

    Please Let Me know If service(), doPost() and doGet() are Thread-safe. If they are not thread safe, How to make them thread-safe?

    Please Let Me know If service(), doPost() and doGet() are Thread-safe. They are not.
    If they are not thread safe, How to make them thread-safe?The best way is to avoid writing code that depends on a servlet's thread safety; i.e., no servlet instance variables - keep everything local to the method. Else, you'll want to learn about synchronization.
    [JavaWorld article - Write thread-safe servlets|http://www.javaworld.com/javaworld/jw-07-2004/jw-0712-threadsafe.html].
    ~

  • Are WLE libraries thread safe?

    Hi,
    Can we implement multiple threads in c CORBA Servers. Are C libraries thread safe? Can i use pthread to create threads in WLE CORBA C servers
    regards,
    Manoj PG

    JSPs/Servlets are not threadsafe in that one instance of the class is created to handle all requests.
    But only your class attributes are not thread-safe. Local variables are stored for each invocation of the service method, and are thread safe.
    Basically you have to declare all your variables inside a method, and if you call any java methods, pass parameters.
    <%!
      int myNumber;   // class attribute - shared among all calls to this servlet
    %>
    <%
      int myLocalNumber; // local variable to method.  will be threadsafe
    %>In short, yes this code is threadsafe. The key will be the same when you get back from doing your "stuff".
    The only problem would be if two people hit it fast enough to get the same time, and thus the same key.
    Cheers,
    evnafets

  • 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

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

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

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

  • Thread safe XSLT extension

    We have a servlet that gets called with a set of parameters. I want to set one of those parameters within my XSL extensions so that it is retrievable from the XSL code. Because the extensions are static and used by all XSL transforms, they are not thread safe. Static elements within the class are overwritten by whatever servlet thread last touched it. So my parameter may not be for the thread wanted, but some subsequent thread. How can I get around this without synchronization?

    Would you provide more details of how you define the extensions?

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

Maybe you are looking for

  • First Script: Need some basic skill help? Can you add an image with a click?

    Hello, Im working on a project were you can replace people heads in a photo. Its for a project so its not supposed to be perfect. So far heres what i think the best steps to take are, but im not sure how to take the first scripting steps. How can i a

  • Error when installing RAC on windows 2000

    Hi, I'm installing Oracle 9i(9.0.1.1.1 EE) RAC for the first time. It has been an interesting experience, with many bumps in the road. But now I'm stuck. I have installed the 9i EE software, but when I try to create a database ( using DBCA), I get an

  • Clamshell mode won't work? (MacBook + LG Monitor)

    Howdy! I've triple-checked the official doc on how to use Clamshell Mode, but I can't seem to get it to work. My MacBook is plugged in and fully charged, the display (LG W2052TG) is connected, as are my USB keyboard and mouse. Yet when I close the di

  • Has anyone found their lost Iphone with Icloud succefully?

    I recently had my Iphone stolen and my Icloud picked it up for a breif moment in front of someones house. I am from Illinois and it was stolen in Wisc. I had a friend go the house but it was a little old lady. Im pretty sure she did not live alone bu

  • How to query CLOB?

    One of the table column stores XML file as CLOB. Now, there is a requirement to retrieve the CLOB if one of the element matches within XML file. Please could someone suggest what is the best way to do that. Here is my table structure TABLEA COL1 COL2