Is the reflection API thread safe?

The obvious answer would appear to be yes, however, I have not been able to find any supporting documentation.
I need to call the newInstance(Object[] initArgs) method on the same instance of the Constructor class from multiple threads.

Hi,
without knowing the reflection API too well, my guess would be, you are ok. If several threads are
just creating new instances and you are not modifying anything used in their constructors, no problem.
However, if you have a thread changing some class variables that are used in turn by the constructors to
initialize the instances, you are in trouble.
In such a case, try to encapsulate read&write access to these variables in synchronized
methods (setter/getter).
Good luck!
Pete

Similar Messages

  • Is the Memory Suite thread safe?

    Hi all,
    Is the memory suite thread safe (at least when used from the Exporter context)?
    I ask because I have many threads getting and freeing memory and I've found that I get back null sometimes. This, I suspect, is the problem that's all the talk in the user forum with CS6 crashing with CUDA enabled. I'm starting to suspect that there is a memory management problem when there is also a lot of memory allocation and freeing going on by the CUDA driver. It seems that the faster the nVidia card the more likely it is to crash. That would suggest the CUDA driver (ie the code that manages the scheduling of the CUDA kernels) is in some way coupled to the memory use by Adobe or by Windows alloc|free too.
    I replaced the memory functions with _aligned_malloc|free and it seems far more reliable. Maybe it's because the OS malloc|free are thread safe or maybe it's because it's pulling from a different pool of memory (vs the Memory Suite's pool or the CUDA pool)
    comments?
    Edward

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

  • Creating junit test cases using the reflection API

    In order to use the reflection API to get information about a *.java file's class name and methods, I need to compile the *.java file first, and then get info through the *.class file. Am I right?
    Eclipse, the Java IDE, can create junit test cases for java files the user selects right after the *.java files have been created, and even before the *.java files have been compiled by the user. I guess Eclipse internally compiles the java files before creating JUnit test cases for them. Does anyone know about it? Thanks.

    Let me explain my problem in more details.
    Given any java source tree, my program is supposed to create junit test cases for each class using java reflection. My approach is to scan through the source tree to keep the list of classes available, then compile all the java files in the given source tree, then do Class.forName() to load them to get their methods... Obviously I don't know what classes I will have at compilation time. I create a temp_classes directory as the output directory for the given source tree java files, and I add temp_classes to my classpath when I strart up my own program. However, that won't work..
    D:\eclipse\workspace\cmpe271_hw4\classes>java -classpath ..\classes;..\temp_classes Test
    javac -classpath .\temp_classes; -d .\temp_classes @temp_classes\javalist.txt
    java.lang.ClassNotFoundException: Factory
    java.lang.ClassNotFoundException: InvalidDateFormatException
    java.lang.ClassNotFoundException: MyUtility
    java.lang.ClassNotFoundException: Storage

  • 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

  • Better not to use the Reflection API?

    A few companies are creating a framework for the company I work for. They use very often the Reflection API which seems strange and even "dirty programming" to me.
    The side effects are in my eyes is that if refactoring is done within Eclipse, everything is refactored except the strings which are used to dynamically build the method name which is then invoked. I hope you know what I mean. Besides, if a UML, audit or metrics tool is used, such tools don't understand that the Reflection API is used. They don't follow the reflection trail.
    So my question to you is whether the Reflection API should be avoided like GOTO or if it should be used? If it should be avoided, what would be the best alternative to the Reflection API?

    Sounds more like a failing of Eclipse than of your partner companies. Reflection is part of Java. Whether an IDE should be capable of refactoring "runtime" code at compile time is another matter, however..
    In most cases reflection can be avoided. Yet, as with all design decisions, you've got to balance purity with simplicity. Reflection can actually be simpler/clearer than the mess you might get in trying to avoid it. It's not evil, it's just misunderstood.
    In the wrong hands it's a nightmare but used judiciously it's another useful tool.
    As for alternatives, there's really not enough information to say - if it's simply being used to install a Factory at runtime, for example, then there's not much of an alternative unless you know all the Factories that will be used and hardcode them in. If reflection's just being used to invoke a method then it could indeed be replaced unless the method is also determined at runtime. Etc...
    Sometimes extracting a common interface will resolve these problems but not always - it's horses for courses.
    Hope this helps.

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

  • Java.lang.reflect.Constructor thread safe ?

    When you have a Constructor object in Java.
    Is calling the newInstance method on the same Constructor object from multiple threads safe.
    Or is this not thread safe leading to wrongly constructed objects?

    ejp wrote:
    And as Constructors are immutable, it's hard to see how it's going to get altered.Constructors are basically immutable, but they have at least one state which can make the difference between newInstance working or failing.
    As you can see in the following example, setAccessible() is not something you would want to set to different values in different threads.
    import java.lang.reflect.Constructor;
    public class Main {
        public static void main(String... args) throws Exception {
            Constructor cons = Private.class.getDeclaredConstructor();
            cons.setAccessible(false);
            try {
                System.out.println("cons.isAccessible()= " + cons.isAccessible());
                cons.newInstance();
                throw new AssertionError("IllegalAccessException expected");
            } catch (IllegalAccessException expected) {
                // ignored
            cons.setAccessible(true);
            System.out.println("cons.isAccessible()= " + cons.isAccessible());
            cons.newInstance();
    class Private {
        private Private() {
    }

  • Is NI-CAN v2.3 & NI PCI-CAN/XS2 with Frame API Thread Safe?

    Hi, I'm downloading a file from the host computer to the modules. When I downloaded the data to the four module at the same time (with 4 threads), I'm getting communication failure ~ 20% of the time. When I synchronized the software, so it will download two modules at a time (using one port from each card at a time). The communication failure disappeared. I just wonder if the NI-CAN software & PCI-CAN/XS2 are thread-safe. I'd appreciate if anyone have any suggestion.
    Information of the software & hardware
    - Computer: Pentium4 2.8GHz, 512M Ram
    - OS: Windows 2000
    - Development Tool: Borland C++ Builder v5
    - NI-CAN v2.3 - The application is using Frame API
    - PCI-CAN/XS2 (SW-Selectable CAN, 2 Ports)
    - CAN bus: 500k High Speed
    Thanks
    Eric

    The NI-CAN software does support threads. What's the specific error
    you're getting that 20% of the time? It may be due to something besides
    the multi-threading.
    Regards,
    Matt S.
    LabVIEW Integration Engineer with experience in LabVIEW Real-Time, LabVIEW FPGA, DAQ, Machine Vision, as well as C/C++. CLAD, working on CLD and CLA.

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

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

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

  • Thread safe logging class, using final and static

    Hi,
    I'm looking through a logging class (which writes entries to a text file and so on) written by someone else, and I'm trying to determine whether it's thread-safe...
    Essentially the class looks like this:
    public final class Logger {
    private static FileOutputStream fout;
    private static PrinterWriter pout;
    private static final long MaxLength = 100000;
    static {
    /* basically checks size of logfile, if bigger than 100k, then copy it as bak, and start again */
    public void write(String msg) {
    /* write entry into log file */
    public void writeWithTimeStamp(string msg) {
    /* write entry with time stamp into log file */
    Now, I could be wrong, but I don't think that the class is thread-safe is it? in order to be thread-safe, I would have to use synchronized before write() and writeWithTimeStamp(), right?
    My confusion arises from the use of the keyword "final" at the top of the class. This class isn't being inherited (or rather, there's no reason for the class not to be inheritable)... so what is it's purpose, if there is one?!
    And my other question concerns the static block. But I need to describe the current setup first: The Logger class is being use by a file server. File server basically sits there, accepts socket connections from the outside, and takes text files and output them into a local directory. When a new socket connection is created, a new thread is created. As it stands right now, each thread instantiates its own Logger object which seems weird! Bringing me to my question which was, if each thread instantiates its own Logger object, the static block is only ran ONCE, regardless of how many threads (and therefore Logger objects) are created, right??
    And wouldn't it be a better idea to simply create only ONE Logger object and pass it by reference to all newly created threads as they are needed so that all threads access the same and only Logger object? (and therefore utilize sychronization)
    Thanks!

    In JDK 1.4, there are already classes written that do all of that work. Check out the docs for the java.util.logging package. Specifically, check out FileHandler (which can rotate log files if they are greater than a specified size) and LogRecord (which is a standardized way to store logging entries). I believe the class is threadsafe, it doesn't say it isn't. Try it and see. If not, you can easily make a threadsafe wrapper for it (or any class for that matter).
    The online documentation is at:
    http://java.sun.com/j2se/1.4/docs/api/index.html
    If you are curious, the simplest way to make any class threadsafe, if you don't want to or are not able to modify the class code itself is to define another class that calls methods of the original class, but that is synchronized.
    Example:
        // NonThreadSafe.java
        public class NonThreadSafe {
            public NonThreadSafe (String s) {
                // Constructor
            public void SomeMethod (int param) {
                // Do some important stuff here...
            public int AnotherMethod (boolean param) {
                // Do some more important stuff here...
        // ThreadSafeWrapper.java
        public class ThreadSafeWrapper {
            protected NonThreadSafe nts;
            public ThreadSafeWrapper (String s) {
                nts = new NonThreadSafe(s);
            public synchronized void SomeMethod (int param) {
                nts.SomeMethod(param);
            public synchronized int AnotherMethod (boolean param) {
                return nts.AnotherMethod(param);
            public NonThreadSafe GetNonThreadSafe () {
                return nts;
        };Unfortunately, ThreadSafeWrapper isn't derived from NonThreadSafe, so you are somewhat limited in what you can do with it compared to what you could do with NonThreadSafe. AFAIK, you can't override unsynchronized methods with synchronized ones.
    Another thing you could do is just write a method that writes to your logging class, and synchronize just that method. For example:
        // ThreadSafeLogger.java
        public class ThreadSafeLogger {
            public static synchronized void LogMessage (MyLogger log, String msg) {
                log.writeString(msg);
        // In another thread, far, far away:
            ThreadSafeLogger.LogMessage(theLog, "Blah");
            ...Hope that helps.
    Jason Cipriani
    [email protected]
    [email protected]

  • Using reflection api to copy like named attributes of a class

    Hi guys,
    I have been hearing about this for a long time now. How can one copy like named attributes from one class to another using the reflection api??
    Can anyone provide a small example, with code??
    Thanks.

    maxim.veksler wrote:
    I think that a chronological order of events should describe what happened :
    Issue #1 10:55 15/09/2008 - I try to find a solution to retrieving annotations of a field http://forums.sun.com/thread.jspa?threadID=5331440
    Issue #211:13 15/09/2008 - I learn that this can be done using the Field class, so I got looking for a way to getting all the fields http://forums.sun.com/thread.jspa?threadID=5331441
    Issue #3 13:15 15/09/2008 - I find a solution which is nearly working and post the last issue I have. http://forums.sun.com/thread.jspa?threadID=5331475
    Issue #313:26 15/09/2008 - thomas.behr helps me with the issue mentioned from thread 5331475 http://forums.sun.com/thread.jspa?messageID=10424090#10424090
    Issue #2 14:32 15/09/2008 - You (kajbj) comment that I need to use suggested solution. Please note that when I posted this I didn't know about the "right" solution.
    Issue #2 15:01 15/09/2008 - I thank you and link to an example where I implemented the search. I still don't know if the solution I found was the correct one.
    Please understand that I had no intention to create unnecessary hassle.kaj post above came at 11:32 (according to the time display here), and your post, in the other thread, acknowledging that you now had a solution was at 10:37. So how did you "not know" at that time, that you had a solution.
    But nevermind, dead conversation anyway, the post would not have been made under any other circumstances than the present (if then) anyway, and we both know it.
    Edit: And I didn't say you had any intention of purposely wasting people's time, but I don't believe that you had any intentions of not doing so, either (i.e. as in trying to prevent it).

  • Problems with Reflection API and intantiating an class from a string value

    I want to instantiate a class with the name from a String. I have used the reflection api so:
    static Object createObject(String className) {
    Object object = null;
    try {
    Class classDefinition = Class.forName(className);
    object = classDefinition.newInstance();
    } catch (InstantiationException e) {
    System.out.println(e);
    } catch (IllegalAccessException e) {
    System.out.println(e);
    } catch (ClassNotFoundException e) {
    System.out.println(e);
    return object;
    Let's say my class name is "Frame1".
    and then if i use:
    Frame1 frm = (Frame1) createObject("Frame1");
    everything is ok but i cannot do this because the name "Frame1" is a String variable called "name" and it doesn't work like:
    name frm = (name) createObject("Frame1");
    where i'm i mistaking?
    Thanks very much!

    i have understood what you have told me but here is a little problem
    here is how my test code looks like
    Class[] parameterTypes = new Class[] {String.class};
    Object frm = createObject("Frame1");
    Class cls = frm.getClass();
    cls.getMethod("pack",parameterTypes);
    cls.getMethod("validate",parameterTypes);
    everything works ok till now.
    usually if i would of had instantiated the "Frame1" class standardly the "cls" (or "frm" in the first question ) object would be an java.awt.Window object so now i can't use the function (proprietary):
    frame_pos_size.frame_pos_size(frm,true);
    this function requires as parameters: frame_pos_size(java.awt.Window, boolean)
    because my cls or frm objects are not java.awt.Window i really don't find any solution for my problem. I hope you have understood my problem. Please help. Thanks a lot in advance.

  • 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 "i++;" thread-safe?

    I got a problem? Look the class below.
    =============================
    public class AQuestion
        private int i=0;
        public void inc()
            i++;
    ==============================
    Is the method inc() thread safe?
    What I mean is that is the single line code "i++;" thread safe?

    I&nbspwrote&nbspa&nbsptest&nbspas&nbspbelow.
    ===============================================
    public&nbspclass&nbspThreadSafeTest
    &nbsp&nbspprivate&nbspstatic&nbspint&nbspthreadCount=100;
    &nbsp&nbspprivate&nbspstatic&nbspfinal&nbsplong&nbsploopCount=100L;
    &nbsp&nbsp//private&nbspstatic&nbspint&nbspthreadCount=1000;
    &nbsp&nbsp//private&nbspstatic&nbspfinal&nbsplong&nbsploopCount=1000000L;
    &nbsp&nbspprivate&nbspstatic&nbspint&nbspfinishedThreadCount=0;
    &nbsp&nbspstatic&nbspsynchronized&nbspvoid&nbspthreadFinished()
    &nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbspfinishedThreadCount++;
    &nbsp&nbsp}
    &nbsp&nbsppublic&nbspstatic&nbspvoid&nbspmain(String[]&nbspargs)
    &nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbspfinal&nbspIncObj&nbsptt=new&nbspIncObj();
    &nbsp&nbsp&nbsp&nbsplong&nbspstart=System.currentTimeMillis();
    &nbsp&nbsp&nbsp&nbspfor(int&nbspi=0;i<threadCount;i++)
    &nbsp&nbsp&nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbspnew&nbspThread()
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsppublic&nbspvoid&nbsprun()
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspfor(long&nbspj=0;j<loopCount;j++)tt.inc();
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspthreadFinished();
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp}
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp}.start();
    &nbsp&nbsp&nbsp&nbsp}
    &nbsp&nbsp&nbsp&nbspwhile(finishedThreadCount<threadCount)
    &nbsp&nbsp&nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsptry{
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspThread.sleep(200L);
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp}catch(Exception&nbspe){
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspe.printStackTrace();
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp}
    &nbsp&nbsp&nbsp&nbsp}
    &nbsp&nbsp&nbsp&nbsplong&nbspend=System.currentTimeMillis();
    &nbsp&nbsp&nbsp&nbspSystem.out.println("All&nbspsub&nbspthreads&nbspfinished&nbspafter&nbsp"+(end-start)+"&nbspmillisecond");
    &nbsp&nbsp&nbsp&nbspSystem.out.println("the&nbspexpected&nbspresult&nbspis&nbsp"+threadCount*loopCount);
    &nbsp&nbsp&nbsp&nbspSystem.out.println("the&nbspreal&nbspresult&nbspis&nbsp"+tt.get());
    &nbsp&nbsp}
    class&nbspIncObj
    &nbsp&nbspprivate&nbspint&nbspi=0;
    &nbsp&nbsp//public&nbspsynchronized&nbspvoid&nbspinc()
    &nbsp&nbsppublic&nbspvoid&nbspinc()
    &nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbspi++;
    &nbsp&nbsp}
    &nbsp&nbsppublic&nbspint&nbspget()
    &nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbspreturn&nbspi;
    &nbsp&nbsp}
    ===============================================
    My&nbspprogram&nbspruns&nbspon&nbspintel&nbspPentiumIII&nbsp500Mhz&nbsp+&nbspwindows&nbspXP&nbsphome&nbspEdition&nbsp+&nbspj2sdk1.4.0&nbsp
    the&nbspresult&nbspis&nbspas&nbspbelow.
    ===============================================
    All&nbspsub&nbspthreads&nbspfinished&nbspafter&nbsp241&nbspmillisecond
    the&nbspexpected&nbspresult&nbspis&nbsp10000
    the&nbspreal&nbspresult&nbspis&nbsp10000
    ===============================================
    but&nbspwhen&nbspI&nbspcommented&nbsp
    &nbsp&nbspprivate&nbspstatic&nbspint&nbspthreadCount=100;
    &nbsp&nbspprivate&nbspstatic&nbspfinal&nbsplong&nbsploopCount=100L;
    into&nbsp
    &nbsp&nbspprivate&nbspstatic&nbspint&nbspthreadCount=1000;
    &nbsp&nbspprivate&nbspstatic&nbspfinal&nbsplong&nbsploopCount=1000000L;
    the&nbspresult&nbspis&nbspbecomes
    ===============================================
    All&nbspsub&nbspthreads&nbspfinished&nbspafter&nbsp345717&nbspmillisecond
    the&nbspexpected&nbspresult&nbspis&nbsp1000000000
    the&nbspreal&nbspresult&nbspis&nbsp785277617
    ===============================================
    when&nbspI&nbspcomment&nbsp
    &nbsp&nbsppublic&nbspvoid&nbspinc()
    into
    &nbsp&nbsppublic&nbspsynchronized&nbspvoid&nbspinc()
    the&nbspperformance&nbspbecomes&nbspunbearable.
    Can&nbspI&nbspget&nbspthe&nbspconclusion&nbspthat&nbsp"i++"&nbspis&nbspnot&nbspthread&nbspsafe?

Maybe you are looking for

  • Adobe acrobat pro 9 and windows 8 issues

    Looking for help regarding adobe acrobat 9 and windows 8.  I am unable to scan will  not allow me to select devise (HP officejet pro 8500 wireless).  Also unable to scan from HP device to PDF using HP solution center.  Printing fine from other applic

  • Path selection question for an image of neurons

    I have a photo of neurons taken by a microscope as a TIFF.  I'd like to remove the black background color and any "cloudiness" that appears in the photo but still maintain the detail of the neurons and the connections.   Essentially, I'd like to chan

  • IPhone - disable spell check for a single input

    I've got an HTML form and I want to disable the spell check on one of the inputs. How do I do that?

  • Does iPhoto support RAW for Fuji X-S1?

    I just bought a Fuji X-S1 to use as a safari camera. I'm experimenting with it and was not able to get iPhoto to import RAW files. Any suggestions?

  • 2 gateway, How to use it in "TMG"? help

    I have two providers for internet: 1- ADSL 2- FiberLine I want to make group of users be on the Fiber line, remaining on the ADSL line. Using forefront TMG>>>>> by use ISP Redundancy or other, I don't care, it is important to identify each user on li