calling thread.start() within its own constructor [duplicate] - java

This question already has answers here:
Java: starting a new thread in a constructor
(3 answers)
Closed 6 years ago.
is it legal for a thread to call this.start() inside its own constructor? and if so what potential issues can this cause? I understand that the object wont have fully initialized until the constructor has run to completion but aside from this are there any other issues?

For memory-safety reasons, you shouldn't expose a reference to an object or that object's fields to another thread from within its constructor. Assuming that your custom thread has instance variables, by starting it from within the constructor, you are guaranteed to violate the Java Memory Model guidelines. See Brian Goetz's Safe Construction Techniques for more info.

You will also see wierd issues if the Thread class is ever further subclassed. In that case, you'll end up with the thread running already once the super() exits, and anything the subclass might do in its constructor could be invalid.
#bill barksdale
If the thread is already running, calling start again gets you an IllegalThreadStateException, you don't get 2 threads.

I assume that you want to do this to make your code less verbose; instead of saying
Thread t = new CustomThread();
t.start();
activeThreads.add(t);
you can just say
activeThreads.add( new CustomThread() );
I also like having less verbosity, but I agree with the other respondents that you shouldn't do this. Specifically, it breaks the convention; anyone familiar with Java who reads the second example will assume that the thread has not been started. Worse yet, if they write their own threading code which interacts in some way with yours, then some threads will need to call start and others won't.
This may not seem compelling when you're working by yourself, but eventually you'll have to work with other people, and it's good to develop good coding habits so that you'll have an easy time working with others and code written with the standard conventions.
However, if you don't care about the conventions and hate the extra verbosity, then go ahead; this won't cause any problems, even if you try to call start multiple times by mistake.

By the way, if one wants lower verbosity and still keep the constructor with its "standard" semantics, one could create a factory method:
activeThreads.add( CustomThread.newStartedThread() );

It's legal, but not wise. The Thread part of the instance will be completely initialised, but your constructor may not. There is very little reason to extend Thread, and to pull tricks like this isn't going to help your code.

It is "legal", but I think the most important issue is this:
A class should do one thing and do it well.
If your class uses a thread internally, then the existence of that thread should not be visible in the public API. This allows improvement without affecting the public API. Solution: extend Runnable, not Thread.
If your class provides general functionality which, in this case, happens to run in a thread, then you don't want to limit yourself to always creating a thread. Same solution here: extend Runnable, not Thread.
For less verbosity I second the suggestion to use a factory method (e.g. Foo.createAndRunInThread()).

