Home arrow Java & J2EE arrow Page 2 - More About Multithreading in Java

Stopping and Synchronization - Java

You are reading the second part of the multithreading in Java series. The first part covered the basics of threads, explained the theory that lies behind them, and then gave examples of the two possible ways of creating new threads. This article resumes the journey by getting even deeper into concepts like the ThreadGroup class, synchronization, and inter-thread communication.

TABLE OF CONTENTS:
  1. More About Multithreading in Java
  2. Stopping and Synchronization
  3. Inter-Thread Synchronization and Communication
  4. Taking a Break
By: Barzan "Tony" Antal
Rating: starstarstarstarstar / 16
March 04, 2009

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
 

We covered earlier that threads must be started with the start() method. Failing to do so and then running them via run() results in a sequential execution and not what we want, which is multi-threading: simultaneous execution of multiple threads. All right but one might also ask, how do we stop a thread that is running? 

There’s a method called stop() that does that—however, its use isn’t advised. That is because there’s a chance it might hog the execution, dragging the system into a stale mate or dead point. The stop() method does not free up allocated system resources. Fortunately, there is a simple and effective workaround. We’re going to introduce a boolean variable (attribute) that always refers to the state of the thread. 

Let’s call it isRunning. We declare this as an attribute of the class with the following modifiers: private volatile. At first, surely, this variable starts out as true. However, we will write a method that sets this to false, such as the stopping() thread. Right after that, we can easily modify the run() method so that it runs while isRunning is true.

 

class MyThread extends Thread{

private volatile boolean isRunning = true;

 

public void stopping(){

isRunning = false;

}

 

public void run(){

while (isRunning){

// action goes here

try{

sleep(10);

}

catch (InterruptedException e){}

}

}

Based on the above source code, threads can be stopped by calling the stopping() method instead of the inherited stop(), which might cause problems. This is much safer. 

And finally, the time has come for us to talk about synchronization. It is one of the most important concepts when working with multiple threads within an application. In order to fully grasp the concept of synchronized execution, we’re required to also talk about unsynchronized (asynchronous) execution. 

If we don’t explicitly “synchronize” the execution of threads, then by all norms they're executed asynchronously. This kind of multi-threading isn’t reliable because it does not give consistent results. A so-called “race condition” appears, which means the threads are “racing each other” because some operations can be completed faster than others, the processor might have faster access to some data (registers), and so forth. 

Moreover, this also means that executing the same application another time does not yield the same results with a 100% guarantee. By definition, a thread becomes synchronized if you become the owner of its object monitor. This is somewhat similar to locking the object. And you can do this in two possible ways. 

Each time the program enters a synchronized method, it becomes owner of that object’s monitor (or class monitor in the case of static methods). In a nutshell, this locks the thread’s access to the synchronized method if another thread is already executing it. And this blockage applies until the lock is released by exiting the method or invoking the wait() method. The latter wait() temporarily releases the monitor. 

You can make a method synchronized by adding the “synchronized” keyword prior to its declaration. This is the first solution. Another way to make a thread become owner of its object monitor is by using the “synchronized” statement on a common object. The latter is safer because it always releases the lock once the execution is done.

Consider the following example for the synchronized method path.

 

synchronized void func(...){

...

}

 

And now let’s see another example for the synchronized common object solution.

 

void func(...){

// ...

synchronized(obj){

// ...

}

}

 

On the next page we’ll tackle inter-thread communication and present an example of the popular producer-consumer model. That problem pops up very frequently as an approach used by professors to explain how inter-thread communication is applied. 



 
 
>>> More Java & J2EE Articles          >>> More By Barzan "Tony" Antal
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

JAVA & J2EE ARTICLES

- More Java Bugs Lead to More Attacks
- Oracle's Java One Brings News, Surprises
- Oracle Patches Java Runtime Environment
- Apple Syncs Java Update with Oracle
- Spring 3.1 Java Development Framework Compat...
- Jelastic Java PaaS Availability and Pricing ...
- NetBeans 7.1 Released, Supports JavaFX 2
- SolarWinds Releases Newest Version of Java M...
- Free Monitoring Tool for Java Apps on Heroku
- Heroku Adds JCloud Platform Support, Java 7 ...
- Java SE 8 Speculation in Full Swing
- Java SE 7 Now Available
- New JVM Language and Java Reporting Tool
- Java 7 Release Update and New Eclipse Toolkit
- The Best Java Netbeans IDE Plugins

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: