Thread-safe invocation of method?

I have 10 threads that would like to store each of their value corresponding to a key in a HashMap. Each thread has a unique key.
They all call this method in class A at the same time:
a.myPut(hm,key,value)
public void myPut(HashMap hm, String key, String value)
       String result = "element with key: " + key + " has value: " + value;
       hm.put(key,v);
}The problem is that while thread 1 is about to store its version of "result" thread 2 might have changed it so thread 1 actually stores thread 2's version of "result".
Solution:
Have another object that has a put method:
class uniquePut
       private HashMap hm;
       private String key;
       private String value;
       public uniquePut(HashMaps h, String k, String v)
                    this.hm=h;
                    this.key = k;
                    this.value = v;
       public void putU ()
                   String result = "element with key: " + key + " has value: " + value;
                   hm.put(key,result);
       }instead of calling a.myPut a thread now first make a new instance of uniquePut and then calls putU:
new uniquePut(hm,key,value).putU();this way each thread gets it own put method that no other thread can interleave with, but still all threads can execute concurrently.
Is there any flaws with this approach?

From the API doc:
<quote>
Note that this implementation is not synchronized. If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:
Map m = Collections.synchronizedMap(new HashMap(...));
</quote>

Similar Messages

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

  • Is Clone thread safe?

    I am examining property change class and notice that it does an unsynchronized clone of vector. This makes me wonder if clone is thread safe? it must be or this clone could experience the same problems of copying the vector while its being modified.
    Anybody know if clone is indeed thread safe?

    Of course your clone() method can be thread safe if
    you want it to be; simply make your overriding clone() method
    synchronized ...I still don't think this will be thread-safe, unless all methods that
    change data in the object are also synchronized. Even then you can't
    be sure unless you declare your class final, because otherwise
    someone else could add non-threadsafe methods later.Sure, that's why I emphasised '*your* clone() method'. What others
    do to it is up to them ;-)
    kind regards,
    Jos

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

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

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

  • How can I get to know if a method is threads-safe?

    Hi, there.
    How can I get to know if a method is threads-safe?
    For example, in two different threads, is System.out.print() method safe or not?And where can I find the information with regard to this?
    thanks very much.

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

  • Are static methods in Java thread safe?

    Are static methods in Java thread safe?
    thanks,
    suresh

    if static method use the instance variable
    You mean member variable, where member variables are either class variables (static) or instance variables (non-static).
    then you have to make it thread safe using
    synchronization Not necessarily. Depends on requirements and usage context.
    else in case of local var. it
    is thread safe. Not necessarily. That local variable could refer to an object that's visible to multiple threads.
    Statements like "Local variables are threadsafe but member variables aren't" are an oversimplification.
    Something is threadsafe if it cannot be made to behave incorrectly simply by running it in a multithreaded context. Determining that can be very difficult.

  • Are methods in the Graphics class Thread Safe

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

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

  • Are Static methods Thread safe?

    Hello All
    I have a static method that takes a integer and returns a mathematically processed result.
    Since this method is frequently required, I have placed it in a common class and declared it as static.
    I want to know whether this method is thread safe?

    There's nothing special about static methods, with regard to thread safety. If they access shared objects, then such access will usually need to be controlled by synchronisation; this might be on the object being accessed, some higher-level object or a special object allocated purely as a lock. The only way that you might think of them as special is that there's no instance of the Class on which you can synchronise.
    You can declare a static method as synchronised. If you do, it will be synchronised on the single Class object of the class in which it is declared. This means that only one thread can be executing any part of the method at any one time. However, I understand that the Java Runtime itself sometimes synchronises on this Class object for its own reasons, therefore you might sometimes find a synchronised static method blocks when no other thread is executing it. Usually better, therefore, to explicitly synchronise on some object or other, than to use synchronised static methods.

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

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

  • Is getString() method in ResourceBundle thread safe?

    Is getString() method in ResourceBundle thread safe?

    i was just thinking about the following scenario.
    Lets assume that there are 2 threads accessing the same ResourceBundle object.
    and are calling getString(key) method. In this case if thread1 passes key1 and thread2 passes key2, there might be a chance that both the threads get the same value as the counter is shared across these threads. I believe if ResourceBundle uses some synchronized objects like HashTable, then we are sure that it is thread safe.
    Let me know your comments on this pls.

  • Is ServletContext methods thread-safe?

    Just read servlet spec again, I know for shared data which is used by
              servlet must be thread-safe. But how about setAttribute/getAttribute methods
              on ServletContext and Session object? Are they thread-safe? or I have to
              synchronize the access to these methods?
              Any help is appreciated.
              

    hi Antalas,
    for Tomcat,it is not thread safe.but for WebSphere it is.for more info click on the following link :
    http://www.webagesolutions.com/knowledgebase/waskb/waskb026/index.html.
    [email protected]

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

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

    Thread safe variables can only be accessed by one thread at a time, so while the first one is holding the pointer, the second one waits until the pointer is released.
    This is more rigid than using thread locks, in that a thread could call CmtTryToGetLock remaining free to run even if the lock cannot be acquired (supposing running without the locked object makes sense).
    But it is not clear to me from your question whether you actually want thread safe variable functions to lock or are afraid they will do so...
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • 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

  • 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

Maybe you are looking for

  • Decimal Point Validation in Oracle Forms 6i

    One of my table has a column named interest. Data type of this column is number (4,1) so it can hold 99.9 and 100 both. If user enters 9.99, oracle form accepts the values and rounds it to 10. When scale defined for this data type is 1 so user should

  • Archiving Mac Mail emails per year

    hello is there an easy way ( read: automatic, by script ;-) to archive my Mac Mail emails per year ? thx in advance Henny

  • Error starting up OC4J Standalone 904

    I'm getting the following error when starting up an OC4J 904 standalone (/j2ee/home/java -jar oc4j.jar) I get this error on both my Windows 2000 environment and Solaris. Any ideas? 04/02/19 10:29:07 Error creating Tag Library Descriptor Cache : null

  • "Display driver stopped responding and has recovered" error

    Hi, I recently upgraded my laptop to Windows 8.1 and now from time to time, I am receiving the error above on the right side of the screen and my photoshop files won't open. Instead it just freezes and becomes unresponsive so I have to close Photosho

  • BCP with Runtime

    Hi, I am facing a problem while I am trying to BCP-in (sybase) through Runtime class. It is working fine on HP machine. Buy when I am trying it on Solaris, it is working fine till 59 records, but after that it is getting stuck. There are no errors. B