Thread safe - again

Hi guys,
If I have 2 threads
Thread one = new Thread();
Thread two = new Thread();
In each Thread (one, two) in run method, I new a class called MyClass
public class myClass
public int a;
public int b;
public int geta()
return a;
public int getb()
return b;
public void seta(int x)
this.a = x;
public void setb(int y)
this.b = y;
Is this thread safe. My result is not a thread safe. Does these 2 thread access the same memory block of myclass? I am really confused now.
Thanks

I agreed with the previous reply that the two myClasses shouldn't share the memory. But there are still many factors which may let them actually share the memory, such as you are actually implementing the two threads by putting the two myClasses into same variable (like static). Anyway, I think it is better for you to post how you create and store those classes in here. Then a clear reason and solution will come out.

Similar Messages

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

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

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

  • Thread-safe Singleton

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

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

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

  • Java.util.Locale not thread-safe !

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

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

  • Trying to understand "thread-safe" w/ swing components

    The other day there was a big hullabaloo about some code I posted because I was calling JLabel.setText from a thread that wasn't the ui thread. On the other hand, this thread was the only thread making changes to the JLabel. My understanding is that in any kind of multi-threaded system, if you just have 1 writer / changer, then no matter how many readers there are, this is thread-safe. So why what I was doing not thread safe?
    Second question - JLabel.setText() is essentially setting data in the model for JLabel, which then gets picked up and displayed the next time the GUI thread paints it. So if it's not safe to update a JLabel's model, I assume its never safe to update any data that also is being displayed visually. So for instance, if I was showing some database table data in a JTable, I should do the update in the UI thread - probably not. But what is the distinction?
    Third question - what swing components and what operations need to be run on the UI thread to call your program "thread-safe". Validate? setSize()? setLocation()? add? remove? Is there anything that can be called on swing components from a non-ui thread?
    Edited by: tjacobs01 on Nov 2, 2008 8:29 PM

    tjacobs01 wrote:
    My understanding is that in any kind of multi-threaded system, if you just have 1 writer / changer, then no matter how many readers there are, this is thread-safe. So why what I was doing not thread safe?This is not true. As I mentioned in that hullabaloo thread, the Java Memory Model allows threads to cache values of variables they use. This means that values written by one thread are not guaranteed to ever be visible to other threads, unless you use proper synchronization.
    Take the following example:
    import java.util.concurrent.TimeUnit;
    public class ThreadExample {
        static class Foo {
            private String value = "A";
            public String getValue() {
                return value;
            public void setValue(String value) {
                this.value = value;
        public static void main(String[] args) {
            final Foo foo = new Foo();
            Thread writer = new Thread() {
                @Override
                public void run() {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                        foo.setValue("B");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
            Thread reader = new Thread() {
                @Override
                public void run() {
                    try {
                        TimeUnit.MINUTES.sleep(1);
                        System.out.println(foo.getValue());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
            writer.start();
            reader.start();
    }Here two different threads both access the same Foo instance, which is initialized with a value of "A". One thread, the writer, sleeps one second, and then sets foo's value to "B". The other thread, the reader, sleeps one minute (to avoid race conditions) and then prints foo's value to System.out. It may seem obvious that the reader thread will read the value "B", but this is in fact not guaranteed to be true. The reader thread may never see the value that was written by the writer thread, so it may very well read the old value "A".
    (If you run the code you will probably see "B" printed out, but again, this is not guaranteed behavior.)
    A simple way to fix this is to synchronize access to the mutable state that the two threads share. For example, change the class Foo to
        static class Foo {
            private String value = "A";
            public synchronized String getValue() {
                return value;
            public synchronized void setValue(String value) {
                this.value = value;
        }It's for this same reason that you often see the use of a volatile boolean as a control flag for stopping threads, rather than a plain old boolean. The use of volatile guarantees that the thread you want to stop actually sees the new value of the flag once it has been set by another thread.
    Here is an article that touches some of this stuff:
    [http://www.ibm.com/developerworks/java/library/j-jtp02244.html]
    I also highly recommend the book "Java Concurrency in Practice" (one of the authors of which, David Holmes, sometime hangs out on the Concurrency forum here, I believe).
    Edited by: Torgil on Nov 2, 2008 9:01 PM

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

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

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

  • Are CacheStore's and BackingMapListener's thread safe?

    I'm implementing a JMS CacheStore and have a quick question: does Coherence ever attempt to run multiple threads concurrently across a CacheStore instance on a given node?
    Reason I ask is that only certain objects are thread-safe in the JMS spec.: Connection Factories, Destinations (i.e. a Queue) and Connections. However Sessions, Producers and Consumers are not.
    In order to improve performance, it's recommended (obviously) to try and reuse Sessions/Producers and not recreate them for every message sent. So I'd like to declare them as instance variables in my class and assign them once-only at construction time.
    I just wanted to make sure that this would be OK (i.e. Coherence would start multiple threads running across my CacheStore). Anyone any ideas?
    (NB. I'm using JMS Connection Pooling to get around this issue at the moment - as the pools are thread-safe and I can close/open them quickly as many times as I like - but this is not a part of the JMS standard, so I end up using vendor-specific classes which I'd rather not do. Likewise I could make many of these non-thread-safe objects use ThreadLocals, but this all seems a bit overkill if it isn't actually required...)
    An other issue... :)
    What about closing the connection when it's finished with? Again, it's JMS recommended best-practice to do so. How is this best accomplished, seem as though it was Coherence that created the CacheStore instance and my client code has no reference to it? Best I can think of for now is have a static method in my CacheStore class that is kicked off via an invocation-service agent. Again, if anyone has a better idea I'm all ears.
    An other issue... :)
    Does the same thread-safety hit BackMapListeners? The "receiving" end of my JMS messages is a BackingMapListener based on the Incubator Commons "AbstractMultiplexingBackingMapListener" class. So, does Coherence ever kick off multiple threads across a single BackingMapListener instance, or can I safely have the JMS Session and Consumer left open after construction as class-level members?
    Cheers,
    Steve

    stevephe wrote:
    True... But I was rather hoping I could just get someone from Oracle who wrote the stuff to comment instead! :) Don't really want to second-guess this, as there could always be unusual corner-cases that could be difficult to replicate. Still...
    I did a bit more testing on my CacheStore this morning. I removed the non JMS-standard "pooling" and just created instance variables for only those items which I know to be thread-safe (ConnectionFactory, Connection and my target queue, a "Destination" in JMS terminology) I now re-get the Session and Producer in each Cachestore method. This makes the code thread-safe and portable. TBH, it hasn't affected performance too much, so I'll leave it as it is for now (and I've put a comment in the code stating that people could move these things to ThreadLocal's if they wanted to further boost performance in their own usage cases and still keep the CacheStore thread-safe.)
    As regards the "receiving" end of these published messages, my BackingMapListener does nothing more than register a JMS MessageListener and a "connection.start()" call. This is a very short, one-off call, so shouldn't leave Coherence service threads "hanging" on anything for extended periods.
    Cheers,
    SteveHi Steve,
    to cut things short:
    1. Coherence instantiates one cache store per read-write-backing-map, therefore it needs to be thread-safe if you have a thread-pool or use write-behind.
    2. If you don't have write-behind then Coherence uses the worker thread to execute the cache store operations.
    3. If you have write-behind then generally Coherence uses the write-behind thread (this is a separate thread per write-behind-configured service) to execute the cache store operations, except for erase[All]() operations on cache.remove() or batch remove which cannot be delayed due to consistency reasons and are executed on the worker thread.
    If you don't have a thread-pool, replace worker thread with service thread.
    I don't know off my head where the refresh-ahead operation executes.
    There is a single backing-map-listener per backing map instantiated, therefore it needs to be thread-safe. BackingMapManagerContext is thread-safe, so there is no issue with sharing it across multiple threads executing on a backing-map-listener.
    Best regards,
    Robert

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

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

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

  • Repaint() is not thread-safe?

    I saw a description that says repaint() is thread-safe in an old swing tutorial, but not in the current tutorial and its javadoc. So can I assume repaint() is not thread-safe and I should call it from EDT? ... Or if they are thread-safe, why does Sun not document it?

    repaint() calls paint() on EDT... but it calculates dirty region on the current thread and does not get AWTTreeLock.I don't think so.
    repaint() is a java.awt.Component method and doesn't know about Swing's RepaintManager and dirty regions. There may be somthing similar at the AWT level that escaped me, but looking at the JDK1.6 source code, java.awt.Component.repaint() just repaints the whole component.
    Now repaint(long, int, int, int, int) has two versions.
    At the AWT level, it just posts a paint event for the specified region. No race condition, and no risk that he region be wrong, but possibility to invoke multiple paint(Graphics) that overlap, that is, to paint several times the same area - it may be an optimization problem, but it doesn't jeopardize the consistency of the drawing.
    At the Swing level, it does compute dirty regions. In Repaint manageer, the call to extendDirtyRegion(...) is protected within a synchronized block, but the code before that is not. From a quick look, that code is:
    1) walking up the component hierarchy to find the root, which may not be thread-safe, but a well-behaved application shouldn't change the hierarchy from outside the EDT.
    2) walking up a chain of "delegate" RepaintManager, which I knew nothing about... Apparently it's a sun's implementation specific construct, each JComponent can be assigne d a delegate RepaintManager. Again I would claim that such things should not happen outside of the EDT, but I haven't found documentation about this.
    Edited by: jduprez on Jul 20, 2009 2:37 PM
    so no, technically, I can't prove repaint(long, int,int,int,int) is thread-safe.
    But a well-behaved application that updates its widgets on the EDT shouldn't worry (that is, repaint(...) calls can still be invoked outside of the EDT).
    Edited by: jduprez on Jul 21, 2009 7:04 PM - typos

  • Are queries thread-safe ? (continued)

    Hi
    In a previous thread on this topic, it was said that a query can be reused, and why it was good on performance. But a reusable object is not necessarily thread-safe.
    So I ask again. Are queries thread-safe ?
    What about Expressions ?
    Thanks
    JCG

    Yes, they're thread safe, both expressions and Queries. TopLink makes copies of whatever parts of the Query/Expression are needed to be changes in parallel.
    - Don

  • Is JSF Page thread safe

    Hi ,
    I was wondering if JSF page is thread safe
    Okay here is my scenarion.
    1. in order to prevent some of the value get re instatiate when the page rendered i declared some of them as static.
    However i make some checking if the Page is accessed for the first time , it will set this static object back to Null , if it is a postback it will hold current value which i assign.
    The question is ,
    1. i have two or three user performing concurrent request will it be a problem ????
    2. i notice when i destroy / invalidate the SessionBean. ( user logout scenario ) .
    When the user login again , why the static variable still holding the same value . i thought the page should be destroyed?? ( Thats why i check if the page is accessed for the first time , i will set all my object to null ).
    Thanks.

    The JSP will we translated to a servet by the application server, and therefore will run as a servlet. Servlets are not thread safe, you'll have to elaborate synchronized code blocks to allow one thread in the critical code, wich in turn has it's drawbacks.
    Best regards
    Antonio.

  • What is "Thread Safe"?

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

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

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

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

Maybe you are looking for

  • How do i get my pictures back on my iphone after restoring and backing up my iphone

    hod do i get my pictures back on my iphone after restoring and backing up my iphone?

  • Background color of Pageheader

    Hi all, I searched on the standard documentation and several threads here, but I didn't find any reply to this specific problem. I need to change the background color of the Pageheader of a WDA modifying somehow a custom theme in the MIME Repository.

  • Itunes error on my laptop

    I have been experiencing problems with itunes on my laptop, I have uninstalled and installed it numerous times and it still doesn't wanna work. Any suggestion may be that I could try?

  • How do I cancel an automatic renewal magazine

    I keep getting charged every month for a few magazines that are automatically renewing. I would like to cancel this but it seems IMPOSSIBLE! Please help..

  • Newsletter help!

    Hello, I am creating a newsletter that has 3 columns and I am trying to make the text lines up at the bottom of each column, so that it is a straight line across and looks neat. Does anyone know how to do that? Thanks, Molly