Can anyone explain to me what the benefits and and drawbacks of the two different approaches are?
|
Possibly similar question:
http://stackoverflow.com/questions/106591/
Today I was debugging my game; It had a very difficult threading problem that would show up every few minutes, but was difficult to reproduce. So first I ... |
Reading a few threads (common concurrency problems, volatile keyword, memory model) I'm confused about concurrency issues in Java.
I have a lot of fields that are accessed by more ... |
Consider the following Java code:
volatile boolean v1 = false;
volatile boolean v2 = false;
//Thread A
v1 = true;
if (v2)
System.out.println("v2 was true");
//Thread B
v2 = true;
if (v1)
System.out.println("v1 ...
|
Does the out variable in the MyThread class need to be declared volatile in this code or will the "volatility" of the stdout variable in the ThreadTest class carry over?
import java.io.PrintStream;
class ...
|
I have read "When to use 'volatile' in Java?" but I'm still confused. How do I know when I should mark a variable volatile? What if I get it ... |
I came across this statement:
In properly constructed objects, all
threads will see correct values of
final fields, regardless of how the
object is published.
Then why a ... |
|
If I have the following
private volatile Collection<Integer> ints;
private void myMethod()
{
for ( Integer i : ints )
{
...
}
}
The ... |
Use of volatile only makes sense in multiprocessor systems. is this wrong?
i'm trying to learn about thread programming, so if you know any good articles/pdfs ... i like stuff that mentions ... |
By referring article, it is using a pair of volatile to prevent out-of-order execution. I was wondering, is it possible to prevent it using single volatile?
void fun_by_thread_1() {
...
|
Based on
What does volatile do? http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#incorrectlySync
and
New guarantees for volatile http://www.ibm.com/developerworks/library/j-jtp03304/
class VolatileExample {
int x = 0;
volatile boolean v = false;
...
|
Okay, suppose I have a bunch of variables, one of them declared volatile:
int a;
int b;
int c;
volatile int v;
If one thread writes to all four variables (writing to v last), and another ... |
I was just wondering if someone could explain the meaning of this:
Operations like increment and
decrement (e.g. ++ and --) can't be
used on a volatile ... |
I have a multithreaded program that loads its configuration on startup. The configuration is then handed down to the threads via their constructors.
But now I want to load one new config ... |
|
Hi I have build an example to understand the behaviour of volatile variables but it is working just like an instance variable. I am not able to understand the behaviour of volatile variable. I will be glad and thankfull if you explain me how i can take advantage of volatile variables and how i can see the bahaviour. An example with ... |
17. volatile coderanch.comConsider the class: public class SerialNumberGenerator { private static volatile int serialNumber = 0; public static int nextSerialNumber() { return serialNumber++; } } ///:~ "The serialNumber field is volatile because it is possible for each thread to have a local stack and maintain copies of some variables there. If you define a variable as volatile, it tells the compiler not to ... |
Hi all, I know that you need to use volatile modifier if the variable is being used by two or more threads simultaneously. But in an example even if I am not using volatile and if i change that variable it gets notified into other thread. Does JDK 1.4 use other technoques to handle shared variables? BTW i m not using ... |
So what exactly happens when you declare a variable volatile?? a) load, store, read, and write actions become atomic even for double and long declarations b) a use action must have been preceded by a load action c) a store action must have been preceded by an assign action d) and as usual the main/shared memory has to service the requests ... |
Originally posted by Henry Wong: It tells that compiler that this variable will be used by many threads at the same time. And not to create any cache copies, in the code that is compiled. Henry You don't think thats a too overly compiler centric answer? When you say compiler are you speaking of hotspot and JIT or something? I think ... |
I know that global variables are shared between threads. Consider the below code: public class Terminate { public static void main (String [] args) { ThreadB tb = new ThreadB (); ThreadA ta = new ThreadA (tb); tb.start (); ta.start (); } } class ThreadA extends Thread { private ThreadB tb; ThreadA (ThreadB tb) { this.tb = tb; } public void ... |
Threads can have their owned cached versions of variables, volatile forces the threads not to cache values declared volatile (they cache for speed), so declaring a variable means threads will always see the latest value but possibly at a cost of speed of access. Synchronization takes care of this for you and does the locking but obviously at the cost of ... |
There is one difference: the synchronized version will block if another thread holds a reference to the instance you're trying to access. If for some reason the other thread does not give up the reference, you can block forever. Admittedly in the code shown there's no apparent reason for another thread to do this, but it's possible. Also, if you consider ... |
I have a question about Object references and how they behave in a multi-threaded environment. Suppose I have the following class where one thread calls the constructor and another thread calls a(), is there a guarantee that the thread running a() always see the value of m_string as "hello"? public class T { private String m_string; public T() { m_string = ... |
This isn't easy to explain. In fact, it seems that this solution might in fact not work as expected. The problem is in subtle side effects of multi-threading - for optimization reasons, the processor is allowed to reorder operations, as long as the effect is the same *for the current thread*. Another effect is the use of memory that is local ... |
Would you really worry about the performance of updating/getting a boolean flag, whether it is volatile or Atomic? I would use an AtomicBoolean if i want to use a compareAndSet() so that i can assure that i *only* set a value if it is equal to something. However, i will use volatile if i want to make sure that while getting ... |
Immutable objects are not something specific to multi-threading. Any object, the state of which can not be changed after they are created (to be precise it only means the internal state of object governed by the instance variables and not any references to the object itself) is called immutable. Since, thread-safe code is something that *changes* modifies shared data in a ... |
Can anyone answer these questions: 1) Was the fix for volatile back-ported to 1.4 JVMs? 2) If the fix was not back-ported to 1.4 JVMs, is there an alternative idiom that can guarantee the same "happens-before" semantics (aside from standard synchronization)? Maybe something in the back-port of the Java 5 concurrency package? 3) Even more specifically, was the fix back-ported in ... |
Hi everybody, I am reading "Java Threads 3rd edition"(Oreilly). The book covers J2SE1.5 so it must also cover thread programming in the new JMM. In chapter5 at "The effect of reodering statements", there is an example code as shown below. public int currentScore, totalScore, finalScore; public void resetScore(boolean done){ totalScore += currentScore; if(done){ finalScore = totalScore; currentScore = 0; } } ... |
I read a document which say Volatile Modifiers, are not cached by the JVM. When ever a volatile variable value is required by a thread it will access directly from the variable itself (without using the JVM cache).. Volatile: Volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program. For ... |
This doesn't make much sense to me. I believe volatile means that the compiler will assume that the variable can be changed at any time. This prevents the compiler from maximally optimizing manipulations of this variable, but for good reason: safety. As far as I know, this has no effect on synchronization. What do you mean though by all of .... ... |
|
public class Volatile extends Object implements Runnable { private int value; private volatile boolean missedIt; // doesnt need to be volatile-doesnt change private long creationTime; public Volatile() { value = 10; missedIt = false; creationTime = System.currentTimeMillis(); } public void run() { print("entering run()"); // each time, check to see if value is different while ( value < 20 ) { ... |
Hi, I am trying to understand the usage of volatile variable. I was trying following code snippet. <-- code snippet start ---> package com.test; class VolatileExample extends Thread { private volatile int testValue; public VolatileExample(String str){ super(str); } public void run() { System.out.println("run method called"); for (int i = 0; i < 10; i++) { try { System.out.println(getName() + " : ... |
What exactly "volatile" does in this program. public class TestVol extends Thread { private volatile boolean stop; // There is no different with/without volatile public void run() { while (!stop) { System.out.println("run by: " + Thread.currentThread().getName()); } } public void toStop() { // when should I call the method "toStop" System.out.println("stop right now"); ttop = true; } public static void main(String[] ... |
public class Test implements Runnable { private static volatile int id = 4; public void run() { id = -4; } public static void setId(int idNew) { id = idNew; } public static void main(String[] args) { Runnable runner = new Test(); new Thread(runner).start(); setId(5); System.out.println("Id at this time is: " + id); } } |
|
The volatile keyword was introduced to the language as a way around optimizing compilers. Take the following code for example: class VolatileTest { boolean flag; public void foo() { flag = false; if(flag) { //this could happen } } } An optimizing compiler might decide that the body of the if statement would never execute, and not even compile the code. ... |
Hi folks, I was wonder if it is 'safe' to create a primitive array of ints say: int[] ints = new int[500]; ..//initialize all ints to 0. then access and increment the array values without any synchronization. I do NOT care if multiple threads read the same value, then increment/set, I want multiple threads to be able to access/update the array ... |
When using multiple processors, the value of a variable may be altered but not visible to other cores that may require the same variable. Marking a variable as volatile allows the compiler and runtime to prevent optimisations and improve the variable visibility so that errors are not introduced at runtime caused by this. Note that the restrictions caused by the volatile ... |
Hum... I don't think this question has something to do with the SCJD certification. So, let's slide this over to the Threads and Synchronization forum! Ah, and by the way, you just have to synchronize on objects that may be accessed by more than one Thread, and you have to do this in order to protect their state. So, I'd say ... |
The simple inaccurate answer is after every write they are written to main memory. The real answer is ... volatile doesn't guarantee to write to main memory at all , it doesn't have to and actually guarantees a lot more. Strictly volatile guarantees that a volatile write will "happen before" any subsequent volatile read and this covers a wide range of ... |
I try several examples (from Effective Java 2, Item 66, StopThread, and from Paul Hyde "Java Thread Programming", page 172, Volatile class). Those code fragments suppose to demonstrate that if you don't declare variable as volatile, the value can be (will be in specially constructed examples) different for different threads. (Visibility, compiler optimization, JIT, etc.) However, on Windows XP (where I ... |
Hi, I'm still not 100% sure about this and I'd like some input. When you read about the volatile keyword semantics you learn about its visibility effects. You also learn that volatile does not provide atomicity, but this observation is always made in the context of compound actions: you can't make n actions transactional using volatile like you can do so ... |
Hi Everybody, I have a question on the scope of volatile. If I have two classes MyObj and MyOtherObj. MyOtherObj is refered by MyObj. public class MyObj { public MyOtherObj myOtherObj = new MyOtherObj(); } public class MyOtherObj { public Boolean myBoolean= true; } And I have another class has a reference to MyObj with volatile attribute. Do I have to ... |