Legal ... yes (with caveats as mentioned elsewhere). Advisable ... no.
I's just a smell you can only too easily avoid. If you want your thread to auto-start, just do it like Heinz Kabutz.
public class ThreadCreationTest {
public static void main(String[] args) throws InterruptedException {
final AtomicInteger threads_created = new AtomicInteger(0);
while (true) {
final CountDownLatch latch = new CountDownLatch(1);
new Thread() {
{ start(); } // <--- Like this ... sweet and simple.
public void run() {
latch.countDown();
synchronized (this) {
System.out.println("threads created: " +
threads_created.incrementAndGet());
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
};
latch.await();
}
}
}

Related

Killing a thread or an asynchronous task

let's say I use a jar that IBM has created.
Let's say that this Jar has a function that I need but is ultimately build as such:
while (true) {
System.out.println(1)
}
(of course it doesn't really just printing 1, but for the example let's say it is)
So, I made the call to the function that does it in another thread using future. How can I completely kill the thread that this code is running in? Or alternatively, how can I kill the asynchronous task in Kotlin that runs the code.
Solutions in Kotlin or Java will be great,
thanks in advance!
EDIT:
I've found out, that if this is a thread, I can Thread#stop() it to really make it stop. But unfortunately making the constructor throwing exceptions multiple times, causes the JVM to erase the class from memory causing a NoClassDefFoundError when instantiating the class the next time..
If you can capture it's thread you should be able to kill it so long as it is doing some kind of blocking function internally.
class OtherFunction implements Runnable {
#Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// We assume the thread will exit when interrupted.
System.out.println("Bye!!");
return;
}
System.out.println("Hello");
}
}
}
class Killable implements Runnable {
final Runnable target;
private Thread itsThread;
Killable(Runnable target) {
this.target = target;
}
#Override
public void run() {
// Catch the thread id of the target.
itsThread = Thread.currentThread();
// Launch it.
target.run();
}
public void kill() {
// Give it a good kick.
itsThread.interrupt();
}
}
public void test() throws InterruptedException {
OtherFunction theFunction = new OtherFunction();
Killable killableVersion = new Killable(theFunction);
new Thread(killableVersion).start();
// Wait for a few seconds.
Thread.sleep(10000);
// Kill it.
killableVersion.kill();
}
It seems like Thread#stop() solved my problem. I know it's deprecated and can be prevented with catch(Throwable t) but at least it did the trick for me.
By the way, to get the thread from the executor, I've used AtomicReference<Thread> and set it in the callback.
Thread#stop() is deprecated as 'inherently unsafe' and should be avoided if at all possible.
It's a source of instability and corruption and may fail anyway!
It actually causes a ThreadDeath exception to be throw in the target thread.
The authors of whatever code it pops into are unlikely to have expected that outcome.
Objects may be in an inconsistent state, external resources may be held and get leaked, files may be incompletely written.
There are ways of handling unexpected errors but in practice most code is written assuming it knows which exceptions might be thrown and not in anticipation for such a 'surprise'.
Given ThreadDeath is a Throwable any catch(Throwable t) will catch it and again, unless great care was taken in every piece of code the thread might execute (unrealistic) ThreadDeath might just get absorbed and not end the thread.
The correct way to handle this is declare an atomic variable (usually as part of the Runnable that represents the task.
AtomicBoolean stopThread=new AtomicBoolean(false);
Then write the loop as:
while (!stopThread.get()) {
System.out.println(1);
}
And provide a method:
public void stopThread(){
stopThread.set(true);
}
Alternatively you can use interrupt() and check interrupted(). These are cleaner methods provided in the Thread class. interrupted() has the behaviour of clearing the flag when called. That's not always helpful and while the flag can be examined by Thread.currentThread().isInterrupted() the 'checking the flag clears it' behaviour can be unhelpful and also suffers some of the issues of stop() because it can cause "surprising" exceptions to be throw at points other code has never anticipated. The right approach is to use your own flag and be in full control of where the process decides to quit.
Take your pick.
See also: Java Thread Primitive Deprecation
Ever wondered why when you click 'Cancel' on some concurrent process you are often made to wait ages for it to respond?
This is why. The task needs to come to a well defined point and do any necessary clean up to terminate in a well defined way.
Think of Thread#stop() as like stopping a cyclist by kicking them off their bike. The method here waves a red flag at them and they then come to a halt as swiftly as they safely can.
Thread#stop() should never have been in Java and you should never use it.
You get away with it in development and small systems. It causes havoc in large production environments.
It's not just deprecated as 'not recommended' it is 'inherently unsafe' do not use it.
It's been deprecated for years and its disappointing that some 'removal date' has never been advertised.
Here's an example that uses either Thread#stop() or interrupt() depending on whether you opt for being dangerous.
import java.lang.System;
import java.lang.Thread;
class Ideone
{
private static boolean beDangerous=true;//Indicates if we're going to use the Thread#stop()....
//This main method uses either stop() or interrupt() depending on the option.
public static void main (String[] args) throws java.lang.Exception
{
PrimeFactor factor=new PrimeFactor();
try{
for(int i=1;i<30;++i){
Thread thrd=new Thread(new Primer(factor));
thrd.start();
Thread.sleep(10);//Represents some concurrent processing...
if(beDangerous){
thrd.stop();
}else{
thrd.interrupt();
}
thrd.join();
if(!factor.check()){
System.out.println("Oops at "+i);
}
}
}catch(Throwable t){
System.out.println(t);
}
}
//This class just hammers the PrimeFactor object until interrupt()ed (or stop()ed).
private static class Primer implements Runnable {
private PrimeFactor factor;
public Primer(PrimeFactor ifactor){
factor=ifactor;
}
public void run(){
int i=1;
while(!Thread.interrupted()){
factor.set(i++);
}
}
}
//Don't worry about this bit too much.
//It's a class that does a non-trivial calculation and that's all we need to know.
//"You're not expected to understand this". If you don't get the joke, Google it.
//This class calculates the largest prime factor of some given number.
//Here it represents a class that ensures internal consistency using synchronized.
//But if we use Thread#stop() this apprently thread-safe class will be broken.
private static class PrimeFactor {
private long num;
private long prime;
public static long getFactor(long num){
if(num<=1){
return num;
}
long temp=num;
long factor=2;
for(int i=2;temp!=1;++i){
if(temp%i==0){
factor=i;
do{
temp=temp/i;
}while(temp%i==0);
}
}
return factor;
}
public synchronized void set(long value){
num=value;
prime=getFactor(value);
}
public synchronized boolean check(){
return prime==getFactor(num);
}
}
}
Typical partial output:
Oops at 1
Oops at 2
Oops at 3
Oops at 6
Oops at 8
Notice that the PrimeFactor class can be described as thread-safe. All it's methods are synchronized. Imagine it's in some library. It's unrealistic to expect "thread-safe" to mean Thread#stop()-safe and the only way to do that would be intrusive. Putting calls to it in a try-catch(ThreadDeath tde) block won't fix anything. The damage will have been down before it's caught.
Don't convince yourself that changing set() to the following solves it:
public synchronized void set(long value){
long temp=getFactor(value);
num=value;
prime=temp;
}
First and foremost the the ThreadDeath exception could throw during the assignments so all that does is potentially shorten the odds on the Race Condition. It hasn't been negated. Never make "how likely is that to happen" arguments about race conditions. Programs call methods billions of times so billion to one-shots come up regularly.
To use Thread#stop() you can essentially never use any library objects including java.* and jump through hoops to handle ThreadDeath everywhere in your code and almost certainly eventually fail anyway.
In java there is no official way of killing thread. This is bug. (no need to argue with it here) Thread#stop() should not be deprecated. It may be improved that it cannot be consumed. Even now it will work most of the time just fine.
Right now, if I write function which will be executed with kill need, I would start new thread and joint to it with timeout or other disconnect mechanism. This will make your code to continue like main thread was killed. Problem is that main thread is still running. All resources are still in use. This is still better than application being frozen. Calling thread.interrupt() is first step but it this does not work using thread.stop() is adequate here. It won't make things worse.
If you really must kill the thread, only way would be to start another jvm via jni, run unsafe code there and use linux kill -9 to stop the whole process if needed.
I believe killing thread is perfectly possible, only jvm developers didn't care enough. I get into this situation all the time and answers like don't use any libraries, fix all foreign code, write your own language or live with it are just frustrating.

Creates thread in Java

I don't understand, when I creates Thread, what i will get in first case and the second?
And in general, there is difference between them?
ExecutorService executorService = Executors.newCachedThreadPool();
NewThread newThread = new NewThread(Thread.MAX_PRIORITY);
for(int i = 0;i < 5; i++){
executorService.execute(newThread);
}
ExecutorService executorService = Executors.newCachedThreadPool();
for(int i = 0;i < 5; i++){
NewThread newThread = new NewThread(Thread.MAX_PRIORITY);
executorService.execute(newThread);
}
Best answer, given what you've provided is: in the first case you'll probably get errors. Second way is totally safe (assuming that you're not doing something unsafe, of course).
I know, not much helpful, so let's get you some background.
NewThread most probably implements Runnable, so it should have method void run(), like this:
class NewThread implements Runnable {
void run(){
//do something
}
}
Now, we don't know what's the actual implementation, but we still can do some analysis. The whole outcome of your examples depends on whether NewThread is stateful or stateless. "Stateful" means that instance of that class has state, for example some internal fields (attributes). "Stateless" is just "not stateful".
If NewThread is stateless, then in both cases the outcome will be the same - underneath ExecutorService executes the run() method in new thread, and as there is no state of variables anyway, we won't have any problems.
If NewThread is stateful, there may be some problems in first of your examples. Compiler won't be of much help here, as the code is OK, but the logic may be broken. Imagine this:
class NewThread implements Runnable {
int x = 0;
void run(){
while (x<10)
x = x + 1;
}
}
What you see here is a handbook example of race condition. Better authors than me explained the issue way better than me, so I'm just gonna provide some links to read, like this, this and this (also: use Google, of course). Basically, race condition in this case is that when we do x = x + 1 we first need to read x, then write to it. Between read and write some other thread may have modified the value of x, and that would be overwriten by this thread.
There is a case in which NewThread is stateful, but still works properly. This happens if you synchronize your code by-hand - either using synchronized keyword (for example, see 3rd link above) or by using synchronized data structures:
class NewThread implements Runnable {
AtomicInteger x = new AtomicInteger(0);
void run(){
while (x<10)
x.incrementAndGet(); //getAndIncrement would work too - we don't care about the result, only about incrementing
}
}
"Atomic" means that every operation on that class is considered single step, like read or write (while x = x+1 are two steps, which is exactly what leads to race condition). There are already several available atomic classes in JDK. If you would like to implement something similiar yourself, you'd probably be using synchronized keyword or some lock-like object to guard the variable.
In the first case you are creating one thread instance and attempting to execute it 5 times in the second you are creating 5 different thread instances and trying to execute them. Does that answer your question?
I think your question is rooted in bad naming. You are doing
executorService.execute(newThread);
and probably you are wondering now how why that service (which is based on a threadpool) is dealing with Threads.
Simple answer: it isn't. That interface Executor.execute() takes a Runnable object.
In other words: your code will call that run method that your class NewThread provides.
Of course, the "direct" answer to your question is: in the first case, you are sending the same Runnable 5 times to the Executor; whereas in the second case, you are sending 5 different Runnables to the Executor.
Different in the sense of: different objects - as they are of the same class, the very same thing should happen for both examples. Unless you do some nasty static stuff in NewThread; which wouldn't be too surprising given the overall impression of your question.
I haven't tried it, but the first case should execute once and then start throwing exceptions. Once an instance of Thread has terminated, it is illegal to try to start it again. See the javadoc for start:
IllegalThreadStateException - if the thread was already started.
Your second example is the more sensible of the two since it's creating 5 separate Thread instances.

Java - Preferred design for using a mutable object reference in another thread?

public class ObjectA {
private void foo() {
MutableObject mo = new MutableObject();
Runnable objectB = new ObjectB(mo);
new Thread(objectB).start();
}
}
public class ObjectB implements Runnable {
private MutableObject mo;
public ObjectB(MutableObject mo) {
this.mo = mo;
}
public void run() {
//read some field from mo
}
}
As you can see from the code sample above, I pass a mutable object to a class that implements Runnable and will use the mutable object in another thread. This is dangerous because ObjectA.foo() can still alter the mutable object's state after starting the new thread. What is the preferred way to ensure thread safety here? Should I make copy of the MutableObject when passing it to ObjectB? Should the mutable object ensure proper synchronization internally? I've come across this many times before, especially when trying to use SwingWorker in a number of GUI applications. I usually try to make sure that ONLY immutable object references are passed to a class that will use them in another thread, but sometimes this can be difficult.
This is a hard question, and the answer, unfortunately, is 'it depends'. You have three choices when it comes to thread-safety of your class:
Make it Immutable, then you don't have to worry. But this isn't what you're asking.
Make it thread-safe. That is, provide enough concurrency control internal to the class that client code doesn't have to worry about concurrent threads modifying the object.
Make it not-thread safe, and force client code to have some kind of external synchronization.
You're essentially asking whether you should use #2 or #3. You are worried about the case where another developer uses the class and doesn't know that it requires external synchronization. I like using the JCIP annotations #ThreadSafe #Immutable #NotThreadSafe as a way to document the concurrency intentions. This isn't bullet-proof, as developers still have to read the documentation, but if everyone on the team understands these annotations and consistently applies them, it does make things clearer.
For your example, if you want to make the class not thread-safe, you could use AtomicReference to make it clear and provide synchronization.
public class ObjectA {
private void foo() {
MutableObject mo = new MutableObject();
Runnable objectB = new ObjectB(new AtomicReference<>( mo ) );
new Thread(objectB).start();
}
}
public class ObjectB implements Runnable {
private AtomicReference<MutableObject> mo;
public ObjectB(AtomicReference<MutableObject> mo) {
this.mo = mo;
}
public void run() {
//read some field from mo
mo.get().readSomeField();
}
}
I think you are overcomplicating it. If it is as the example (a local variable of which no reference is kept) you should trust that nobody will try to write to it. If it is more complicated (A.foo() has more LOC) if possible, create it only to pass to the thread.
new Thread(new MutableObject()).start();
If not (due to initializations), declare it in a block so it gets out of scope immediately, even maybe in a separate private method.
{
MutableObject mo = new MutableObject();
Runnable objectB = new ObjectB(mo);
new Thread(objectB).start();
}
....
Copy the object. You won't have any weird visibility problems because you pass the copy to a new Thread. Thread.start always happens before the new thread enters its run method. If you change this code to pass the object to an existing thread, you need proper synchronization. I recommend a blocking queue from Java.util.concurrent.
Without knowing your exact situation, this question will be difficult to answer precisely. The answer totally depends on what the MutableObject represents, how many other threads may modify it simultaneously, and whether or not the threads that read the object care whether its state changes while they are reading it.
With respect to thread-safety, internally synchronizing all reads and writes to MutableObject is provably the "safest" thing to do, but it comes at the cost of performance. If contention is really high on reads and writes, then your program may suffer performance issues. You can get better performance by sacrificing some guarantees on mutual exclusion - whether those sacrifices are worth the performance increases totally depends on the specific problem you're trying to solve.
You can also play some games with how you go about "internally synchronizing" your MutableObject, if that's what you end up doing. If you haven't already, I'd recommend reading up on the differences between volatile and synchronized and understand how each can be used to ensure thread safety for different situations.

Good thread design: "Method in Thread" or "Thread in Method"

This is just a general question on actual thread design. I'm using Java on android specifically but general design would be the better focus of this question.
Its simple enough, which is better method in thread or thread in method.
Example,
Lets say we have 3 methods/functions/whatever.
public void readMail()
{
//Logic...
}
public void postQuestion()
{
//Logic...
}
public void answerQuestion()
{
//Logic...
}
Is it better to have
A: Thread within Method
public void readMail()
{
new Thread(new Runnable()
{
public void run()
{
//Logic
}
}).start();
}
And then call your method as you normally would in any OO situation. Say
Email.readMail();
B: Method within Thread
//note this could be inside a method or a class that extends runnable
new Thread(new Runnable()
{
public void run()
{
readMail();
postQuestion();
answerQuestion();
}
}).start();
Method within Thread
[+] If your methods do not need to ensure the property of concurrent execution, or they have deterministic runtime behavior (time and performance), this approach can be a high-level management for concurrency of the application; i.e. concurrency remains at the level of objects rather than methods.
[-] Since the concurrency remains at the level of threads/objects, the application may lose the notion of responsiveness. A user may be "posting a question" while another is "fetch an answer"; and both can be dealt with concurrently.
Thread with Method
[+] More fine-grained concurrency control: each method becomes a unit of execution at the OS level. That's why as #LouisWasserman mentioned, maybe, taking advantage of Executor framework would make more sense.
[-] Generally threads are resourceful and expensive; so this means that you will have performance issues when used in high-frequency/load application with numerous calls to one method. Specially, if there are inter-method data/logic dependencies. In this regard, synchronization also becomes a concerns and that's why using Actor models can help more.
I'd suggest reading more about Actor models and their available implementations.
The second option is more amenable to being rewritten to use Executors and the like, so I'd prefer that version.
I prefer:
C: One Thread One Object
public class Test {
public static class MailReader implements Runnable {
public void readMail() {
//Logic...
}
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
readMail();
}
}
}
public static class QuestionPoster implements Runnable {
public void postQuestion() {
//Logic...
}
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
postQuestion();
}
}
}
public static class QuestionAnswerer implements Runnable {
public void answerQuestion() {
//Logic...
}
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
answerQuestion();
}
}
}
public static void main(String[] args) throws FileNotFoundException {
new Thread(new QuestionAnswerer()).start();
new Thread(new QuestionPoster()).start();
new Thread(new MailReader()).start();
}
}
This allows the full gamut of possibilities without any additional grok effort. If you want more mail answered than questions posted, make more MailReaders.
If you see
for ( int i = 0; i < 10; i++ ) {
new Thread(new MailReader()).start();
}
you know exactly what is intended and you know that will work.
At first design (A), every method is a SEPARATE THREAD in fact, while at second design (B), you have ONLY ONE THREAD.
It deeply depends on you application logic & the operation which every method performs:
If you need to run your methods parallel, then A is the correct answer, but if you need execute all methods sequentially in a thread, then B would be your choice.
If you are building a utility for other programmers to use, note that the client programmer may not care about threads at all and may just want to write a single-threaded program. Unless there is a very good reason to do so, you shouldn't force them to drag threading issues into a program which would otherwise work fine single-threaded. Does this mean your library can't use threads internally? No! But to a caller, your methods should appear single-threaded (except that they return faster than they would if they were implemented without threads).
How can you do this? When someone calls into one of your methods, block the calling thread, and pass the task off to a pool of worker threads, who can perform it in parallel. After the worker threads finish the task, unblock the calling thread and let it return a value to the caller.
This way you can get the performance benefits of parallelism, without forcing callers to deal with threading issues.
Now, on the other hand, even if you decide that your library doesn't need to use threads internally, you should still make it thread-safe, because client programmers may want to use threads.
In other words, there is no reason why the decisions of "thread in method?" and "method in thread?" need to be coupled. You can use "thread in method" if there are performance benefits to doing so, but that shouldn't affect the caller. (They should just be able to call the method and get the needed return value back, without worrying about whether you are using threads internally).
If your module is thread-safe, then it won't be affected either by whether the caller is using threads or not. So if the client programmer wants to use threads, they can also use "method in thread". In some situations, you may have both "method in thread" and "thread in method" -- your module may be using a worker thread pool + task queue internally, and you may have multiple caller threads pushing tasks onto the queue and waiting for results.
Now, while I am talking like you are building a library, in reality you are probably just building code for your own use. But regardless of that, the same principles apply. If you want to use threads for performance, it is better to encapsulate the use of threads behind an interface, and make it so the rest of the program doesn't have to know or care whether module XYZ is using threads or not. At the same time, it is best if you make each module thread-safe, so callers can decide whether to use threads or not.

