Hashtable really thread safe or is there a bug in it ?

Hashtable is said to be thread-safe, so I think it should be true.
So I just want someone to tell me what is wrong with my following observation:
I downloaded the source code of jdk 1.3.1 and read the file Hashtable.java, that contains the implementation code of Hashtables.
Lots of methods (like get(), put(), contains(), ...) are declared public and synchronized. So far, all is good.
But the function size() is defined as follows:
public int size() {
     return count;
where count is an instance variable defined as follows:
* The total number of entries in the hash table.
private transient int count;
As the function size() is not synchronized, it can retrieve the value of "count" when another method is in the process of updating it.
For instance, the method put() (that is synchronized) increments the variable "count" with this instruction:
count++;
But we know that operation on variable of type "int" are atomic, so this issue doesn't harm the thread safety of the code.
But there is another issue with multithreading, that deals with caching of data in the working memory of each thread.
Suppose the following scenario:
1) Thread A calls method size(). This method reads the value of "count" and put it in the working memory of thread A.
2) Thread B calls method put(). This method increments "count" using instruction "count++".
3) Thread A calls method size() again. This method reads the value of "count" from the working memory of the thread, and this cached value may not be the updated value by thread B.
As size() is not synchronized, or "count" is not declared "volatile", multiple threads may retrieve stale value, because the content of the thread working memory is not in sync with main memory.
So, here I see a problem.
Is there something wrong in this observation ?
But

Is there something wrong in this observation ?Unfortunately not, as far as I can tell.
Recent analysis of java's synchronized support has revealed the danger in such unsynchronized code blocks, so it may have been a simple case that it wasn't realised that size is not thread-safe.
If this is an issue, use Collections.synchronizedMap - in Sun's JDK 1.3, at least, all of the methods are synchronized, except for iterators.
Regards,
-Troy

