I am trying to understand the thread safety mechanism in java and I need help. I have a class:
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 < 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()); } } } }
Here I am trying to make the value stream safe, accessed by only one stream at a time. When I run this program, I see that there is more than one thread in value , even if I wrap it in a synchronized block. Of course, this loop will be infinite, but this is just an example, I will stop this program manually after a few seconds, so I have:
2470 Thread[pool-1-thread-3,5,main] 2470 Thread[pool-1-thread-5,5,main] 2470 Thread[pool-1-thread-2,5,main]
Access to various streams and their change value . Can someone explain to me why this is so? And how to make this global variable thread safe?
user2219247
source share