Why threads do not cache object locally?

HeyAlex

I have a String and ThreadPoolExecutor that changes the value of this String. Just check out my sample:

String str_example = "";     
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10, 30, (long)10, TimeUnit.SECONDS, runnables);
    for (int i = 0; i < 80; i++){
        poolExecutor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep((long) (Math.random() * 1000));
                    String temp = str_example + "1";
                    str_example = temp;
                    System.out.println(str_example);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

so after executing this, i get something like that:

1
11
111
1111
11111
.......

So question is: i just expect the result like this if my String object has volatile modifier. But i have the same result with this modifier and without.

Andrey Cheboksarov

There are several reasons why you see "correct" execution.

First, CPU designers do as much as they can so that our programs run correctly even in presence of data races. Cache coherence deals with cache lines and tries to minimize possible conflicts. For example, only one CPU can write to a cache line at some point of time. After write was done other CPUs should request that cache line to be able to write to it. Not to say x86 architecture(most probable which you use) is very strict comparing to others.

Second, your program is slow and threads sleep for some random period of time. So they do almost all the work at different points of time.

How to achieve inconsistent behavior? Try something with for loop without any sleep. In that case field value most probably will be cached in CPU registers and some updates will not be visible.

P.S. Updates of field str_example are not atomic so you program may produce the same string values even in presense of volatile keyword.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Why do we need locks for threads, if we have GIL?

Why do locally declared primitives goes to the stack while locally defined objects goes to the heap?

Why do we need to use threads for running Kafka consumers? And how many threads do we need?

Why do we need to install gulp globally and locally?

Why do threads share the heap space?

Why do threads spontaneously awake from wait()?

Why is guava's Cache.invalidate(Object key) method not generic?

Why do we need a Runnable to start threads?

How do I mock a locally created object?

Why does using the same cache-line from multiple threads not cause serious slowdown?

How do I share a mutable object between threads using Arc?

Why do we really need multiple netty boss threads?

Why do native threads behave different when app is in background?

Do multiple threads Using the same object in java make a copy of it?

Why do my jest tests run locally, but not on Travis?

Why do modules sometimes raise an UnboundLocalError when imported locally?

Why do some MySQL threads never die?

Where to cache files locally

Why do threads seem to execute randomly?

Is there a way to cache map locally

Why do my threads not run in parallel using Java ExecutorService?

Why do I have 3 threads here?

Why is NullReferenceException being returned when trying to add an object to my cache?

Why do these threads stop working?

Why object is created using apt.Cache rather than apt.cache.Cache()

Why is my `StandardOleMarshalObject` COM Object called from multiple threads?

why do these mysql queries run differently locally and on stage?

Why do these threads not execute in the same order as the code?

Why do all threads always take the same time, why does the OS run all threads "in parallel"?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive