Note that there are some explanatory texts on larger screens.

plurals
  1. POThread safe global variable in Java
    primarykey
    data
    text
    <p>I am trying to understand the thread safety mechanism in java and I need some help. I have a class:</p> <pre><code>public class ThreadSafe { private Executor executor = new ScheduledThreadPoolExecutor(5); private long value = 0; public void method() { synchronized (this) { System.out.println(Thread.currentThread()); this.value++; } } private synchronized long getValue() { return this.value; } public static void main(String... args) { ThreadSafe threadSafe = new ThreadSafe(); for (int i = 0; i &lt; 10; i++) { threadSafe.executor.execute(new MyThread()); } } private static class MyThread extends Thread { private ThreadSafe threadSafe = new ThreadSafe(); private AtomicBoolean shutdownInitialized = new AtomicBoolean(false); @Override public void run() { while (!shutdownInitialized.get()) { threadSafe.method(); System.out.println(threadSafe.getValue()); } } } } </code></pre> <p>Here I am trying to make the <code>value</code> thread safe, to be accessed only by one thread at a time. When I am running this program I see that there is more than one thread operating on the <code>value</code> even if I wrap it within the <code>synchronized</code> block. Of course this loop will be infinite but its just an example, I am stopping this program manually after few seconds, so I have:</p> <pre><code>2470 Thread[pool-1-thread-3,5,main] 2470 Thread[pool-1-thread-5,5,main] 2470 Thread[pool-1-thread-2,5,main] </code></pre> <p>Different threads are accessing and changing this <code>value</code>. Can somebody explain to me why is this so? And how to make this global variable thread safe?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload