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

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

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

Similar Messages

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

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

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

  • RDBMS non-thread-safe issue

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

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

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

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

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

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

  • 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

  • Thread-safe dlls: re-entrant

    Hi!
    I've been trying to research on multi-threaded dlls w/ jni, & it seems every native method HAS TO BE synchronized. Unfortunately, my reqs call for native methods that are NOT ENTIRELY synchronized. The option I came across was TLS, although actually I was looking for better options. Then I found Roedy Green's advice that TLS was not even an option!
    Help! It seems that if native methods are NOT synchronized, any variable will be prone to being overwritten when multiple java objects call the method? My assumption is that native code is not translated into unique object space for each object since a dll is involved.
    TIA,
    Reggie

    Thanks again for your patience! Let me restate my
    problem: I need several instances of the same class
    running the same JNI code, w/c of course reside in a
    dll. I want my classes to be thread-safe, so I thought
    of using Thread-Local-Storage. Unfortunately, I found
    references on the web that JNI does not work w/ TLS.
    Neither can I simply "synchronized" the whole native
    method from java. Do I have other options?
    I still must not be precise enough.
    For java and C++ there are two types of variables (created various ways): single thread visible and multi-thread visible. For example:
    - Java/C++ static class variable (multi-thread visible)
    - Java/C++ member class variable (single thread visible)
    - Java/C++ local (method) variable (single thread visible)
    There are three interfaces to the variables:
    -Java only.
    -C++ only.
    -Java variables accessed in a JNI method.
    So there are six possible cases.
    1. Java only, single thread visible. Absolutely nothing you do will make these visible to other threads so there is never any point to synchronization
    2. C++ only, single thread visible. Again you can't see these in other threads so it doesn't matter.
    3. Java only, multi-thread visible. You have to synchronize these variables using java methods.
    4. C++ only, multi-thread visible. You have to synchronize these variable using C++ methods. Keep in mind that if you got to this point using java then you are still in a C++ thread - the jvm created it. The only problematic aspect is if the OS supports multiple thread models (Windows doesn't.) Then you have to determine the model to use the correct locking mechanism.
    5. JNI, single thread visible. Again you can't see these in other threads so it doesn't matter.
    6. JNI, multi-thread visible. In this case you need to create a java synchronization method in your C++ code. For example if you want to access a static variable of a java class in C++ you would have to synchronize it. In this case I would strongly recommend writing a java method and calling that instead. The synchronization code will be much easier to understand in java and it will significantly simplify the C++ code.
    Now the above cases should cover everything. If not you need to specifically tell me what is missing.

  • 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 XMLProcessor Thread Safe?

    I was wondering if the XMLProcessor.processXSL(xsl, null) method is thread safe?
    What if there were a single instance ( Singleton ), would it be able to handle multiple request without failing?
    Any help or direction would be of great help.
    null

    is vector thread safe ?
    is arraylist thread safe ?
    i want to use any one of thsese without
    Synchronised keyword
    Vector is synchronized but ArrayList is not. This means that two different threads cannot access the same method in a Vector at the same time. An ArrayList can easily be made synchronized and will then behave as a Vector.
    Now synchronized methods don't necessarily lead to thread-safe code. That depends on how the Vector/ArrayList is used. Have a look at the new concurrency package in Java 5. It contains lots of readymade collections with different behaviours. Maybe one will suit your needs and be thread-safe with your usage right out of the box.

  • Thread Safe Testing

    I havn't written much mult-threaded code but I realise it's important when many web round-trips are required.
    How do I design, test and verify that I have a thread-safe application? I don't like relying on the testing statistics of chance unless the odds of failure are 0.0001%!
    Is there a correct way to verify a thread-safe application?

    I agree it is a lofty, though sadly in all probability too time consuming, goal to achieve. However, there are a few pitfalls to watch out for that should get most of the common, pernicious thread safety issues:
    Synchronize data that must be shared. This will involved performance bottle-necks. If the data is read-mostly, consider a Singleton cache. Though pitfalls will always remain here. Data sharing among threads, IMO, is the single greatest issue.
    Use static methods and instances wisely. If an object has instance variables that are used from method to method call (either within the class or from the caller), then state exists for that object. It is inherently a candidate to look at in terms of thead-safety. This class should be created for each logical unit of work that depends on its state. So, do not reuse these classes among threads (or at least provide an init() or reset() method to clear the state). The same applies to static methods. You can safely use a static method from multiple threads if it does not modify other static variables (e.g., changing the state of a static variable).
    Within the Collections API, pay attention to which types are synchronized and which are not. The Javadocs will specify.
    Try to write methods thread-safe. Have them only use the arguments provided in the method's signature.
    Watch for relatively simple race conditions that can easily be spotted.
    static private Singleton INSTANCE;
    private Singleton() {
        super();
        // Now I will fetch values from a database, perhaps taking seconds
    static final public Singleton getInstance() {
          if (INSTANCE == null) {
             INSTANCE = new Singleton();  // what if this takes some time, e.g. database query to get cache values?
          return INSTANCE;
    }Not good. Here's a possible refactoring:
    private static final Singleton INSTANCE;  // bonus, we can now make it final
    static {
       INSTANCE = new SIngleton();  // Occurs only when class is loaded, atomic
    public static final Singleton getInstance() {
      return INSTANCE;  // no race condition
    }The above would be even more applicable and pronounced if you offered a static refresh() method on the instance, say to refresh its cache of data from a database.
    Seems easy, right? The rub is that you need to verify that a given method does not call other methods that are not thread-safe. If every class you design follows the above precepts, then you will probably only be chasing down rarer thread-safety issues.
    - Saish

  • Is Vector thread-safe in J2ME?

    I understand java.util.Vector is thread-safe in J2SE. How about in Vector in J2ME? I did not find any documentation about this.
    Any help is appreciated.

    is vector thread safe ?
    is arraylist thread safe ?
    i want to use any one of thsese without
    Synchronised keyword
    Vector is synchronized but ArrayList is not. This means that two different threads cannot access the same method in a Vector at the same time. An ArrayList can easily be made synchronized and will then behave as a Vector.
    Now synchronized methods don't necessarily lead to thread-safe code. That depends on how the Vector/ArrayList is used. Have a look at the new concurrency package in Java 5. It contains lots of readymade collections with different behaviours. Maybe one will suit your needs and be thread-safe with your usage right out of the box.

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

  • Guidlines for a "thread safe" library

    I am trying to use a 3rd party library for a communications board (ARINC).  I asked the vendor if the library is "thread-safe" since the application is multi-threaded.  He had indicated to me he didn't know how to create a thread-safe library.  Are there any guidelines i can give him to help him (and eventually me) to write a library that is thread-safe?.
    The application uses 5 threads to upload a program or data to a production unit via ARINC communications protocol. (Lane 1 program, Lane 2 program, Progress, Lane 1 cal, Lane 2 cal).  If any interruption occurs or a bad checksum in the data flow the unit will lockup and require disassembly and low level j-tag re-programming.

    Never Mind -
    The instrument driver development guide talks about thread protection that can be applied to a library.
    Moderator - Please close/delete this topic

  • WebServiceSoap_Stub - is it thread safe?

    Hi,
    Is the WebServiceSoap_Stub class thread safe, ie can it be used by multiple EJBs (threads) at the same time? I would say yes but a confirmation would be nice.
    Thanks!

    well, that assumes you are using thread-safe stream impls. i believe all the ones in the jvm are safe for this, but if you are using any custom streams, you'll have to check those out for yourself.

  • Synchronized use of System.out.println()

    So I am again at the point of part of my program running ahead of itself out of the call stack and ruining the sequence or order of printing.
    I read that System.out.println() is synchronized so how may it be used to wait() until notified to continue and not ruin the output?

    jverd wrote:
    Always Learning wrote:
    YES SIR EJP! SIR! I thank you for the assistance because using only System.out and synchronizing worked beautifully.You said you're not using multiple threads. If this is true, then there's no reason to synchronize anything. The output will appear on System.out in exactly the order you send it there.
    Nos if only I could figure out dependencies to make it work with out and err.You have to stop and think about it for a minute. You know that when you call println() on either one of those two streams, the output may be buffered an not necessarily go immediately to the console. From that you can reason that if you call out.println() first, and then err.println(), that you could end up with err's buffer getting flushed first, and the output appearing on the console in a different order than that in which your code executed the calls.
    You are of course not surprised by this, given that you know that out and err are completely independent and just happen to end up at the same destination in this particular case.
    So, as a first guess, you might reasonably think that, since buffering is obviously the culprit here, calling flush() on each stream after each print() or println() call should eliminate the problem. In a multithreaded environment, this wouldn't be sufficient, of course, but it's a logical approach to try here.
    Another tidbit to make note of is that the System class has setOut() and setErr() calls. Since you're looking at out and err in the same console, you presumably don't care about the distinction between them (which makes me wonder why you're using them both in the first place, instead of just using one). If you're just going to mush them together into the same console anyway, then you can use setOut() or setErr() to make them the same stream, and things will be ordered as you expect.Very interesting Jverd and I think there may yet be life in what I would like to do. I did not know or was not immediately aware of these things. I will give it a try.
    To answer your question, I am using them both because, like logging, they are distinct in the Eclipse console (black for out and red for err). With your patch I just tried that distinction has faded but the output is sequenced the same so I do appreciate you noting this. Learn something new in Java each time I am doing a project. I considered using logging and putting errors in a window but I am not sure if I should do that; just not enough experience with it.
    Edited by: Always Learning on Oct 23, 2011 9:28 AM

Maybe you are looking for

  • We have 2 Galaxy 4 phones that are exactly alike. They are 2-3 minutes different in the time. We share the same network.

    We have 2 Galaxy 4 phones that are exactly alike. They are 2-3 minutes different in the time. We share the same network.

  • Connection Time Out exception

    Hi All, I want to handle to Connection Time Out exception when displaying the BW Report in Portal. Please provide inputs. Also, is it possible to handle some look and feel of the BW Report from Portal itself. Regards Nikhil Bansal

  • Self repair apple cinema display 65W power adaptor?

    After a power outage, I have discovered that the 65W power adaptor (A1096 661-3760) driving a 20" apple cinema display is no longer working.  A different brick from another display works fine.  I was wondering whether I might be able to service this

  • Business place not found for plant 8149?

    Hi, I am facing the below mentioned problem with regard to Business Place with reference to Purchase order for Brazil. We are getting error while creating Purchase order."Business place not found for plant 8149" can any one has idea on this.. Thanks

  • Zen Micro screen doesn't wo

    The music plays and the backlite lights up, but the lcd pixels aren't working. I had a problem a couple of days ago where the lcd was messing up and looking real weird but after a while it sorted itself out. Now the lcd just doesn't work.