Similar Messages

  • Thread safe ?

    Hi
    This code is currently running on my companys server in a java class implementing the singleton pattern:
    public static ShoppingAssistant getInstance() {
        if (instance == null) {
            synchronized (ShoppingAssistant.class) {
                instance = new ShoppingAssistant();
        return instance;
    }1 Is there really a need for synchronizing the method?
    2 If you choose to synchronize it. Why not just synchronize the whole method?
    3 Is this method really thread safe? Is I see it a thread A could be preempted after checking the instance and seing that it is null. Thereafter another thread B could get to run, also see that instance is null and go on and create the instance. Thereafter B modifies some of the instance�s instance variables. After that B is preempted and A gets to run. A, thinking instance is null, goes on and create a new instance of the class and assigns it to instance, thus owerwriting the old instance and creating a faulty state.
    By altering the code like this I think that problem is solved although the code will probably run slower. Is that correct?
    public static ShoppingAssistant getInstance() {
        synchronized (ShoppingAssistant.class) {
            if (instance == null) {
                instance = new ShoppingAssistant();
    }Regards, Mattias

    public class Singleton {
    private static final instance = newSingleton();
    public static Singleton getInstance() {
    return instance;
    }This seems like it's so obviously the standard
    solution, why do
    people keep trying to give lazy solutions? Do they
    expect it to be
    more efficient that this?I can see one possible performance gains with a lazy solution:
    If you use something else in that class (besides getInstance()), but don't use getInstance, then you don't take the performance hit of instantiating the thing.
    Of course, this is dubious at best because how often do you have other static methods in your singleton class? And not use the instance? And have construction be so expensive that a single unnecessary one has a noticeably detrimental impact on your app's performance?

  • Swing isn't thread safe, what about AWT?

    Since Swing isn't really thread safe what does that mean for AWT? Is AWT thread safe? Also if it is doesn't that mean one should use AWT over Swing since AWT is thread safe?

    Trizi wrote:
    jverd wrote:
    Trizi wrote:
    [http://forum.java.sun.com/thread.jspa?threadID=5282846&tstart=0|http://forum.java.sun.com/thread.jspa?threadID=5282846&tstart=0]
    There ya go duffy the hom^oYou say that is if being gay were a bad thing. So, besides being an obnoxious fuckhead, you're also a homophobic troglodyte? Man your fiancee must be a real winner to have picked you. My guess is that she's either a sheep, a blow-up doll, or someone you've got bound and gagged in your basement.Now from what everyone is saying that I don't have anything original...
    You don't either, too much "Silence of the Lambs" maybe?Dude, try speaking English.
    By the way, I am sure if I was a troglodyte I would be in a museum, also I have homosexual friends, sorry not homophobic, I just found a good ting to his name and figured I'd exploit it.. Just like I'm exploiting your pathetic intelligence.You really need help if you think the above makes any sense or any point.

  • Is weblogic jax-ws generated client thread safe

    Hi
    I want to use JAX-WS webservice on weblogic 10.3.
    Is there any best practices on how to generate the client stub ? Are the client stubs generated by weblogic thread-safe or is there any pool to implement.
    I've read on some old forum posts that with older versions of weblogic client stub was not thread safe when using SSL : is it always the case ?
    Regards
    Sébastien

    Hello Ravish,
    Can you please confirm the following:
    1) Check the Admin>Web Services Utilization page in CRMOD to see if the request is received
    2) Do you receive any response from CRMOD on the client side and if so, please post the SOAP response
    3) Have you tried other objects and had any issues with them?
    Thanks,
    Sean

  • 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

  • Is there a thread safe date format ?

    I had format problem with date so I wrote a test program to see if I could reproduce it
    this program runs 2 threads which translate a system date into a french date format
    I used 3 method
    1 - static java.text.DateFormat df = �����������������DateFormat.getDateInstance(DateFormat.SHORT,Locale.FRANCE);
    the result is
    thread 1 �04/02/02
    thread 1 �04/02/02
    thread 1 �04/02/02
    thread 2 �04/02/02
    thread 1 �04/02/2002 � ==> ?
    thread 2 �04/02/02
    thread 1 �04/02/2002 �==> ?
    thread 2 �04/02/02
    thread 1 �04/02/2002 �==> ?
    thread 2 �04/02/02
    thread 1 �04/02/2002
    2 - static java.text.DateFormat df = ��������������DateFormat.getDateInstance(DateFormat.LONG,Locale.FRANCE);
    thread 2 �4 f�vrier 2002
    thread 2 �4 f�vrier 2002
    thread 2 �4 f�vrier 2002
    thread 2 �4 f�vrier 2002
    thread 1 �0004 f�vrier 2002 �==> ?
    thread 1 �4 f�vrier 2002
    thread 1 �4 f�vrier 2002
    3 - �SimpleDateFormat ("dd/MM/yyyy");
    thread 2 �04/0002/2002 ==> ?
    thread 1 �04/02/2002
    thread 2 �04/0002/2002 ==> ?
    thread 1 �04/02/2002
    thread 2 �04/0002/2002 ==> ?
    thread 1 �04/02/2002
    thread 1 �04/02/2002
    did I miss something ?
    why it is not "thread safe " ?
    any help ...
    thranks denis
    (my sample program)
    import java.util.*;
    import java.text.*;
    public class th extends Thread {
    /** T1 = getDateInstance(DateFormat.[SHORT-LONG],Locale.FRANCE); **/
    //static java.text.DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT,Locale.FRANCE);
    /** T2 = SimpleDateFormat **/
    static private SimpleDateFormat _formatter = new SimpleDateFormat ("dd/MM/yyyy");
    public String message ;
    public th (String msg) {
    this.message = msg ;
    public void run () {
    try {
    while ( true ) {
    printmess() ;
    } catch (Exception e ) {System.out.println (" error  ") ; } ;
    public void printmess( ) {
         /** T1 **/
         //String dateString = df.format(new Date());
         /** T2 **/          
    String dateString = _formatter.format( new Date() );
    System.out.println(message+" "+dateString);
    public static void main(String[] args) {
    Thread t1 = new th("thread 1 ") ;
    Thread t2 = new th("thread 2 ") ;
    t1.start();
    t2.start();

    I was able to reproduce your problem and found that make a minor change seems to have fixed the problem:
    import java.util.*;
    import java.text.*;
    public class th extends Thread {
    /** T1 = getDateInstance(DateFormat.[SHORT-LONG],Locale.FRANCE); **/
    //static java.text.DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT,Locale.FRANCE);
    /** T2 = SimpleDateFormat **/
    // static private SimpleDateFormat _formatter = new SimpleDateFormat ("dd/MM/yyyy");
    SimpleDateFormat _formatter;
    public String message ;
    public th (String msg) {
    this.message = msg ;
    _formatter = new SimpleDateFormat ("dd/MM/yyyy");
    public void run () {
    try {
    while ( true ) {
    printmess() ;
    } catch (Exception e ) {System.out.println (" error ") ; } ;
    public void printmess( ) {
    /** T1 **/
    //String dateString = df.format(new Date());
    /** T2 **/
    String dateString = _formatter.format( new Date() );
    System.out.println(message+" "+dateString);
    public static void main(String[] args) {
    Thread t1 = new th("thread 1 ") ;
    Thread t2 = new th("thread 2 ") ;
    t1.start();
    t2.start();
    V.V.

  • HASHMAP is it thread safe really?

    Hi all,
    I want to use the Hashmap class in my program but I need to know is it thread safe???
    Thanks
    ps where would I find out information like that?

    I am just wondering what gave u the concept of thread safetyness.........Well its up to u how u make use of it for that matter even a simple program can be thread unsafe u know........ its only the implementation which matters So don't worry take my word and go ahead with that...the class by itself is threadsafe but do a proper implementataion.

  • What is "Thread Safe"?

    I have heard a lot of folks talking about a class that is "Thread Safe".
    I am assuming that this means the obect can be accessed by more than one thread at a time. I do not know what the concept really means in practice.
    My question is, how can I tell if something is thread safe, what do I need to look out for?

    Basically you're looking to avoid unwanted behavior by simultaneous access. Here are a couple examples I've seen:
    Assuming myID is a class variable...
    public void assignID(Client currentClient) {
    myID = (some new random value)
    currentClient.ID = myID;
    In the above example, what happens if two threads access the method at the same time? The first one starts, assigning a value to the myID variable. Then the second one starts, assigning a value to myID AGAIN. Then when both clients assign their currentClients, they'll both end up with the same ID. To avoid a code block being accessed by two clients simultaneously, use the "synchronized" keyword.
    Here's another one. Assume you have a Hashtable:
    Enumerator myEnum = myHashtable.keys()
    while (myEnum.hasMoreElements()) {
    Object myKey = myEnum.nextElement();
    myHashtable.remove(myKey);
    This should not work in Java (and I know it doesn't in C# which I'm currrently being forced to use at work) because you're iterating through the keys of a Hashtable. But while you're trying to go linearly from key to key, you're also removing elements of the Hashtable. You're trying to operate on the object twice and the object doesn't allow it.
    There are a couple ideas. I wrote a database pool once and had to synchronize methods so two clients didn't try to execute a query through the same Connection, etc.
    Michael Bishop

  • Thread-safe design pattern for encapsulating Collections?

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

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

  • Thread-safe Singleton

    Hi,
    I want to create a thread safe singleton class. But dont want to use the synchronized method or block. One way i could think of was initializing the object in static block. This way the instance will be created only once. But what if instance becomes null after some time. How will it get initialized again. Can anyone help me in creating a thread safe singleton class.
    Also i would really really appreciate if some one can point me to a good tutorial on design patters, I searched on google.. Found many.. But not finding any of them satisfying.
    Thanks

    tschodt wrote:
    Balu_ch wrote:
    kilyas wrote:
    Look into the use of volatile instead of synchronized, however the cost of using volatile is comparable to that of synchronizingCan you please explain in detail Google can.
    Google ( [java volatile vs synchronized|http://www.google.com/search?q=java+volatile+vs+synchronized] ).
    Hi, I think we need to use both (volatile and synchronized). Can some please explain how "volatile" alone can be used to ensure thread safe singleton? Below is the code taken from wikipedia
    public class Singleton {
       // volatile is needed so that multiple thread can reconcile the instance
       // semantics for volatile changed in Java 5.
       private volatile static Singleton singleton;
       private Singleton()
       // synchronized keyword has been removed from here
       public static Singleton getSingleton(){
         // needed because once there is singleton available no need to acquire
         // monitor again & again as it is costly
         if(singleton==null) {
           synchronized(Singleton.class){
              // this is needed if two threads are waiting at the monitor at the
              // time when singleton was getting instantiated
              if(singleton==null)
              singleton= new Singleton();
       return singleton;
    }

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

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

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

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

  • 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

  • Is abap thread safe? Some question in Singleton pattern in ABAP

    Hi Grus,
    I have a very basic question but really make me headache...
    Recently I am learning the design pattern in ABAP and as you know in JAVA there is a key word "Synchronized" to keep thread safe. But in ABAP, I didn't find any key words like that. So does that mean ABAP is always a single thread language? And I found that there is a way looks like "CALL FUNCTION Remotefunction STARTING NEW TASK Taskname DESTINATION dest" to make multi-thread works. As you can see it use the destination, so does that mean actually the function module is always executed in a remote system, and in every system, it is always single thread?
    Could you help me on the question? Thanks a lot, grus
    And here comes up to my mind another question...It's a little bit mad but I think it may works....What if I set every attribute and method as static in the singleton class...Since as you can see it is already a singleton so every attribute in it should be only one piece. So then I don't even need to implement a get_instance( ) method to return the instance. Just call "class_name=>some_method( )" directly then singleton is achieved...What do you think?
    BR,
    Steve

    Steve,
    I've the same question, few days ago I tried to use the singleton in ABAP. In Java programming is possible to use the same reference in two sessions or programs, sharing attributes, methods and all data, but I could not do in ABAP.
    In my test I created a program with one global class using the singleton pattern, so I expected that when I run my program and see the reference returned after the get_instance method it should be equal to the same program run in another session, but the ABAP will create a new reference and instantiate again.
    So I deduced that the only way to share it between sessions in ABAP is using the ABAP Shared Memory Objects.
    I can be wrong, but I think that ABAP use a thread by user session (Each window) and we can't change it.
    Best regards.

  • 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

Maybe you are looking for

  • Error 1603. Photoshop CS4

    Alright, so I recently got Photoshop CS4, for some odd reason when I had to do a system restore, it messed up. Not sure why, but I got the screen to accept or decline the user end license agreement, when I clicked to accept it, it just went away and

  • How do I delete something from the drop-down menu of the URL bar. I went there accidentally and don't want it in the list.

    I directly typed what I thought was the correct URL into the URL box. It took me to a site different from where I was wanting to go. Now that site's URL is in the list of URL's in the drop-down box. Is there some way of deleting this from the drop-do

  • I updated to itunes 11.3 and now when i open itunes it is not responding

    I just updated iTunes to 11.3 and now every time I go to open iTunes its saying that iTunes is not responding and closes. I do not know what to do or how to fix this problem at all. please someone help!

  • Displaying International Characters

    Some users have been concerned about the fact that Buzzword does not display some international characters - ranging from Greek to Russian. This is accentuated by the fact that we have Buzzword users in well over 100 countries. The problem occurs whe

  • Nonblocking I/O  & serialization

    Hi!! I try to send an object (a class that I created) using nonblocking Java 1.4.1 channels, but when I create the ImputObjectStream for deserialize, an interruption (IllegalBlockingMode) is throws. Why? How I use serialization method (like InputObje