RDBMS non-thread-safe issue

<snip>
This (as you probably know) is due to the fact that the code provided by
most of the DB vendors is not thread safe.
<snip>
Sean's comment, above, speaks to an issue that is causing some concern
within my (large - 180 projects in development) organisation.
May I please ask the forum if there are others out there who have an
understanding of / concern with this "problem"?
My perception (quite possibly flawed) of the "problem" is that the RDBMS
cannot multi-thread data access objects. So we find ourselves in a situation
where we can achieve scaleability in just about all other
performance-sensitive areas of a system's technical architecture (we're
using DCE -- but have found that Encina is not advisable except where there
is a true requirement for heterogeneous distributed 2 phase commit, which we
don't often see.....) but when we go to hit on the RDBMS, we go back to good
ole single-threading.
In certain circumstances, this shortfall of RDBMS technology -- I won't
mention any names, of course, but the initials are "Oracle" -- seems to be
hindering our achievement of a desired technical architecture.
Is this a "Pro*C / PL/SQL stored procedures" problem or is it something that
is in the RDBMSs' DNA?
How can we get around it?
Any comments?
Regards
Jon

Jon
I agree. But it is the best solution within the constraints of existing
technology. At least we don't use a process per client. 10 replicated
copies of a service could service the needs of 100 clients.
Eric
>
At 13:15 6/09/96 EST, you wrote:
Eric
Thanks for your response. Yep. I realise that the issue I've presented is
clearly not something that Forte causes or is responsible for in any way.
Forte can, as you've pointed out, actually help in this area. But I don't
think that getting Forte to spawn another instance of a data access server
is really the best solution. Ie, that's not what we tend to have in mind
when we think about "scaleability". The best solution is -- perhaps -- to
get the RDBMS people to thread-safe all code and libraries. I have pointedly
asked Oracle for a position on this -- and got the usual blank stare.
I also considered whether people might get upset at me for posting what is
clearly a non-Forte-specifc question in a Forte forum. But then I went ahead
and did it anyway. Justification being (assumption follows) that the kind of
people who hang out on the Forte forum may tend to be more
architecture-oriented than your run of the mill VB / SQL*Net / PL/SQL stored
procedures kinda guy/gal, and may be using or considering Forte (plug for
Forte follows) precisely because it clearly enables a superior architecture.
Should proably post to the comp.database.oracle forum, but I just don't know
them as well.
Regards
Jon
From: Eric Gold
To: McLeod, Jon
Cc: [email protected]
Subject: Re: RDBMS non-thread-safe issue
Date: Friday, 6 September 1996 11:21AM
Jon
In response to this message.....read below...
Sean's comment, above, speaks to an issue that is causing some concern
within my (large - 180 projects in development) organisation.
May I please ask the forum if there are others out there who have an
understanding of / concern with this "problem"?
My perception (quite possibly flawed) of the "problem" is that the RDBMS
cannot multi-thread data access objects. So we find ourselves in a situation
where we can achieve scaleability in just about all other
performance-sensitive areas of a system's technical architecture (we're
using DCE -- but have found that Encina is not advisable except where there
is a true requirement for heterogeneous distributed 2 phase commit, which we
don't often see.....) but when we go to hit on the RDBMS, we go back to good
ole single-threading.
In certain circumstances, this shortfall of RDBMS technology -- I won't
mention any names, of course, but the initials are "Oracle" -- seems to be
hindering our achievement of a desired technical architecture.
Is this a "Pro*C / PL/SQL stored procedures" problem or is it something that
is in the RDBMSs' DNA?
How can we get around it?
Any comments?Jon,
Go ahead ask the Forum any questions you want. This "problem"
is not a problem in Forte. What we allow you to do is "replicate" your
data access services so that each one runs inside its own
process. Each one of these processes (aka partitions) has its
own connection to the database. The routing to the replicated
partitions is transparent to the clients. Clients send a
message like "DatabaseService.GetCustomer()" and then the Forte
router sees which replicated copy of the service is not currently
processing a request and routes it to that free replicate. You
can dynamically increase or decrease the number of replicated
copies of the service easily.
We call this feature "load balancing" in Forte. It is achieved
by checking a box in the data access service object definition.
You can dynamically increase/decrease the number of replicates
and also dynamically move replicates to other nodes in the environment.
This approach assumes that you are using application driven
security and not database security. Each replicated copy
of the service is using the same generic username/password
to connect to the database.
I am forwarding this answer to forte-users because others
might not completely understand this feature.
Eric
Eric Gold
Technical Director
Forte Australia
Voice: 61-2-9926-1403
Fax: 61-2-9926-1401
Eric Gold
Technical Director
Forte Australia
Voice: 61-2-9926-1403
Fax: 61-2-9926-1401

Similar Messages

  • List of Non-thread safe system calls in Solaris 2.6??

    Hi,
    I'm searching for a list of system calls which are known to be non thread safe in a multithreaded process in Solaris 2.6. Anyone know of such a list?

    I'm not aware of any list but you can easily find the list by looking for the following pattern in the man pages :-)
    | ATTRIBUTE TYPE| ATTRIBUTE VALUE|
    |__________________________________
    | MT-Level | Unsafe |
    |_______________|_________________|
    HTH
    Angelo
    Sun Developer Support.

  • Locking a non-thread-safe DLL, innovative solutions?

    Hi,
    I need to be able to lock access to a non-thread-safe third party DLL, so that multiple threads cannot access DLL simultaneously. I know that I can use semaphore or a single element queue. Are there any other innovative solutions that would limit the access to the DLL to a single call simultaneously.
    If I use either semaphores or single element queue and use the semaphore (queue) with the same name in multiple programs (independent VIs), will the access to the DLL be handled without problems i.e. no collisions can happen? What if I build multiple applications (.exe) or application libraries (.dll), does a single semaphore (queue) still work between different applications or do they need to be initiated from the same application?
    Tomi
    Message Edited by Tomi M on 03-06-2006 08:01 PM
    Tomi Maila

    Tomi M wrote:
    One more thing, with
    innovative solutions I meant something like the following. Is there a
    way to use some properties of Labview execution system to automatically
    restrict the access to the DLL i.e. allow only single thread with
    certain properties to call the DLL while all other threads with the
    same properties are waiting in the execution queue. So if I set the
    execution priority to something specific and execution system to
    another something specific, will Labview thisway restrict access to DLL
    to be sequential?
    The proper way to
    call non multithread safe DLLs in LabVIEW is to configure the Call
    Library Node in the configuration dialog to be NOT reentrant. This
    tells LabVIEW that the DLL may behave badly or at least you do not want
    LabVIEW to call the DLL just from any thread. LabVIEW then will call
    this DLL function from the UI execution system which is guaranteed to
    only have one single thread at all times and therefore protect your DLL
    from being called frm different threads at the same time.
    Rlf Kalbermatter
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • Non-thread safe System.console(), although synchronized used?

    Hi, I recently noticed that the System.console() code looks like the following:
    public static Console console() {
             if (cons == null) {
                 synchronized (System.class) {
                     cons = sun.misc.SharedSecrets.getJavaIOAccess().console();
             return cons;
         }Is this thread safe, despite the synchronized block? I mean, suppose two threads try to get the console, and they both go past the null check. Then, one of them gets the lock, initializes the field blah blah. Then, the second gets the chance to run, and since it is past the null check, it will enter the synchronized code again. I don't know what happens in the sun.misc package, but as far as this code is concerned, this doesn't look valid to me. I might be wrong though :-)
    Cheers.

    DeltaGeek wrote:
    Correct, that is not thread-safe. Why not just make the entire method synchronized?Because if cons is already non-null, there's no need to synchronize (assuming cons is the same object for each thread, something not evident in the code snippet...)
    I'd put forth this:
    public static Console console() {
             if ( null == cons ) {
                 synchronized (System.class) {
                     // need second check in case cons was set while the thread
                     // was blocked
                     if ( null == cons ) {
                         cons = sun.misc.SharedSecrets.getJavaIOAccess().console();
             return cons;
         }And yes, I always put the non-L-value first, just in case I make a typo like this:
    int x;
    if ( x |= SOME_CONSTANT ) ...

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

  • 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

  • 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

  • Is this method thread safe?

    Hi Guys
    I have the following code:
    public class MyClass extends HttpServlet {
         HttpSession session;
         public doGet(HttpServletRequest request, HttpServletResponse response)
                                      throws IOException, ServletException                              
              session = request.getSession(false);
              List<AClass> htransactions = (List<AClass>)session.getAttribute("AClass");
                   //do stuff here
    }What I want to know is that if the HttpSession session is declared as a instance variable, does this make it non thread safe? Or is using such a way of for a session fine?
    .

    Steve declared a thumb-rule.
    Bear Bibeault
    sheriff & author
    Member # 24697
    posted Yesterday 9:17 PM
    Yes, variables created inside methods are safe because each thread will get their own copies. Instance variables are unsafe because they are shared across all threads.
    Keep this in memory, hope this was a perfect clarification...you can declare now on the answer.

  • Question about EJB and thread safe coding - asking again!

    sorry everyone, no one seems to be interested in helping me on this, so i post it again.
    i have a question about the EJB and thread safe coding. when we build EJBs, do we need to worry about thread safe issue? i know that EJBs are single threaded, and the container manages the thread for us. maybe i am wrong about this. if i wasnot, how can we program the EJB so that two or more instance of EJB are not going to have deadlock problem when accessing data resources. do we need to put syncronization in ours beans, do we even need to worry about creating a thread safe EJB? thanks in advance. the question really bothers me a lot lately.

    sorry everyone, no one seems to be interested in
    helping me on this, so i post it again.Excellent plan. Why not search a little bit on your own instead of waiting for your personal forum slaves to answer your call. See below.
    i have a question about the EJB and thread safe
    coding. when we build EJBs, do we need to worry about
    thread safe issue? Read this: http://forum.java.sun.com/thread.jsp?forum=13&thread=562598&tstart=75&trange=15
    i know that EJBs are single
    threaded, and the container manages the thread for us.
    maybe i am wrong about this. if i wasnot, how can we
    program the EJB so that two or more instance of EJB
    are not going to have deadlock problem when accessing
    data resources. do we need to put syncronization in
    ours beans, do we even need to worry about creating a
    thread safe EJB? thanks in advance. the question
    really bothers me a lot lately.
    Java's Thread Tutorial
    JavaWorld: Introduction to Java threads
    IBM: Introduction to Java threads
    Google: java+threads+tutorial

  • SSRS - Is there a multi thread safe way of displaying information from a DataSet in a Report Header?

     In order to dynamically display data in the Report Header based in the current record of the Dataset, we started using Shared Variables, we initially used ReportItems!SomeTextbox.Value, but we noticed that when SomeTextbox was not rendered in the body
    (usually because a comment section grow to occupy most of the page if not more than one page), then the ReportItem printed a blank/null value.
    So, a method was defined in the Code section of the report that would set the value to the shared variable:
    public shared Params as String
    public shared Function SetValues(Param as String ) as String
    Params = Param
    Return Params 
    End Function
    Which would be called in the detail section of the tablix, then in the header a textbox would hold the following expression:
    =Code.Params
    This worked beautifully since, it now didn't mattered that the body section didn't had the SetValues call, the variable persited and the Header displayed the correct value. Our problem now is that when the report is being called in different threads with
    different data, the variable being shared/static gets modified by all the reports being run at the same time. 
    So far I've tried several things:
    - The variables need to be shared, otherwise the value set in the Body can't be seen by the header.
    - Using Hashtables behaves exactly like the ReportItem option.
    - Using a C# DLL with non static variables to take care of this, didn't work because apparently when the DLL is being called by the Body generates a different instance of the DLL than when it's called from the header.
    So is there a way to deal with this issue in a multi thread safe way?
    Thanks in advance!
     

    Hi Angel,
    Per my understanding that you want to dynamic display the group data in the report header, you have set page break based on the group, so when click to the next page, the report hearder will change according to the value in the group, when you are using
    the shared variables you got the multiple thread safe problem, right?
    I have tested on my local environment and can reproduce the issue, according to the multiple safe problem the better way is to use the harshtable behaves in the custom code,  you have mentioned that you have tryied touse the harshtable but finally got
    the same result as using the ReportItem!TextBox.Value, the problem can be cuased by the logic of the code that not works fine.
    Please reference to the custom code below which works fine and can get all the expect value display on every page:
    Shared ht As System.Collections.Hashtable = New System.Collections.Hashtable
    Public Function SetGroupHeader( ByVal group As Object _
    ,ByRef groupName As String _
    ,ByRef userID As String) As String
    Dim key As String = groupName & userID
    If Not group Is Nothing Then
    Dim g As String = CType(group, String)
    If Not (ht.ContainsKey(key)) Then
    ' must be the first pass so set the current group to group
    ht.Add(key, g)
    Else
    If Not (ht(key).Equals(g)) Then
    ht(key) = g
    End If
    End If
    End If
    Return ht(key)
    End Function
    Using this exprssion in the textbox of the reportheader:
    =Code.SetGroupHeader(ReportItems!Language.Value,"GroupName", User!UserID)
    Links belowe about the hashtable and the mutiple threads safe problem for your reference:
    http://stackoverflow.com/questions/2067537/ssrs-code-shared-variables-and-simultaneous-report-execution
    http://sqlserverbiblog.wordpress.com/2011/10/10/using-custom-code-functions-in-reporting-services-reports/
    If you still have any problem, please feel free to ask.
    Regards
    Vicky Liu

  • Java.util.Locale not thread-safe !

    In multithreading programming, we know that double-checking idiom is broken. But lots of code, even in sun java core libraries, are written using this idiom, like the class "java.util.Locale".
    I have submitted this bug report just now,
    but I wanted to have your opinion about this.
    Don't you think a complete review of the source code of the core libraries is necessary ?
    java.util.Locale seems not to be thread safe, as I look at the source code.
    The static method getDefault() is not synchronized.
    The code is as follows:
    public static Locale getDefault() {
    // do not synchronize this method - see 4071298
    // it's OK if more than one default locale happens to be created
    if (defaultLocale == null) {
    // ... do something ...
    defaultLocale = new Locale(language, country, variant);
    return defaultLocale;
    This method seems to have been synchronized in the past, but the bug report 4071298 removed the "synchronized" modifier.
    The problem is that for multiprocessor machines, each processor having its own cache, the data in these caches are never synchronized with the main memory.
    The lack of a memory barrier, that is provided normally by the "synchronized" modifier, can make a thread read an incompletely initialized Locale instance referenced by the static private variable "defaultlocale".
    This problem is well explained in http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html and other documents about multithreading.
    I think this method must just be synchronized again.

    Shankar, I understand that this is something books and articles about multithreading don't talk much about, because for marketing reasons, multithreading is supposed to be very simple.
    It absolutely not the case.
    Multithreading IS a most difficult topic.
    First, you must be aware that each processor has its own high-speed cache memory, much faster than the main memory.
    This cache is made of a mixture of registers and L1/L2/L3 caches.
    Suppose we have a program with a shared variable "public static int a = 0;".
    On a multiprocessor system, suppose that a thread TA running on processor P1 assign a value to this variable "a=33;".
    The write is done to the cache of P1, but not in the main memory.
    Now, a second thread TB running on processor P2 reads this variable with "System.out.prinln(a);".
    The value of "a" is retrieved from main memory, and is 0 !
    The value 33 is in the cache of P1, not in main memory where its value is still 0, because the cache of P1 has not been flushed.
    When you are using BufferedOutputStream, you use the "flush()" method to flush the buffer, and the "synch()" method to commit data to disk.
    With memory, it is the same thing.
    The java "synchronized" keyword is not only a streetlight to regulate traffic, it is also a "memory barrier".
    The opening brace "{" of a synchronized block writes the data of the processor cache into the main memory.
    Then, the cache is emptied, so that stale values of other data don't remain here.
    Inside the "synchronized" block, the thread must thus retrieve fresh values from main memory.
    At the closing brace "}", data in the processor cache is written to main memory.
    The word "synchronized" has the same meaning as the "sync()" method of FileDescriptor class, which writes data physically to disk.
    You see, it is really a cache communication problem, and the synchronized blocks allows us to devise a kind of data transfer protocol between main memory and the multiple processor local caches.
    The hardware does not do this memory reconciliation for you. You must do it yourself using "synchronized" block.
    Besides, inside a synchronized block, the processor ( or compiler ) feels free to write data in any order it feels most appropriate.
    It can thus reorder assignments and instruction.
    It is like the elevator algorithm used when you store data into a hard disk.
    Writes are reordered so that they can be retrieved more efficiently by one sweep or the magnetic head.
    This reordering, as well as the arbitrary moment the processor decides to reconciliate parts of its cache to main memory ( if you don't use synchronized ) are the source of the problem.
    A thread TB on processor P2 can retrieve a non-null pointer, and retrieve this object from main memory, where it is not yet initialized.
    It has been initialized in the cache of P1 by TA, though, but TB doen't see it.
    To summarize, use "synchronized" every time you access to shared variables.
    There is no other way to be safe.
    You get the problem, now ?
    ( Note that this problem has strictly nothing to do with the atomicity issue, but most people tend to mix the two topics...
    Besides, as each access to a shared variable must be done inside a synchronized block, the issue of atomicity is not important at all.
    Why would you care about atomicity if you can get a stale value ?
    The only case where atomicity is important is when multiple threads access a single shared variable not in synchronized block. In this case, the variable must be declared volatile, which in theory synchronizes main and cache memory, and make even long and double atomic, but as it is broken in lots of implementation, ... )

  • SwingWorker process(List V chunks) but List isn't thread safe is it.

    Folks,
    Am I missing something or does
    protected void process(List<V> chunks)in the new 1.6 javax.swing.SwingWorker represent a potential threading issue?
    List isn't thread safe... so why not use a Vector, which is? Except that Vector is currently considered persona-non-grata by bigger brains than me.
    Hmmm... Of course, I don't know which implementation of List is being used under the hood, so I suppose I just have to trust the Java Gods who built the new SwingWorker to have used a thread safe implementation... which is pretty good bet, I suppose...
    Can anyone state categorically that it isn't a problem?
    Thanx. Keith.
    Message was edited by: corlettk PS: I'm knee deep in thread gruel and going down fast.

    publish definitely does not block until process is finished.
    In fact calling publish does not necessarily mean that process will be called right away.
    From the API:
    Because the process method is invoked asynchronously on the Event Dispatch Thread multiple invocations to the publish method might occur before the process method is executed. For performance purposes all these invocations are coalesced into one invocation with concatenated arguments.
    For example:
    publish("1");
    publish("2", "3");
    publish("4", "5", "6");
    might result in:
    process("1", "2", "3", "4", "5", "6")
    Edit:
    The only source I could find for AccumulativeRunnable (the class used to accumulate the arguments passed to publish) was here:
    http://fisheye5.cenqua.com/browse/swingworker/src/java/org/jdesktop/swingworker/AccumulativeRunnable.java?r=1.2
    which isn't necessarily the implementation in the JDK but it's probably close.
    That shows that before process is called the accumulating list reference is nulled, meaning that there is no way that publish can append to the list during a call to process.
    In fact calling publish as the same time as process is executing on the EDT appends the published arguments to a fresh list, leading to another call to process at some later time (in SwingWorker the delay between a call to publish and a call to process is at most 1000/30 milliseconds).
    Message was edited by:
    dwg

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

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

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

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

  • Is the Illustrator SDK thread-safe?

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

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

Maybe you are looking for

  • TS2446 I do not have another cc to make payments please advise

    I am studying and have had my apple ID disabled....To reset to purchase books I need to place another cc...this is day 2 now...it's Sunday and I do not want another cc !!! How frustrating is this !!!!!!

  • IMac started to hang!!

    I have had my mac for little over a year now and have just started to experience my first taste of mac issues. For some reason my OS (leopard 10.5.8) takes forever to do anything. All I have for company most of the time is the colour wheel. It also f

  • Parsing problems under xmlparserv2.jar

    I cannot parse a XML file with the Oracle XML Parser xmlparserv2.jar. I have also tried to attached a XML Schema to the file and the same error occurred. Trying another parser ( crimson.jar) the file was parsed successfully. So I think I am missing s

  • Iphone 4 will not sync after restore

    Iphone 4 will not sync via itunes via USB cable after restore.  Rebooted PC and iphone.  Latest version of itunes and iOS.  Device appears on left hand window, but the main window only shows the Apple logo, and empty white box, and a small LOCK symbo

  • Help: How to change the name of a Mighty Mouse (Bluetooth)

    When I go into the Keyboard & Mouse preference and click on the Bluetooth, I can see the box for name and battery level for the mouse and keyboard. The problem is, those textboxes are not enabled. As the result, I cannot rename my bluetooth mouse. Ca