Java threading – The Executor framework

The main goal of this article is to present the better mechanism of executing threads in Java and to show that working directly with threads is no longer necessary. Thanks to the Executor framework, working with threads in Java is easier. And there are people who claim that working with threads in Java is easier than in most other languages.

Defining threads in Java

Multithreading is increasingly becoming the  part of every modern application these days. The program is multithreaded if it is able to run more than one thread at the same time.

In Java, defining threads is straightforward and it is done either by extending the java.lang.Thread class and overriding its run() method or, more common, by implementing the java.lang.Runnable interface.

Let’s look at the example of defining a thread by implementing the Runnable interface:

class SomeRunnable implements Runnable {
    @Override
    public void run() {
	for (int i = 0; i < 3; i++) {
	    System.out.println(Thread.currentThread().getName() + " counter="
		    + i);
	}
    }
}

To have the above code run by a separate thread the new java.lang.Thread object must be instantiated and started as it is shown below:

public class Runner {
    public static void main(String[] args) {
	// instantiate a runnable object
	Runnable runnable = new SomeRunnable();
	// instantiate 2 threads and pass the runnable object
	Thread thread_0 = new Thread(runnable);
	Thread thread_1 = new Thread(runnable);
	// start the threads
	thread_0.start();
	thread_1.start();
    }
}

Using the Runnable interface is better than extending the Thread class. One of the main advantages of doing that is the ability to use an Executor framework instead of directly using the Thread class to create and execute new threads: constructing new threads is relatively expensive because it involves interaction with the operating system.

The Executor framework

The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies.

The Executor Framework was introduced in Java 1.5 and it is a part of the java.util.concurrent package. The main interface for the framework is the Executor interface and its subinterfaces: ExecutorService and ScheduledExecutorService. Please refer to Executor API [ExecutorAPI] to see the detailed description of the interfaces.

Let’s take a look at the simple example of using the Executor framework to run a previously created task using a fixed thread pool:

public class Runner {
    public static void main(String[] args) {
	Runnable runnable = new SomeRunnable();
	// create a fixed thread pool
	ExecutorService pool = Executors.newFixedThreadPool(3);
	// run the task 5 times using the pool
	for (int i = 0; i < 5; i++) {
	    pool.execute(runnable);
	}
	pool.shutdown();
    }
}

In the above example, I used the ExecutorService interface which is an Executor that provides a number of useful methods to control the task execution. For the creation of the concrete ExecutorService, I used the Executors class and one of its static factory methods: newFixedThreadPool(). Please refer to Executor API [ExecutorAPI].

Task scheduling

The ScheduledExecutorService is the Executor that supports scheduling of tasks based on the relative time or to run task periodically. Example of scheduling a task to run after a 1000 ms:

public class Runner {
    public static void main(String[] args) {
	Runnable runnable = new SomeRunnable();

	ScheduledExecutorService thread = Executors
		.newSingleThreadScheduledExecutor();

	thread.schedule(runnable, 1000, TimeUnit.MILLISECONDS);
	thread.shutdown();
    }
}

Summary

The article barely scratched the surface of the Executor framework. Thus, I encourage the reader to study the framework’s documentation to see its power and simplicity.

References and useful links

  1. [ExecutorAPI] – The API documentation of the framework is comprehensive and should be a good starting point to get along with the framework. Examples included – http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executor.html
  2. “Concurrency: Executors” article at http://www.javalobby.org/forums/thread.jspa?threadID=16252&tstart=0
  3. “The Executor Framework” from “Java Concurrency in Practice” at http://book.javanb.com/java-concurrency-in-Practice/ch06lev1sec2.html

Tags:

Aspire Blog Team

Aspire Systems is a global technology services firm serving as a trusted technology partner for our customers. We work with some of the world's most innovative enterprises and independent software vendors, helping them leverage technology and outsourcing in our specific areas of expertise. Our services include Product Engineering, Enterprise Solutions, Independent Testing Services and IT Infrastructure Support services. Our core philosophy of "Attention. Always." communicates our belief in lavishing care and attention on our customers and employees.