Questions on Concurrency from Java Guide

So I've been reading on concurrency and have some questions on the way (guide I followed - though I'm not sure if its the best source):
Processes vs. Threads: Is the difference basically that a process is the program as a whole while a thread can be a (small) part of a program?
I am not exactly sure why there is a interrupted() method and a InterruptedException. Why should the interrupted() method even be used? It just seems to me that Java just adds an extra layer of indirection.
For synchronization (and specifically about the one in that link), how does adding the synchronize keyword even fix the problem? I mean, if Thread A gives back its incremented c and Thread B gives back the decremented c and store it to some other variable, I am not exactly sure how the problem is solved. I mean this may be answering my own question, but is it supposed to be assumed that after one of the threads return an answer, terminate? And if that is the case, why would adding synchronize make a difference?
I read (from some random PDF) that if you have two Threads start() subsequently, you cannot guarantee that the first thread will occur before the second thread. How would you guarantee it, though?
In synchronization statements, I am not completely sure whats the point of adding synchronized within the method. What is wrong with leaving it out? Is it because one expects both to mutate separately, but to be obtained together? Why not just have the two non-synchronized?
Is volatile just a keyword for variables and is synonymous with synchronized?
In the deadlock problem, how does synchronize even help the situation? What makes this situation different from starting two threads that change a variable?
Moreover, where is the "wait"/lock for the other person to bowBack? I would have thought that bow() was blocked, not bowBack().
I'll stop here because I think if I went any further without these questions answered, I will not be able to understand the later lessons.
Answers:
Yes, a process is an operating system process that has an address space, a thread is a unit of execution, and there can be multiple units of execution in a process.
The interrupt() method and InterruptedException are generally used to wake up threads that are waiting to either have them do something or terminate.
Synchronizing is a form of mutual exclusion or locking, something very standard and required in computer programming. Google these terms and read up on that and you will have your answer.
True, this cannot be guaranteed, you would have to have some mechanism, involving synchronization that the threads used to make sure they ran in the desired order. This would be specific to the code in the threads.
See answer to #3
Volatile is a way to make sure that a particular variable can be properly shared between different threads. It is necessary on multi-processor machines (which almost everyone has these days) to make sure the value of the variable is consistent between the processors. It is effectively a way to synchronize a single value.
Read about deadlocking in more general terms to understand this. Once you first understand mutual exclusion and locking you will be able to understand how deadlocks can happen.
I have not read the materials that you read, so I don't understand this one. Sorry.
I find that the examples used to explain synchronization and volatility are contrived and difficult to understand the purpose of. Here are my preferred examples:
Synchronized:
private Value value;
public void setValue(Value v) {
value = v;
}
public void doSomething() {
if(value != null) {
doFirstThing();
int val = value.getInt(); // Will throw NullPointerException if another
// thread calls setValue(null);
doSecondThing(val);
}
}
The above code is perfectly correct if run in a single-threaded environment. However with even 2 threads there is the possibility that value will be changed in between the check and when it is used. This is because the method doSomething() is not atomic.
To address this, use synchronization:
private Value value;
private Object lock = new Object();
public void setValue(Value v) {
synchronized(lock) {
value = v;
}
}
public void doSomething() {
synchronized(lock) { // Prevents setValue being called by another thread.
if(value != null) {
doFirstThing();
int val = value.getInt(); // Cannot throw NullPointerException.
doSecondThing(val);
}
}
}
Volatile:
private boolean running = true;
// Called by Thread 1.
public void run() {
while(running) {
doSomething();
}
}
// Called by Thread 2.
public void stop() {
running = false;
}
To explain this requires knowledge of the Java Memory Model. It is worth reading about in depth, but the short version for this example is that Threads have their own copies of variables which are only sync'd to main memory on a synchronized block and when a volatile variable is reached. The Java compiler (specifically the JIT) is allowed to optimise the code into this:
public void run() {
while(true) { // Will never end
doSomething();
}
}
To prevent this optimisation you can set a variable to be volatile, which forces the thread to access main memory every time it reads the variable. Note that this is unnecessary if you are using synchronized statements as both keywords cause a sync to main memory.
I haven't addressed your questions directly as Francis did so. I hope these examples can give you an idea of the concepts in a better way than the examples you saw in the Oracle tutorial.

Categories

Resources