Immutable Objects in multi threaded application - how does it works?

Hi
I have this code will work in multithreaded application.
I know that immutable object is thread safe because its state cannot be changed. And if we have volatile reference, if is changed with e.g.
MyImmutableObject state = MyImmutableObject.newInstance(oldState, newArgs); i.e. if a thread wants to update the state it must create new immutable object initializing it with the old state and some new state arguments) and this will be visible to all other threads.
But the question is, if a thread2 starts long operation with the state, in the middle of which thread1 updates the state with new instance, what will happen? Thread2 will use reference to the old object state i.e. it will use inconsistent state? Or thread2 will see the change made by thread1 because the reference to state is volatile, and in this case thread1 can use in the first part of its long operation the old state and in the second part the new state, which is incorrect?
Therad1:                                                  Thead2:
State state = cache.get();     //t1                  
Result result1 = DoSomethingWithState(state);     //t1    
                           State state = cache.get(); //t2
   ->longOperation1(state); //t1
                           Result result2 = DoSomethingWithState(state); //t2
                               ->longOperation1(state); //t2
   ->longOperation2(state);//t1
cache.update(result1);    //t1             
                               ->longOperation2(state);//t2
                           cache.update(result2);//t2
Result DoSomethingWithState(State state) {
   longOperation1(state);
   //Imaging Thread1 finish here and update state, when Thread2 is going to execute next method
   longOperation2(state);
return result;
class cache {
private volatile State state = State.newInstance(null, null);
cache.update(result) {
   this.state = State.newInstance(result.getState, result.getNewFactors);
get(){
return state;
}

Please don't cross post
http://stackoverflow.com/questions/6803487/immutable-objects-in-multi-threaded-application-how-does-it-work

Similar Messages

  • Multi-Thread application and common data

    I try to make a multi-Thread application. All the Threads will update some common data.
    How could I access the variable �VALUE� with the Thread in the following code:
    public class Demo {
    private static long VALUE;
    public Demo(long SvId) {
    VALUE = 0;
    public static class makeThread extends Thread {
    public void run() {
    VALUE++;
    public static long getVALUE() {
    return VALUE;
    The goal is to get the �VALUE� updated by the Thread with �getVALUE()�
    Thanks for your reply
    Benoit

    That code is so wrong in so many ways......
    I know you're just experimenting here, learning what can and can't be done with Threads, but bad habits start early, and get harder to kick as time goes on. I am going to give a little explanation here about what's wrong, and what's right.. If you're going to do anything serious though, please, read some books, and don't pick up bad habits.
    Alright, The "answer" code. You don't use Thread.sleep() to wait for Threads to finish. That's just silly, use the join() method. It blocks until the threads execution is done. So if you have a whole bunch of threads in an array, and you want to start them up, and then do something once they finish. Do this.
    for(int k=0; k<threads.length; k++) {
      threads[k].start();
    for(int k=0; k<threads.length; k++) {
      threads[k].join();
    System.out.println("All Threads Done");Now that's the simple problem. No tears there.
    On to the java memory model. Here where the eye water starts flowing. The program you have written is not guarenteed to do what you expect it to do, that is, increment VALUE some amount of time and then print it out. The program is not "Thread Safe".
    Problem 1) - Atomic Operations and Synchronization
    Incrementing a 'long' is not an atomic operation via the JVM spec, icrementing an int is, so if you change the type of VALUE to an int you don't have to worry about corruption here. If a long is required, or any method with more then one operation that must complete without another thread entering. Then you must learn how to use the synchronized keyword.
    Problem 2) - Visiblity
    To get at this problem you have to understand low level computing terms. The variable VALUE will NOT be written out to main memory every time you increment it. It will be stored in the CPUs cache. If you have more then one CPU, and different CPUs get those threads you are starting up, one CPU won't know what the other is doing. You get memory overwrites, and nothing you expect. If you solve problem 1 by using a synchronized block, you also solve problem 2, because updating a variable under a lock will cause full visiblity of the change. However, there is another keyword in java.. "volatile".. A field modified with this keyword will always have it's changes visible.
    This is a very short explaination, barely scratching the surface. I won't even go into performance issues here. If you want to know more. Here's the resources.
    Doug Lea's book
    http://java.sun.com/docs/books/cp/
    Doug Lea's Site
    http://g.cs.oswego.edu
    -Spinoza

  • Clarification of the handle/body idiom in multi threaded applications

    Hello
    As some DBXML classes use the handle-body idiom (handle/body idiom in some docs), could someone please clarify the consequences of that in a multi threaded application like a web container?
    For 100% Java people, like me, this is known in the Java world as 'programming towards interfaces', or as the Bridge pattern; which is seen as good practice.
    Let's take an example. The class XmlQueryContext is not thread safe, but it has a copy constructor. Imagine that your web application has one XmlQueryContext, that we never use in a query, but that we prepare only to be copied in new threads. Is it thus safe to instantiate various new XmlQueryContexts using that copy constructor in various new threads and use them simultaneously?
    Thank you
    Koen
    PS What I am really asking here is if somebody could please translate the following to Java parlé:
    A copy constructor is provided for this class. The class is implemented using a handle-body idiom. When a handle is copied both handles maintain a reference to the same body.

    As a Java user you do not have to worry about how the C++ copy constructors behave. In the Java API if a copy constructor exists for the object, then the copy constructor will copy all of the original object's data into a new object (XmlContainer is the one exception to this rule, generally one should not use that copy constructor at all). So in short, what you plan to do will work.
    Lauren Foutz

  • Menu Object; MANUAL option. What is this, and how does it work?

    What is this... and, how does it work? Can't find documentation on this.

    My knee-jerk reaction is, "are f'n kidding me?"... but, of course, you're not.
    I must say, that is an incredibly useless option. How would that 'option" differ from simply making a text object (or text/rectangle/image combo or group) and creating a link?
    What got me looking at this option was the hope to find some way to insert a dynamic "field" that could be used on a master page to display the current page title (of a page based on that master). Something similar to Word (and other applications) that you can enter information into a document property and then insert that information anywhere within the document by using a field code for that info. I don't know if there is an HTML code that could be used to accomplish this, in this case. Something that would refer to the page title.
    Thanks for the info none-the-less.

  • Would you give me some information about objective-c multi thread

    hello,
    I am studing objective-c multi thread, but have not enough information. would you give me some, please? Thanks very much!

    Have you tried the ADC pages: http://developer.apple.com/macosx/?
    Multi-threading can be a complicated business in any programming language, so good luck!

  • Would you give me some information about objective-c multi thread please

    hello,
    I am studing objective-c multi thread, but have not enough information. would you give me some, please? Thanks very much!

    Hello
    You rang at the wrong door.
    This forum is dedicated to AppleWorks, not to objective-c
    Yvan KOENIG (from FRANCE mercredi 9 août 2006 07:38:25)

  • Referenced objects : how does it work ?

    Hello
    I would like to design a table, with 2 rows.
    Within the first row, a combo modifies the content of the second colum regarding its value.
    I believe I should use referenced objects (under the Referenced Objects nod in hierarchie tab), because "A referenced object is an object that is added to a form only when it is required", but I do not understand how it works.
    I've added a subform to the tree "referenced objects" ; using javascript let me access this subform, but when previewing the code does not work
    would anybody point me a link/a doc out ?
    thanks a lot !

    You gotta throw use a bone here... How does what work? More info please.

  • Applications: How does OS X Know Which App to Reference a File to?

    I just got my new Macbook and while installing applications, a question I've had for a while came up again.
    How does OS X know to reference applications to certain file types?
    For example. I have a .avi I downloaded to watch, and downloaded VLC to watch it. I open the .dmg and drag/drop VLC to my Applications folder. Instantly, VLC appears in the "Open With" list for my .avi. How does it know to list it?
    My theories are:
    1. When dragging/dropping VLC, it's not just copying files, it's also doing some background stuff, including VLC telling OS X that it should be referenced for .avi files
    2. When I "Open With" a file, OS X looks at apps in my Applications folder and detects applicable ones in some manner.
    3. It's Voodoo magic.
    How does it work? I hope my question makes sense.
    Thanks!

    From what I understand, the second the .dmg is opened and VLC is seen by OS X as an application, Launch Services asks VLC what filetypes to associate it with, and adds that to the database? Then when I try to "open with" a .avi, it sees that .avi is associated with QuickTime, and now VLC too.
    that's right. inside the VLC application bundle there is a file called info.plist which contains among other things the info about which files VLC can handle. that file is consulted by the Launch services once it becomes aware of VLC being present in the system and that info is recorded in the launch services database. That's how it works with all applications. you can view this file if you want. control-click on VLC in finder and select "show package contents". in the new finder window that opens up go to Contens folder and quicklook the file info.plist.
    Is this correct?
    Thanks.

  • Java Security Manager in Multi-threaded application

    I am writing a multi-threaded application listening (TCP and UDP) to several ports. To help implement certain security features (eg. refusing connections from certain ip address), I'm using the java.lang.SecurityManager (by subclassing it). I am having a few problems and queries and am hoping someone here can help me.
    1. As all the threads are calling the checkAccept(host, port) method. Is there a way to know which thread is currently accessing the security manager? For example if host A were to make 2 connections to the application, one to thread 1 (say listening to port 5001) and the other to to thread 2 (say listening to port 5002). I intend to refuse the connection to thread 2 but there is not way of differentiating the 2 connections since they are from the same host and there isnt any way of knowing their port number.
    2. Are calls to the Security Manager thread safe?
    I have been having this problem for a long time, would appreciate if someone can help point me to the right direction. cheers.

    1. As all the threads are calling the
    checkAccept(host, port) method. Is there a way to
    know which thread is currently accessing the security
    manager?Just use Thread.currentThread(). As specified in the Javadoc for e.g. SecurityManager.checkAccept().
    2. Are calls to the Security Manager thread safe? No.

  • How does QoS work with WAAS WCCP? What's the interaction between QoS Traffic Classification and WAE Traffic Application Policy?

    How does QoS work with WAAS WCCP? What's the interaction between Router QoS Traffic Classification and WAE Traffic Application Policy?

    By default, WAAS preserves the DSCP marking on intercepted packets.  There is a configuration option to set/override the DSCP value at the global (device), application, and classifier levels.  Currently WAAS provides marking only.  There is no action taken by WAAS based on the DSCP value.
    Regards,
    Zach

  • FAQ: How does GroupPix work?

    FAQ: How does Grouppix work?
    Answer:
    GroupPix is an iPhone app that automatically collects photos taken by you and friends that you invite. It lets you comment on and automatically share photos with others. Everyone participating in a GroupPix group album needs to install and use the GroupPix app. You can download it for free from the App Store. Provided everyone has a good network signal, all the photos -- either taken with the built-in GroupPix camera, or added via the camera roll -- can be shared with everyone else in the group event. Leave comments and vote for favorites to add a fun social angle to the event!
    Related: read the thread about how to invite others to use GroupPix.

    By default, WAAS preserves the DSCP marking on intercepted packets.  There is a configuration option to set/override the DSCP value at the global (device), application, and classifier levels.  Currently WAAS provides marking only.  There is no action taken by WAAS based on the DSCP value.
    Regards,
    Zach

  • How does this work?

    This is not a complaint, but a confused sigh of admiration. I've got an email account at the university where I teach. When I got my iBook, it took me a while, and a few conversations with IT at the school, to get this account working in the Mail application. (Since I have a Verizon DSL at home, I had to include that SMTP as the outgoing server.) Anyway, I synched this mail account (along with my AOL and .Mac accounts) onto the iPhone, and it works perfectly, both incoming and outgoing. I didn't have to change any of the settings. I thought I was computer savvy, but I can't wrap my mind around this. It seems like magic. How does it work?

    The sync process with iTunes transfers the email account settings (for your chosen accounts via your iPhone sync preferences) from the Mail application on your Mac to the iPhone's email application.
    The iPhone is running OS X and the iPhone's email client can be considered a mobile version of the Mail application.

  • TS1425 My co worker has given me his iPod to take home and transfer his music to my laptop, however, I am unable to access his music to download it to my computer.  How does this work?

    My co-worker has given me his iPod to take home and transfer his music to my laptop, however, I am unable to access his music to download it to my computer.  How does this work?

    You need to transfer the iTunes Library from the most recent backup you made before the hard drive was replaced.
    You can't transfer the full iTunes Library from the iPad back to iTunes.
    There are third-party Windows applications that will transfer data from an iOS device, but they don't re-create the iTunes Library exactly as it was before.

  • What is UMA exactly? How does it work?

    What is UMA exactly? How does it work?
    I have T Mobile but am not subscribed to Hotspots at Home.  I do pay for the BB unlimited internet package.
    When I am connected to my router at home, it goes to UMA.  But other times, it just says wifi and is still connected to my router -- but NO UMA.  I haven't made any changes.
    What is this?

    Here is a KB that discusses UMA:
    http://www.blackberry.com/btsc/microsites/search.do?cmd=displayKC&docType=kc&externalId=KB11735&slic...
    Hope that helps!
    Occam's Razor nearly always applies when troubleshooting technology issues!
    If anyone has been helpful to you, please show your appreciation by clicking the button inside of their post. Please click here and read, along with the threads to which it links, for helpful information to guide you as you proceed. I always recommend that you treat your BlackBerry like any other computing device, including using a regular backup schedule...click here for an article with instructions.
    Join our BBM Channels
    BSCF General Channel
    PIN: C0001B7B4   Display/Scan Bar Code
    Knowledge Base Updates
    PIN: C0005A9AA   Display/Scan Bar Code

  • How does tagging work?

    I see there is a show by tags feature in the ios app. How does tagging work?

    On the N96, fire up the camera, then:
    Options > Settings > Record location > On
    You can't see the position on Google maps but you can on Nokia Maps. When viewing a location-tagged image in the gallery view application, simply do Options > Show on map.
    Was this post helpful? If so, please click on the white "Kudos!" star below. Thank you!

Maybe you are looking for

  • Problem with HDMI - external display resolution (MacBook andSamsung HDTV)

    I just bought a new MacBook, and I have used my Samsung HDTV (http://www.amazon.com/Samsung-LN-S2338W-widescreen-720p-HDTV/dp/B000G6300U) with my old MacBook for over a year. First I tried to connect the two using the Mini Display Port to VGA adapter

  • Clone stamp not working in CS6

    Each time i try to use my actions is says"could not use the clone stamp because the area to clone has not been defined (option-click to define a source point)" or "unable to do ____". Any advice on how to fix this? Thanks!

  • Repeat regions not working in Contribute

    I've got a problem with repeat regions inside templated pages. When in contribute, I can't seem to add a new repeat region by clicking on the plus (+) button, although it works fine in dreamweaver. It isn't a permissions issue as far as I can tell, s

  • SL300 Dim Display

    Hi All I was searching the internet for possible solutions to my problem and found this board but couldn't find an answer to my problem. Basically, I have an SL300 and the screen is really dim. I can just see the image on the screen but there is no b

  • Multiple source files

    Hi, My client has given me two files for HEADER and ITEM as source and receiver has only one structure . can anyone guide my how to  proceed with mapping .Please help me FULL POINTS WILL BE AWARDED thank u Bhasker