10 comments

  1. Rafal,

    nice useful article – congratulations.

    I am curious how efficient Executor framework will be working with Swing and AWT GUIs which are using own threads ?

    Krzysztof

  2. Rafal,

    nice useful article – congratulations.

    I am curious how efficient Executor framework will be working with Swing and AWT GUIs which are using own threads ?

    Krzysztof

  3. GET GENERIC LOPID ON-LINE.

    Fast delivery, No hidden fees, Moneyback guarantee. Order in bulk and get the lowest price.

    + Get FREE pills with your order
    + 24/7/365 Customer Support
    + Top quality medications
    + All most payment methods
    + Fast Worldwide shipping

    http://med4health.biz/t_pics/lopid.jpeg

    Order Generic Lopid Here

    About Generic Lopid
    Gemfibrozil helps reduce cholesterol and triglycerides (fatty acids) in the blood. High levels of these types of fat in the blood are associated with an increased risk of atherosclerosis (clogged arteries). Gemfibrozil is used to treat very high cholesterol and triglyceride levels in people with…

    Related search:
    side effects lopid
    is lopid a statin
    rash lopid
    stop taking lopid
    lopid liver bamage
    reactions to lopid
    lopid 900
    lopid and ceftin drug interactions
    lopid cholesterol drug
    get lopid
    lopid drug test
    lopid drug reactions
    zocor lopid
    lopid uses
    reactions to lopid
    lopid dosage
    drug interactions norvasc zetia lopid
    lopid vc
    buy generic lopid
    diflucan and lopid inteaction
    lopid liver law
    celebrex and lopid
    lopid 900
    side effects lopid
    rash from lopid
    lopid manufacturer
    side effects of lopid
    can’t tolerate statins or lopid
    lopid price
    lipitor and lopid
    lopid dangers
    lopid foods to avoid
    lopid manufactuer
    medication lopid 25 mg
    lopid and pregnancy
    celebrex and lopid
    spanish word for lopid
    lopid dosage
    lopid 600mg tab
    triglyceride drug lopid
    lopid and lactation
    lopid gemfibrozil

  4. [url=http://susmatch.com/articles/15]] [b]Buy Actonel lowest price! [/b][/url]

    [url=http://susmatch.com/articles/15][img]http://thisdrugs.com/imgtb/actonel01.jpg[/img][/url]

    [b]* Customer support available 24/7![/b]
    [b]* No prescription required![/b]
    [b]* Payment options: Visa, Amex, MasterCard, eCheck, Wire transfe etc[/b].

    [url=http://susmatch.com/articles/15]] [b]Click Here [/b][/url]
    ::
    ::
    ::
    ::
    ::
    ::
    ::
    ::
    ::
    ::
    ::
    ::
    ::
    ::
    ::
    ::
    ::
    ::
    ::
    ::
    ::

    Weighty tidings here Actonel
    Do not take a Actonel tablet if you cannot seating for stand-up or rise after at least 30 minutes. Actonel can give rise to life-threatening problems in the abdomen or esophagus (the tube that connects your way out and suffer). You will lack to stay upright as a replacement for at least 30 minutes after winsome this medication.
    Take the Actonel capsule before all emotional attachment in the morning, at least 30 minutes prior to you sup or drink anything or take any other medicine.

    womens discussion group on actonel
    actonel fosamax vs
    [url=http://thequake.org/quakeboard/index.php?topic=14784.0] availability of risedronate actonel in us [/url]
    [url=http://www.northantsriders.com/forum/viewtopic.php?f=2&t=30892] actonel jaw problems [/url]
    [url=http://georgiafishingreportforum.info/index.php?topic=46.0] mdl fosamax actonel 1789 [/url]
    [url=http://planterwartremoval.net/forum/viewtopic.php?f=1&t=65524] actonel information sheet [/url]
    [url=http://myorbitra.com/forums/index.php?topic=50729.0] i can’t afford actonel [/url]
    [url=http://ylos40ladrones.info/viewtopic.php?f=12&t=965] food and drug administration actonel [/url]
    [url=http://cecadesu.semarnat.gob.mx/foro/viewtopic.php?f=2&t=17785] alendronate fosamax and risedronate actonel revisited [/url]
    [url=http://www.sportska-prehrana.com/forum/index.php?topic=878.0] actonel litigation [/url]
    [url=http://www.jkandjranches.com/forum/viewtopic.php?p=239389#239389] actonel homeopathy [/url]
    [url=http://forum.kelhost.org/showthread.php?p=966#post966] generic actonel [/url]
    [url=http://www.ciberagendas.com/agamir/phpBB3/viewtopic.php?f=3&t=11601] actonel vertebral fracture 31 [/url]
    [url=http://www.chaupromotions.com/forum/viewtopic.php?f=2&t=137367] actonel and jaw problems [/url]
    [url=http://www.hammerslagfestival.net/forum/viewtopic.php?f=2&t=2907] actonel with calcium [/url]
    [url=http://tigrechacho.com/foro/index.php?topic=3455.0] actonel eyes [/url]
    [url=http://www.cwhutton.com/phpBB3/viewtopic.php?f=2&t=2766] define actonel [/url]
    [url=http://diet.exnavi.com/newbb%2Bviewtopic.topic_id%2B5900%2Bpost_id%2B61245%2Border%2B0%2Bviewmode%2Bflat%2Bpid%2B0%2Bforum%2B3.htm#forumpost61245] side effects to the drug actonel [/url]
    [url=http://www.majestic13.net/caballusridare/index.php?topic=2305.0] actonel fatigue [/url]
    [url=http://www.bedrijfskundeforum.nl/viewtopic.php?f=3&t=1702] taking actonel and prevacid [/url]
    [url=http://jimmiejamezband.com/forum/viewtopic.php?f=3&t=2739] actonel and heartburn [/url]

    [url=http://forum.arduino.cz/viewtopic.php?f=18&t=32659] actonel drug [/url]
    [url=http://reb.netne.net/foro/index.php?topic=1494.0] actonel 2 tablets monthly [/url]
    [url=http://www.davesfriends.org/forums/viewtopic.php?f=3&t=103413] missing a dose of actonel [/url]
    [url=http://gaithaibinh.org/showthread.php?p=93223#post93223] fosamax or actonel [/url]
    [url=http://wtmel.org/forum/index.php?topic=24130.0] actonel with calcium [/url]
    [url=http://www.forum.tih.pl/viewtopic.php?f=81&t=8166] actonel vs alendronate [/url]
    [url=http://www.adulttalk-load.com/index.php?topic=40626.0] actonel and pain discussion [/url]
    [url=http://burgas.bulboard.com/viewtopic.php?f=2&t=4891] actonel product [/url]
    [url=http://www.dumbcitydesign.com/noshori/herdthink/index.php?topic=2645.0] aventis poland actonel [/url]
    [url=http://forum.blogneng.com/index.php?topic=1750.0] choosing between fosamax actonel or boniva [/url]
    [url=http://www.law-wrestling.com/pwr/phpBB3/viewtopic.php?f=10&t=29939] can valerian root interfere with actonel [/url]
    [url=http://www.porada.forek.eu/viewtopic.php?f=2&t=3427] suma flax seed actonel taken together [/url]
    [url=http://myorbitra.com/forums/index.php?topic=50729.0] ocular side effects actonel [/url]

    [url=http://www.speed.freecp.net/showthread.php?p=7788#post7788] cognitive impairment from actonel [/url]
    [url=http://www.tauchsportclub-mettingen.com/forum/viewtopic.php?f=8&t=8124&start=0&st=0&sk=t&sd=a&view=print] order actonel online [/url]
    [url=http://bleacheledia.mojeforum.net/posting.php?mode=newtopic&f=20] actonel vs boniva [/url]
    [url=http://princesserin.com/erinsforum/index.php?topic=1343.0] actonel alternative [/url]
    [url=http://prisonbreak.tv-forums.co.uk/viewtopic.php?f=4&t=15264] actonel et creatinine [/url]
    [url=http://www2.age.ne.jp/%7Estormcat/BBS/minibbs.cgi] long term effects of taking actonel [/url]
    [url=http://www.mp3collecting.com/forums/index.php?showtopic=458704] actonel 150mg [/url]
    [url=http://www.learningtrust.org.uk/phpBB3/viewtopic.php?f=4&t=54488] actonel vs evista [/url]
    [url=http://thelandofcocoa.com/forum/viewtopic.php?f=2&t=11112] evista or actonel [/url]
    [url=http://www.longneckstrangler.com/forum/index.php?topic=27074.0] * Actonel no prescription discount * Actonel no prescription online * Actonel online * cheap Actonel online * buy Actonel pill * Actonel medicine * Actonel pill * order Actonel medication * buy Actonel online * Actonel discount * buy Actonel pill * Actonel pharmacy online * Actonel no prescription discount * Actonel pills online * order Actonel no prescription * cheap Actonel no prescription * purchase Actonel * purchase Actonel no prescription * purchase Actonel [/url]
    [url=http://www.dominia.com.ar/viewtopic.php?f=2&t=4398] actonel vs evista [/url]
    [url=http://www.dpu.ac.th/artsciences/km/viewtopic.php?f=2&t=2266] actonel joint pain [/url]
    [url=http://www.ai-dealer.com/forum/index.php?topic=32647.0] actonel pros and cons [/url]

    [url=http://aroilun.nafarroa.org/eztabaidagunea/index.php?topic=18428.0] who owns actonel [/url]
    [url=http://breakitdowndesign.com/phpbb/viewtopic.php?f=3&t=41200] find actonel serious side effects [/url]
    [url=http://aikenweb.co.uk/forum/viewtopic.php?f=2&t=22262] actonel side affects [/url]
    [url=http://new.caspy.net/forum/index.php?showtopic=28209] actonel news alerts [/url]
    [url=http://bdwarcraft.com/forum/index.php?topic=13504.0] vaginal bleeding with actonel [/url]
    [url=http://www.torontovolvoclub.com/viewtopic.php?f=5&t=63687] side effects of the drug actonel [/url]
    [url=http://fiction-writers-software.com/forum/index.php?topic=37311.0] actonel cost [/url]
    [url=http://www.kindle2fan.com/forum/viewtopic.php?f=4&t=3418] actonel mdl [/url]
    [url=http://cs.tvsatrm.ro/viewtopic.php?f=54&t=2459] alternative drug to actonel [/url]
    [url=http://onlineadman.com/forum/index.php?topic=24068.0] actonel boniva fosamax side effects [/url]
    [url=http://dutasia.org/forum_dutasia/YaBB.pl?board=3;action=post;title=StartNewTopic] buy actonel sales online specials [/url]
    [url=http://www.forumturizm.com/forum/index.php/topic,989.0.html] actonel and dental extraction osteomyelitis rcdso [/url]
    [url=http://www.clawandshadow.com/modules.php?name=Forums&file=viewtopic&p=41116#41116] actonel womens forum [/url]

    [url=http://hiphopmg2.mojeforum.net/posting.php?mode=newtopic&f=2] actonel jaw [/url]
    [url=http://wedgefitter.com/index.php?topic=30751.0] actonel one weekly side effects [/url]
    [url=http://forum.westendchristian.com/viewtopic.php?f=2&t=17221] order actonel online [/url]
    [url=http://www.boy4boy.ch/phpbb/viewtopic.php?p=138768#138768] order actonel [/url]
    [url=http://www.oicclub.com/board/viewtopic.php?f=5&t=67099] discontinuing therapy with actonel [/url]
    [url=http://glucotrolxlonli.mojeforum.net/posting.php?mode=newtopic&f=1] actonel jaw problems [/url]
    [url=http://kurio.info/simplemachinesforumbb/index.php?topic=12470.0] buy overnight cheap actonel [/url]
    [url=http://www.openloop.com/forums/viewtopic.php?f=4&t=20046] actonel generic [/url]
    [url=http://agamkab.go.id/forum/index.php?topic=144.0] buy actonel online cheap [/url]
    [url=http://nhipdieu.info/forum/showthread.php?p=9368#post9368] marketing actonel [/url]
    [url=http://www.hardcorepokershow.com/forum/viewtopic.php?f=2&t=2814] actonel tb [/url]
    [url=http://submuzik.com/subforums/index.php?topic=839.0] who owns actonel [/url]
    [url=http://www.belev1.com/bb/viewtopic.php?f=2&t=16164] actonel commercial [/url]

    [url=http://www.phantascope.co.uk/bb/viewtopic.php?p=112460#112460] can i take mobic and actonel [/url]
    [url=http://witness.net/forum/viewtopic.php?f=3&t=396131] medicarion actonel [/url]
    [url=http://www.konin.lm.pl/forum/posting.php?mode=newtopic&f=23] actonel medication [/url]
    [url=http://lannagames.rmutl.ac.th/forum/index.php?topic=870889.0] actonel mayo clinic [/url]
    [url=http://www.zonadivxonline.com/smf/index.php?topic=10276.0] actonel not working [/url]
    [url=http://outsidersoftware.com/forum/index.php?topic=12237.0] missing a dose of actonel [/url]
    [url=http://tsobaruch.com/tsoforum/index.php?topic=28673.0] jaw problems actonel [/url]
    [url=http://fleurdelispizza.com/cardmaking/index.php?topic=3408.0] side-effects of actonel [/url]
    [url=http://www.rosehybridizers.org/forum/index.php] buy cheap buy actonel online [/url]
    [url=http://ntelemoveis.com/forum/index.php?PHPSESSID=acbe55be2d80ea5a616e3549edbd7e56&topic=3780.0] actonel side effects after two years [/url]
    [url=http://heavenlybread.net/forum/viewtopic.php?f=2&t=11276] actonel risedronate [/url]
    [url=http://www.biyolojidefteri.net/forum/index.php/topic,6017.new.html#new] actonel vs fosamax which is better [/url]
    [url=http://www.unswbabesoc-eissoc.org/forum/viewtopic.php?f=6&t=14934] actonel speakers [/url]

    [url=http://www.we-wed-you.com/forum/viewtopic.php?f=2&t=6290] actonel and jaw problems [/url]
    [url=http://www.pokerkalender.at/phpBB3/viewtopic.php?f=2&t=17103] actonel vs evista [/url]
    [url=http://moses35i.forum-xl.nl/viewtopic.php?f=5&t=1400] i can’t afford actonel [/url]
    [url=http://www.mauerlocks-bg.com/forum_en/viewtopic.php?f=2&t=59022] actonel otosclerosis [/url]
    [url=http://allsportsat.com/viewtopic.php?f=5&t=19413] choosing between fosamax actonel or boniva [/url]
    [url=http://domogalaxy.site40.net/smf/index.php?topic=728.0] actonel jaw problems [/url]
    [url=http://www.forum365.org/index.php?topic=2037.0] actonel and side affects [/url]
    [url=http://yankeebizaar.com/forum/index.php?topic=2726.0] actonel warnings [/url]
    [url=http://maggiemcguinnesspub.com/chatroom/index.php?topic=7388.0] forum actonel [/url]
    [url=http://www.web-infor.com/forum/viewtopic.php?f=27&t=16875] actonel and managed care [/url]
    [url=http://ksb-alumni.ch/forum/viewtopic.php?f=1&t=4052] buy actonel online rezeptservice [/url]
    [url=http://lankanneeds.com/forum/index.php/topic,3446.0.html] actonel and vitamin d deficiency [/url]
    [url=http://www.midsouthguntalk.com/forums/viewtopic.php?f=12&t=5406] what is actonel [/url]

  5. Well , the view of the passage is totally correct ,your details is really reasonable and you guy give us valuable informative post, I totally agree the standpoint of upstairs. I often surfing on this forum when I m free and I find there are so much good information we can learn in this forum! http://less-accurate.com/

Comments are closed.