<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Washao</id>
	<title>Expertiza_Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Washao"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Washao"/>
	<updated>2026-09-11T17:15:16Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.41.0</generator>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15905</id>
		<title>CSC/ECE 517 Summer 2008/wiki3 7 ws</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15905"/>
		<updated>2008-07-26T23:41:44Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Actions Performed in the Shopper Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Shopper Pattern =&lt;br /&gt;
&lt;br /&gt;
== Preface ==&lt;br /&gt;
E-commerce has been increasingly popular these past few years and people who want a good deal are certainly taking full advantage of online shopping. Regardless of where online shoppers go, there is one consistent factor – the shopping cart. Shoppers shop online by adding items to the shopping cart and at the end can compare prices, remove items and make adjustments. There are certainly some variations of the shopping cart but the main functionalities are there as a “standard”. This “standard” leads to shopper pattern.&lt;br /&gt;
&lt;br /&gt;
=== Shopper Pattern Defined ===&lt;br /&gt;
Shopper pattern is the inner workings of online shopping – it helps in collecting items from providers (brand names, different products etc.) and presents them to the user. It takes in users' inputs (desire to purchase by adding to cart) and at the end display the contents the user desires. It helps in facilitating the final purchase and then communicates with the providers about the purchase. This pattern is basically a middleman – shoppers and providers have no knowledge of each other – shopper buys the product and the shopper pattern takes care of communicating to the provider. Of course in the E-commerce world there are fierce competitions – many competitors’ shopping carts might have more/better functionalities than others (mini shopping carts (Barnes &amp;amp; Noble), dynamic item availability (Amazon)) but they all branch from the basic shopper pattern.&lt;br /&gt;
&lt;br /&gt;
== Actors in the Pattern ==&lt;br /&gt;
The shopper pattern has three main actors: the consumer, the provider, and the cart.  &lt;br /&gt;
&lt;br /&gt;
=== Consumer ===&lt;br /&gt;
The consumer requests an item or multiple items to be placed in the cart.&lt;br /&gt;
&lt;br /&gt;
=== Provider ===&lt;br /&gt;
The provider is the entity or person that holds the items that consumers wish to attain.  The provider may not necessarily have what the consumer requests of it.&lt;br /&gt;
&lt;br /&gt;
=== Cart ===&lt;br /&gt;
The cart is the middleman between the consumer and provider.  Its job is to maintain the requests as agreed upon between the consumer and provider.&lt;br /&gt;
&lt;br /&gt;
=== Item ===&lt;br /&gt;
This is the object that the consumer desires, the provider possesses, and the cart tracks.  The requirement for an item is that it has to be an asset that can be conveyed from the provider to the consumer.&lt;br /&gt;
&lt;br /&gt;
== When to use a Shopper Pattern ==&lt;br /&gt;
* When a consumer could possibly want more than one different item from a provider.&lt;br /&gt;
* When a consumer could possibly want multiple of the same item from a provider.&lt;br /&gt;
* When a consumer may wish to take a break in shopping then return to shopping.&lt;br /&gt;
* When a consumer may wish to conduct payment at a later time.&lt;br /&gt;
&lt;br /&gt;
== Actions Performed in the Shopper Pattern ==&lt;br /&gt;
[[Image:Actor.jpg]]&lt;br /&gt;
&lt;br /&gt;
There are multiple actions performed by the consumer and provider on the cart.  They are as follows:&lt;br /&gt;
&lt;br /&gt;
=== Consumer ===&lt;br /&gt;
==== View cart ====&lt;br /&gt;
The consumer wishes to view his/her collection of items amassed in the cart.  This is a very important action because the provider can also influence what is in the cart, namely the quantity of items due to availability.&lt;br /&gt;
&lt;br /&gt;
==== Add to cart ====&lt;br /&gt;
The consumer requests that a certain quantity of an item be added to the cart.  The cart queries the provider as to whether the resources are available to furnish this request.  If so, the quantity of items is added to the cart.  If the full quantity cannot be added to the cart, the maximum quantity allowable is added (this includes when none are available).&lt;br /&gt;
&lt;br /&gt;
==== Update cart ====&lt;br /&gt;
The consumer changes a quantity of items in the cart. The cart does a query to the provider exactly like when an item is added to the cart.&lt;br /&gt;
&lt;br /&gt;
==== Remove from cart ====&lt;br /&gt;
The consumer requests that all of a certain type of item be removed from the cart.  The provider is notified of this action, but does not provide input.&lt;br /&gt;
&lt;br /&gt;
=== Shopper pattern ===&lt;br /&gt;
==== Check avail. ====&lt;br /&gt;
The shopper pattern checks the availability of items desired by the consumer by calling the provider.&lt;br /&gt;
&lt;br /&gt;
=== Provider ===&lt;br /&gt;
==== Update inven. ====&lt;br /&gt;
The provider can update the current inventory so the consumer can be informed of any sudden changes when updating the cart.&lt;br /&gt;
&lt;br /&gt;
== Exercising the Shopper Pattern ==&lt;br /&gt;
''Put a chart and stuff here that shows how it all works.''&lt;br /&gt;
&lt;br /&gt;
== Other Examples of Shopper Pattern ==&lt;br /&gt;
The shopper pattern does not have to be used for an e-commerce shopping cart.  There shopper pattern can be generalized as a collection of objects being provided by a provider and being requested by a consumer.  Some other examples of possible shopper pattern are:&lt;br /&gt;
* A library - A library patron (consumer) requesting books or other materials (items) from the library (provider).  The patron can make a list of materials needed to be picked up or checked out. In this example no money exchanges hands, payment in this case is just a promise to return the materials.&lt;br /&gt;
&lt;br /&gt;
= Resources =&lt;br /&gt;
* [http://www.welie.com/patterns/showPattern.php?patternID=shopping-cart Shopping Cart - Interactive Design Pattern Library]&lt;br /&gt;
* [http://ui-patterns.com/pattern/ShoppingCart Shopping Cart - UI-patterns.com]&lt;br /&gt;
* [http://www.surl.org/usabilitynews/92/shoppingcart.asp Usability News - Naidu]&lt;br /&gt;
* [http://www.guuui.com/browse.php?cid=152 Shopping Carts - GUUUI]&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15904</id>
		<title>CSC/ECE 517 Summer 2008/wiki3 7 ws</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15904"/>
		<updated>2008-07-26T23:41:04Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Actions Performed in the Shopper Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Shopper Pattern =&lt;br /&gt;
&lt;br /&gt;
== Preface ==&lt;br /&gt;
E-commerce has been increasingly popular these past few years and people who want a good deal are certainly taking full advantage of online shopping. Regardless of where online shoppers go, there is one consistent factor – the shopping cart. Shoppers shop online by adding items to the shopping cart and at the end can compare prices, remove items and make adjustments. There are certainly some variations of the shopping cart but the main functionalities are there as a “standard”. This “standard” leads to shopper pattern.&lt;br /&gt;
&lt;br /&gt;
=== Shopper Pattern Defined ===&lt;br /&gt;
Shopper pattern is the inner workings of online shopping – it helps in collecting items from providers (brand names, different products etc.) and presents them to the user. It takes in users' inputs (desire to purchase by adding to cart) and at the end display the contents the user desires. It helps in facilitating the final purchase and then communicates with the providers about the purchase. This pattern is basically a middleman – shoppers and providers have no knowledge of each other – shopper buys the product and the shopper pattern takes care of communicating to the provider. Of course in the E-commerce world there are fierce competitions – many competitors’ shopping carts might have more/better functionalities than others (mini shopping carts (Barnes &amp;amp; Noble), dynamic item availability (Amazon)) but they all branch from the basic shopper pattern.&lt;br /&gt;
&lt;br /&gt;
== Actors in the Pattern ==&lt;br /&gt;
The shopper pattern has three main actors: the consumer, the provider, and the cart.  &lt;br /&gt;
&lt;br /&gt;
=== Consumer ===&lt;br /&gt;
The consumer requests an item or multiple items to be placed in the cart.&lt;br /&gt;
&lt;br /&gt;
=== Provider ===&lt;br /&gt;
The provider is the entity or person that holds the items that consumers wish to attain.  The provider may not necessarily have what the consumer requests of it.&lt;br /&gt;
&lt;br /&gt;
=== Cart ===&lt;br /&gt;
The cart is the middleman between the consumer and provider.  Its job is to maintain the requests as agreed upon between the consumer and provider.&lt;br /&gt;
&lt;br /&gt;
=== Item ===&lt;br /&gt;
This is the object that the consumer desires, the provider possesses, and the cart tracks.  The requirement for an item is that it has to be an asset that can be conveyed from the provider to the consumer.&lt;br /&gt;
&lt;br /&gt;
== When to use a Shopper Pattern ==&lt;br /&gt;
* When a consumer could possibly want more than one different item from a provider.&lt;br /&gt;
* When a consumer could possibly want multiple of the same item from a provider.&lt;br /&gt;
* When a consumer may wish to take a break in shopping then return to shopping.&lt;br /&gt;
* When a consumer may wish to conduct payment at a later time.&lt;br /&gt;
&lt;br /&gt;
== Actions Performed in the Shopper Pattern ==&lt;br /&gt;
[[Image:Actor.jpg]]&lt;br /&gt;
&lt;br /&gt;
There are multiple actions performed by the consumer and provider on the cart.  They are as follows:&lt;br /&gt;
&lt;br /&gt;
=== Consumer ===&lt;br /&gt;
==== View cart ====&lt;br /&gt;
The consumer wishes to view his/her collection of items amassed in the cart.  This is a very important action because the provider can also influence what is in the cart, namely the quantity of items due to availability.&lt;br /&gt;
&lt;br /&gt;
==== Add to cart ====&lt;br /&gt;
The consumer requests that a certain quantity of an item be added to the cart.  The cart queries the provider as to whether the resources are available to furnish this request.  If so, the quantity of items is added to the cart.  If the full quantity cannot be added to the cart, the maximum quantity allowable is added (this includes when none are available).&lt;br /&gt;
&lt;br /&gt;
==== Update cart ====&lt;br /&gt;
The consumer changes a quantity of items in the cart. The cart does a query to the provider exactly like when an item is added to the cart.&lt;br /&gt;
&lt;br /&gt;
==== Remove from cart ====&lt;br /&gt;
The consumer requests that all of a certain type of item be removed from the cart.  The provider is notified of this action, but does not provide input.&lt;br /&gt;
&lt;br /&gt;
=== Shopper pattern ===&lt;br /&gt;
==== Check avail. ====&lt;br /&gt;
The shopper pattern checks the availability of items desired by the consumer by calling the provider.&lt;br /&gt;
&lt;br /&gt;
==== Update inven. ====&lt;br /&gt;
The provider can update the current inventory so the consumer can be informed of any sudden changes when updating the cart.&lt;br /&gt;
&lt;br /&gt;
== Exercising the Shopper Pattern ==&lt;br /&gt;
''Put a chart and stuff here that shows how it all works.''&lt;br /&gt;
&lt;br /&gt;
== Other Examples of Shopper Pattern ==&lt;br /&gt;
The shopper pattern does not have to be used for an e-commerce shopping cart.  There shopper pattern can be generalized as a collection of objects being provided by a provider and being requested by a consumer.  Some other examples of possible shopper pattern are:&lt;br /&gt;
* A library - A library patron (consumer) requesting books or other materials (items) from the library (provider).  The patron can make a list of materials needed to be picked up or checked out. In this example no money exchanges hands, payment in this case is just a promise to return the materials.&lt;br /&gt;
&lt;br /&gt;
= Resources =&lt;br /&gt;
* [http://www.welie.com/patterns/showPattern.php?patternID=shopping-cart Shopping Cart - Interactive Design Pattern Library]&lt;br /&gt;
* [http://ui-patterns.com/pattern/ShoppingCart Shopping Cart - UI-patterns.com]&lt;br /&gt;
* [http://www.surl.org/usabilitynews/92/shoppingcart.asp Usability News - Naidu]&lt;br /&gt;
* [http://www.guuui.com/browse.php?cid=152 Shopping Carts - GUUUI]&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15902</id>
		<title>CSC/ECE 517 Summer 2008/wiki3 7 ws</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15902"/>
		<updated>2008-07-26T23:39:22Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Actions Performed in the Shopper Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Shopper Pattern =&lt;br /&gt;
&lt;br /&gt;
== Preface ==&lt;br /&gt;
E-commerce has been increasingly popular these past few years and people who want a good deal are certainly taking full advantage of online shopping. Regardless of where online shoppers go, there is one consistent factor – the shopping cart. Shoppers shop online by adding items to the shopping cart and at the end can compare prices, remove items and make adjustments. There are certainly some variations of the shopping cart but the main functionalities are there as a “standard”. This “standard” leads to shopper pattern.&lt;br /&gt;
&lt;br /&gt;
=== Shopper Pattern Defined ===&lt;br /&gt;
Shopper pattern is the inner workings of online shopping – it helps in collecting items from providers (brand names, different products etc.) and presents them to the user. It takes in users' inputs (desire to purchase by adding to cart) and at the end display the contents the user desires. It helps in facilitating the final purchase and then communicates with the providers about the purchase. This pattern is basically a middleman – shoppers and providers have no knowledge of each other – shopper buys the product and the shopper pattern takes care of communicating to the provider. Of course in the E-commerce world there are fierce competitions – many competitors’ shopping carts might have more/better functionalities than others (mini shopping carts (Barnes &amp;amp; Noble), dynamic item availability (Amazon)) but they all branch from the basic shopper pattern.&lt;br /&gt;
&lt;br /&gt;
== Actors in the Pattern ==&lt;br /&gt;
The shopper pattern has three main actors: the consumer, the provider, and the cart.  &lt;br /&gt;
&lt;br /&gt;
=== Consumer ===&lt;br /&gt;
The consumer requests an item or multiple items to be placed in the cart.&lt;br /&gt;
&lt;br /&gt;
=== Provider ===&lt;br /&gt;
The provider is the entity or person that holds the items that consumers wish to attain.  The provider may not necessarily have what the consumer requests of it.&lt;br /&gt;
&lt;br /&gt;
=== Cart ===&lt;br /&gt;
The cart is the middleman between the consumer and provider.  Its job is to maintain the requests as agreed upon between the consumer and provider.&lt;br /&gt;
&lt;br /&gt;
=== Item ===&lt;br /&gt;
This is the object that the consumer desires, the provider possesses, and the cart tracks.  The requirement for an item is that it has to be an asset that can be conveyed from the provider to the consumer.&lt;br /&gt;
&lt;br /&gt;
== When to use a Shopper Pattern ==&lt;br /&gt;
* When a consumer could possibly want more than one different item from a provider.&lt;br /&gt;
* When a consumer could possibly want multiple of the same item from a provider.&lt;br /&gt;
* When a consumer may wish to take a break in shopping then return to shopping.&lt;br /&gt;
* When a consumer may wish to conduct payment at a later time.&lt;br /&gt;
&lt;br /&gt;
== Actions Performed in the Shopper Pattern ==&lt;br /&gt;
[[Image:Actor.jpg]]&lt;br /&gt;
&lt;br /&gt;
There are multiple actions performed by the consumer and provider on the cart.  They are as follows:&lt;br /&gt;
&lt;br /&gt;
=== View cart ===&lt;br /&gt;
The consumer wishes to view his/her collection of items amassed in the cart.  This is a very important action because the provider can also influence what is in the cart, namely the quantity of items due to availability.&lt;br /&gt;
&lt;br /&gt;
=== Add to cart ===&lt;br /&gt;
The consumer requests that a certain quantity of an item be added to the cart.  The cart queries the provider as to whether the resources are available to furnish this request.  If so, the quantity of items is added to the cart.  If the full quantity cannot be added to the cart, the maximum quantity allowable is added (this includes when none are available).&lt;br /&gt;
&lt;br /&gt;
=== Update cart ===&lt;br /&gt;
The consumer changes a quantity of items in the cart. The cart does a query to the provider exactly like when an item is added to the cart.&lt;br /&gt;
&lt;br /&gt;
=== Remove from cart ===&lt;br /&gt;
The consumer requests that all of a certain type of item be removed from the cart.  The provider is notified of this action, but does not provide input.&lt;br /&gt;
&lt;br /&gt;
=== Check avail. ===&lt;br /&gt;
The shopper pattern checks the availability of items desired by the consumer by calling the provider.&lt;br /&gt;
&lt;br /&gt;
=== Update inven. ===&lt;br /&gt;
The provider can update the current inventory so the consumer can be informed of any sudden changes when updating the cart.&lt;br /&gt;
&lt;br /&gt;
== Exercising the Shopper Pattern ==&lt;br /&gt;
''Put a chart and stuff here that shows how it all works.''&lt;br /&gt;
&lt;br /&gt;
== Other Examples of Shopper Pattern ==&lt;br /&gt;
The shopper pattern does not have to be used for an e-commerce shopping cart.  There shopper pattern can be generalized as a collection of objects being provided by a provider and being requested by a consumer.  Some other examples of possible shopper pattern are:&lt;br /&gt;
* A library - A library patron (consumer) requesting books or other materials (items) from the library (provider).  The patron can make a list of materials needed to be picked up or checked out. In this example no money exchanges hands, payment in this case is just a promise to return the materials.&lt;br /&gt;
&lt;br /&gt;
= Resources =&lt;br /&gt;
* [http://www.welie.com/patterns/showPattern.php?patternID=shopping-cart Shopping Cart - Interactive Design Pattern Library]&lt;br /&gt;
* [http://ui-patterns.com/pattern/ShoppingCart Shopping Cart - UI-patterns.com]&lt;br /&gt;
* [http://www.surl.org/usabilitynews/92/shoppingcart.asp Usability News - Naidu]&lt;br /&gt;
* [http://www.guuui.com/browse.php?cid=152 Shopping Carts - GUUUI]&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15901</id>
		<title>CSC/ECE 517 Summer 2008/wiki3 7 ws</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15901"/>
		<updated>2008-07-26T23:38:32Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Actions Performed in the Shopper Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Shopper Pattern =&lt;br /&gt;
&lt;br /&gt;
== Preface ==&lt;br /&gt;
E-commerce has been increasingly popular these past few years and people who want a good deal are certainly taking full advantage of online shopping. Regardless of where online shoppers go, there is one consistent factor – the shopping cart. Shoppers shop online by adding items to the shopping cart and at the end can compare prices, remove items and make adjustments. There are certainly some variations of the shopping cart but the main functionalities are there as a “standard”. This “standard” leads to shopper pattern.&lt;br /&gt;
&lt;br /&gt;
=== Shopper Pattern Defined ===&lt;br /&gt;
Shopper pattern is the inner workings of online shopping – it helps in collecting items from providers (brand names, different products etc.) and presents them to the user. It takes in users' inputs (desire to purchase by adding to cart) and at the end display the contents the user desires. It helps in facilitating the final purchase and then communicates with the providers about the purchase. This pattern is basically a middleman – shoppers and providers have no knowledge of each other – shopper buys the product and the shopper pattern takes care of communicating to the provider. Of course in the E-commerce world there are fierce competitions – many competitors’ shopping carts might have more/better functionalities than others (mini shopping carts (Barnes &amp;amp; Noble), dynamic item availability (Amazon)) but they all branch from the basic shopper pattern.&lt;br /&gt;
&lt;br /&gt;
== Actors in the Pattern ==&lt;br /&gt;
The shopper pattern has three main actors: the consumer, the provider, and the cart.  &lt;br /&gt;
&lt;br /&gt;
=== Consumer ===&lt;br /&gt;
The consumer requests an item or multiple items to be placed in the cart.&lt;br /&gt;
&lt;br /&gt;
=== Provider ===&lt;br /&gt;
The provider is the entity or person that holds the items that consumers wish to attain.  The provider may not necessarily have what the consumer requests of it.&lt;br /&gt;
&lt;br /&gt;
=== Cart ===&lt;br /&gt;
The cart is the middleman between the consumer and provider.  Its job is to maintain the requests as agreed upon between the consumer and provider.&lt;br /&gt;
&lt;br /&gt;
=== Item ===&lt;br /&gt;
This is the object that the consumer desires, the provider possesses, and the cart tracks.  The requirement for an item is that it has to be an asset that can be conveyed from the provider to the consumer.&lt;br /&gt;
&lt;br /&gt;
== When to use a Shopper Pattern ==&lt;br /&gt;
* When a consumer could possibly want more than one different item from a provider.&lt;br /&gt;
* When a consumer could possibly want multiple of the same item from a provider.&lt;br /&gt;
* When a consumer may wish to take a break in shopping then return to shopping.&lt;br /&gt;
* When a consumer may wish to conduct payment at a later time.&lt;br /&gt;
&lt;br /&gt;
== Actions Performed in the Shopper Pattern ==&lt;br /&gt;
[[Image:Actor.jpg]]&lt;br /&gt;
&lt;br /&gt;
There are multiple actions performed by the consumer and provider on the cart.  They are as follows:&lt;br /&gt;
&lt;br /&gt;
=== View Cart ===&lt;br /&gt;
The consumer wishes to view his/her collection of items amassed in the cart.  This is a very important action because the provider can also influence what is in the cart, namely the quantity of items due to availability.&lt;br /&gt;
&lt;br /&gt;
=== Add to Cart ===&lt;br /&gt;
The consumer requests that a certain quantity of an item be added to the cart.  The cart queries the provider as to whether the resources are available to furnish this request.  If so, the quantity of items is added to the cart.  If the full quantity cannot be added to the cart, the maximum quantity allowable is added (this includes when none are available).&lt;br /&gt;
&lt;br /&gt;
=== Update Cart ===&lt;br /&gt;
The consumer changes a quantity of items in the cart. The cart does a query to the provider exactly like when an item is added to the cart.&lt;br /&gt;
&lt;br /&gt;
=== Remove from Cart ===&lt;br /&gt;
The consumer requests that all of a certain type of item be removed from the cart.  The provider is notified of this action, but does not provide input.&lt;br /&gt;
&lt;br /&gt;
=== Check avail. ===&lt;br /&gt;
The shopper pattern checks the availability of items desired by the consumer by calling the provider.&lt;br /&gt;
&lt;br /&gt;
=== Update inven. ===&lt;br /&gt;
The provider can update the current inventory so the consumer can be informed of any sudden changes when updating the cart.&lt;br /&gt;
&lt;br /&gt;
== Exercising the Shopper Pattern ==&lt;br /&gt;
''Put a chart and stuff here that shows how it all works.''&lt;br /&gt;
&lt;br /&gt;
== Other Examples of Shopper Pattern ==&lt;br /&gt;
The shopper pattern does not have to be used for an e-commerce shopping cart.  There shopper pattern can be generalized as a collection of objects being provided by a provider and being requested by a consumer.  Some other examples of possible shopper pattern are:&lt;br /&gt;
* A library - A library patron (consumer) requesting books or other materials (items) from the library (provider).  The patron can make a list of materials needed to be picked up or checked out. In this example no money exchanges hands, payment in this case is just a promise to return the materials.&lt;br /&gt;
&lt;br /&gt;
= Resources =&lt;br /&gt;
* [http://www.welie.com/patterns/showPattern.php?patternID=shopping-cart Shopping Cart - Interactive Design Pattern Library]&lt;br /&gt;
* [http://ui-patterns.com/pattern/ShoppingCart Shopping Cart - UI-patterns.com]&lt;br /&gt;
* [http://www.surl.org/usabilitynews/92/shoppingcart.asp Usability News - Naidu]&lt;br /&gt;
* [http://www.guuui.com/browse.php?cid=152 Shopping Carts - GUUUI]&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15893</id>
		<title>CSC/ECE 517 Summer 2008/wiki3 7 ws</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15893"/>
		<updated>2008-07-26T23:29:13Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Actions Performed in the Shopper Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Shopper Pattern =&lt;br /&gt;
&lt;br /&gt;
== Preface ==&lt;br /&gt;
E-commerce has been increasingly popular these past few years and people who want a good deal are certainly taking full advantage of online shopping. Regardless of where online shoppers go, there is one consistent factor – the shopping cart. Shoppers shop online by adding items to the shopping cart and at the end can compare prices, remove items and make adjustments. There are certainly some variations of the shopping cart but the main functionalities are there as a “standard”. This “standard” leads to shopper pattern.&lt;br /&gt;
&lt;br /&gt;
=== Shopper Pattern Defined ===&lt;br /&gt;
Shopper pattern is the inner workings of online shopping – it helps in collecting items from providers (brand names, different products etc.) and presents them to the user. It takes in users' inputs (desire to purchase by adding to cart) and at the end display the contents the user desires. It helps in facilitating the final purchase and then communicates with the providers about the purchase. This pattern is basically a middleman – shoppers and providers have no knowledge of each other – shopper buys the product and the shopper pattern takes care of communicating to the provider. Of course in the E-commerce world there are fierce competitions – many competitors’ shopping carts might have more/better functionalities than others (mini shopping carts (Barnes &amp;amp; Noble), dynamic item availability (Amazon)) but they all branch from the basic shopper pattern.&lt;br /&gt;
&lt;br /&gt;
== Actors in the Pattern ==&lt;br /&gt;
The shopper pattern has three main actors: the consumer, the provider, and the cart.  &lt;br /&gt;
&lt;br /&gt;
=== Consumer ===&lt;br /&gt;
The consumer requests an item or multiple items to be placed in the cart.&lt;br /&gt;
&lt;br /&gt;
=== Provider ===&lt;br /&gt;
The provider is the entity or person that holds the items that consumers wish to attain.  The provider may not necessarily have what the consumer requests of it.&lt;br /&gt;
&lt;br /&gt;
=== Cart ===&lt;br /&gt;
The cart is the middleman between the consumer and provider.  Its job is to maintain the requests as agreed upon between the consumer and provider.&lt;br /&gt;
&lt;br /&gt;
=== Item ===&lt;br /&gt;
This is the object that the consumer desires, the provider possesses, and the cart tracks.  The requirement for an item is that it has to be an asset that can be conveyed from the provider to the consumer.&lt;br /&gt;
&lt;br /&gt;
== When to use a Shopper Pattern ==&lt;br /&gt;
* When a consumer could possibly want more than one different item from a provider.&lt;br /&gt;
* When a consumer could possibly want multiple of the same item from a provider.&lt;br /&gt;
* When a consumer may wish to take a break in shopping then return to shopping.&lt;br /&gt;
* When a consumer may wish to conduct payment at a later time.&lt;br /&gt;
&lt;br /&gt;
== Actions Performed in the Shopper Pattern ==&lt;br /&gt;
[[Image:Actor.jpg]]&lt;br /&gt;
&lt;br /&gt;
There are multiple actions performed by the consumer and provider on the cart.  They are as follows:&lt;br /&gt;
&lt;br /&gt;
=== View Cart ===&lt;br /&gt;
The consumer wishes to view his/her collection of items amassed in the cart.  This is a very important action because the provider can also influence what is in the cart, namely the quantity of items due to availability.&lt;br /&gt;
&lt;br /&gt;
=== Add to Cart ===&lt;br /&gt;
The consumer requests that a certain quantity of an item be added to the cart.  The cart queries the provider as to whether the resources are available to furnish this request.  If so, the quantity of items is added to the cart.  If the full quantity cannot be added to the cart, the maximum quantity allowable is added (this includes when none are available).&lt;br /&gt;
&lt;br /&gt;
=== Update Cart ===&lt;br /&gt;
The consumer changes a quantity of items in the cart. The cart does a query to the provider exactly like when an item is added to the cart.&lt;br /&gt;
&lt;br /&gt;
=== Remove from Cart ===&lt;br /&gt;
The consumer requests that all of a certain type of item be removed from the cart.  The provider is notified of this action, but does not provide input.&lt;br /&gt;
&lt;br /&gt;
== Exercising the Shopper Pattern ==&lt;br /&gt;
''Put a chart and stuff here that shows how it all works.''&lt;br /&gt;
&lt;br /&gt;
== Other Examples of Shopper Pattern ==&lt;br /&gt;
The shopper pattern does not have to be used for an e-commerce shopping cart.  There shopper pattern can be generalized as a collection of objects being provided by a provider and being requested by a consumer.  Some other examples of possible shopper pattern are:&lt;br /&gt;
* A library - A library patron (consumer) requesting books or other materials (items) from the library (provider).  The patron can make a list of materials needed to be picked up or checked out. In this example no money exchanges hands, payment in this case is just a promise to return the materials.&lt;br /&gt;
&lt;br /&gt;
= Resources =&lt;br /&gt;
* [http://www.welie.com/patterns/showPattern.php?patternID=shopping-cart Shopping Cart - Interactive Design Pattern Library]&lt;br /&gt;
* [http://ui-patterns.com/pattern/ShoppingCart Shopping Cart - UI-patterns.com]&lt;br /&gt;
* [http://www.surl.org/usabilitynews/92/shoppingcart.asp Usability News - Naidu]&lt;br /&gt;
* [http://www.guuui.com/browse.php?cid=152 Shopping Carts - GUUUI]&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15891</id>
		<title>CSC/ECE 517 Summer 2008/wiki3 7 ws</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15891"/>
		<updated>2008-07-26T23:28:36Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Actors in the Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Shopper Pattern =&lt;br /&gt;
&lt;br /&gt;
== Preface ==&lt;br /&gt;
E-commerce has been increasingly popular these past few years and people who want a good deal are certainly taking full advantage of online shopping. Regardless of where online shoppers go, there is one consistent factor – the shopping cart. Shoppers shop online by adding items to the shopping cart and at the end can compare prices, remove items and make adjustments. There are certainly some variations of the shopping cart but the main functionalities are there as a “standard”. This “standard” leads to shopper pattern.&lt;br /&gt;
&lt;br /&gt;
=== Shopper Pattern Defined ===&lt;br /&gt;
Shopper pattern is the inner workings of online shopping – it helps in collecting items from providers (brand names, different products etc.) and presents them to the user. It takes in users' inputs (desire to purchase by adding to cart) and at the end display the contents the user desires. It helps in facilitating the final purchase and then communicates with the providers about the purchase. This pattern is basically a middleman – shoppers and providers have no knowledge of each other – shopper buys the product and the shopper pattern takes care of communicating to the provider. Of course in the E-commerce world there are fierce competitions – many competitors’ shopping carts might have more/better functionalities than others (mini shopping carts (Barnes &amp;amp; Noble), dynamic item availability (Amazon)) but they all branch from the basic shopper pattern.&lt;br /&gt;
&lt;br /&gt;
== Actors in the Pattern ==&lt;br /&gt;
The shopper pattern has three main actors: the consumer, the provider, and the cart.  &lt;br /&gt;
&lt;br /&gt;
=== Consumer ===&lt;br /&gt;
The consumer requests an item or multiple items to be placed in the cart.&lt;br /&gt;
&lt;br /&gt;
=== Provider ===&lt;br /&gt;
The provider is the entity or person that holds the items that consumers wish to attain.  The provider may not necessarily have what the consumer requests of it.&lt;br /&gt;
&lt;br /&gt;
=== Cart ===&lt;br /&gt;
The cart is the middleman between the consumer and provider.  Its job is to maintain the requests as agreed upon between the consumer and provider.&lt;br /&gt;
&lt;br /&gt;
=== Item ===&lt;br /&gt;
This is the object that the consumer desires, the provider possesses, and the cart tracks.  The requirement for an item is that it has to be an asset that can be conveyed from the provider to the consumer.&lt;br /&gt;
&lt;br /&gt;
== When to use a Shopper Pattern ==&lt;br /&gt;
* When a consumer could possibly want more than one different item from a provider.&lt;br /&gt;
* When a consumer could possibly want multiple of the same item from a provider.&lt;br /&gt;
* When a consumer may wish to take a break in shopping then return to shopping.&lt;br /&gt;
* When a consumer may wish to conduct payment at a later time.&lt;br /&gt;
&lt;br /&gt;
== Actions Performed in the Shopper Pattern ==&lt;br /&gt;
There are multiple actions performed by the consumer and provider on the cart.  They are as follows:&lt;br /&gt;
&lt;br /&gt;
=== View Cart ===&lt;br /&gt;
The consumer wishes to view his/her collection of items amassed in the cart.  This is a very important action because the provider can also influence what is in the cart, namely the quantity of items due to availability.&lt;br /&gt;
&lt;br /&gt;
=== Add to Cart ===&lt;br /&gt;
The consumer requests that a certain quantity of an item be added to the cart.  The cart queries the provider as to whether the resources are available to furnish this request.  If so, the quantity of items is added to the cart.  If the full quantity cannot be added to the cart, the maximum quantity allowable is added (this includes when none are available).&lt;br /&gt;
&lt;br /&gt;
=== Update Cart ===&lt;br /&gt;
The consumer changes a quantity of items in the cart. The cart does a query to the provider exactly like when an item is added to the cart.&lt;br /&gt;
&lt;br /&gt;
=== Remove from Cart ===&lt;br /&gt;
The consumer requests that all of a certain type of item be removed from the cart.  The provider is notified of this action, but does not provide input.&lt;br /&gt;
&lt;br /&gt;
== Exercising the Shopper Pattern ==&lt;br /&gt;
''Put a chart and stuff here that shows how it all works.''&lt;br /&gt;
&lt;br /&gt;
== Other Examples of Shopper Pattern ==&lt;br /&gt;
The shopper pattern does not have to be used for an e-commerce shopping cart.  There shopper pattern can be generalized as a collection of objects being provided by a provider and being requested by a consumer.  Some other examples of possible shopper pattern are:&lt;br /&gt;
* A library - A library patron (consumer) requesting books or other materials (items) from the library (provider).  The patron can make a list of materials needed to be picked up or checked out. In this example no money exchanges hands, payment in this case is just a promise to return the materials.&lt;br /&gt;
&lt;br /&gt;
= Resources =&lt;br /&gt;
* [http://www.welie.com/patterns/showPattern.php?patternID=shopping-cart Shopping Cart - Interactive Design Pattern Library]&lt;br /&gt;
* [http://ui-patterns.com/pattern/ShoppingCart Shopping Cart - UI-patterns.com]&lt;br /&gt;
* [http://www.surl.org/usabilitynews/92/shoppingcart.asp Usability News - Naidu]&lt;br /&gt;
* [http://www.guuui.com/browse.php?cid=152 Shopping Carts - GUUUI]&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15890</id>
		<title>CSC/ECE 517 Summer 2008/wiki3 7 ws</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15890"/>
		<updated>2008-07-26T23:28:11Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Actors in the Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Shopper Pattern =&lt;br /&gt;
&lt;br /&gt;
== Preface ==&lt;br /&gt;
E-commerce has been increasingly popular these past few years and people who want a good deal are certainly taking full advantage of online shopping. Regardless of where online shoppers go, there is one consistent factor – the shopping cart. Shoppers shop online by adding items to the shopping cart and at the end can compare prices, remove items and make adjustments. There are certainly some variations of the shopping cart but the main functionalities are there as a “standard”. This “standard” leads to shopper pattern.&lt;br /&gt;
&lt;br /&gt;
=== Shopper Pattern Defined ===&lt;br /&gt;
Shopper pattern is the inner workings of online shopping – it helps in collecting items from providers (brand names, different products etc.) and presents them to the user. It takes in users' inputs (desire to purchase by adding to cart) and at the end display the contents the user desires. It helps in facilitating the final purchase and then communicates with the providers about the purchase. This pattern is basically a middleman – shoppers and providers have no knowledge of each other – shopper buys the product and the shopper pattern takes care of communicating to the provider. Of course in the E-commerce world there are fierce competitions – many competitors’ shopping carts might have more/better functionalities than others (mini shopping carts (Barnes &amp;amp; Noble), dynamic item availability (Amazon)) but they all branch from the basic shopper pattern.&lt;br /&gt;
&lt;br /&gt;
== Actors in the Pattern ==&lt;br /&gt;
The shopper pattern has three main actors: the consumer, the provider, and the cart.  &lt;br /&gt;
&lt;br /&gt;
=== Consumer ===&lt;br /&gt;
The consumer requests an item or multiple items to be placed in the cart.&lt;br /&gt;
&lt;br /&gt;
=== Provider ===&lt;br /&gt;
The provider is the entity or person that holds the items that consumers wish to attain.  The provider may not necessarily have what the consumer requests of it.&lt;br /&gt;
&lt;br /&gt;
=== Cart ===&lt;br /&gt;
The cart is the middleman between the consumer and provider.  Its job is to maintain the requests as agreed upon between the consumer and provider.&lt;br /&gt;
&lt;br /&gt;
=== Item ===&lt;br /&gt;
This is the object that the consumer desires, the provider possesses, and the cart tracks.  The requirement for an item is that it has to be an asset that can be conveyed from the provider to the consumer.&lt;br /&gt;
&lt;br /&gt;
[[Image:Actor.jpg]]&lt;br /&gt;
&lt;br /&gt;
== When to use a Shopper Pattern ==&lt;br /&gt;
* When a consumer could possibly want more than one different item from a provider.&lt;br /&gt;
* When a consumer could possibly want multiple of the same item from a provider.&lt;br /&gt;
* When a consumer may wish to take a break in shopping then return to shopping.&lt;br /&gt;
* When a consumer may wish to conduct payment at a later time.&lt;br /&gt;
&lt;br /&gt;
== Actions Performed in the Shopper Pattern ==&lt;br /&gt;
There are multiple actions performed by the consumer and provider on the cart.  They are as follows:&lt;br /&gt;
&lt;br /&gt;
=== View Cart ===&lt;br /&gt;
The consumer wishes to view his/her collection of items amassed in the cart.  This is a very important action because the provider can also influence what is in the cart, namely the quantity of items due to availability.&lt;br /&gt;
&lt;br /&gt;
=== Add to Cart ===&lt;br /&gt;
The consumer requests that a certain quantity of an item be added to the cart.  The cart queries the provider as to whether the resources are available to furnish this request.  If so, the quantity of items is added to the cart.  If the full quantity cannot be added to the cart, the maximum quantity allowable is added (this includes when none are available).&lt;br /&gt;
&lt;br /&gt;
=== Update Cart ===&lt;br /&gt;
The consumer changes a quantity of items in the cart. The cart does a query to the provider exactly like when an item is added to the cart.&lt;br /&gt;
&lt;br /&gt;
=== Remove from Cart ===&lt;br /&gt;
The consumer requests that all of a certain type of item be removed from the cart.  The provider is notified of this action, but does not provide input.&lt;br /&gt;
&lt;br /&gt;
== Exercising the Shopper Pattern ==&lt;br /&gt;
''Put a chart and stuff here that shows how it all works.''&lt;br /&gt;
&lt;br /&gt;
== Other Examples of Shopper Pattern ==&lt;br /&gt;
The shopper pattern does not have to be used for an e-commerce shopping cart.  There shopper pattern can be generalized as a collection of objects being provided by a provider and being requested by a consumer.  Some other examples of possible shopper pattern are:&lt;br /&gt;
* A library - A library patron (consumer) requesting books or other materials (items) from the library (provider).  The patron can make a list of materials needed to be picked up or checked out. In this example no money exchanges hands, payment in this case is just a promise to return the materials.&lt;br /&gt;
&lt;br /&gt;
= Resources =&lt;br /&gt;
* [http://www.welie.com/patterns/showPattern.php?patternID=shopping-cart Shopping Cart - Interactive Design Pattern Library]&lt;br /&gt;
* [http://ui-patterns.com/pattern/ShoppingCart Shopping Cart - UI-patterns.com]&lt;br /&gt;
* [http://www.surl.org/usabilitynews/92/shoppingcart.asp Usability News - Naidu]&lt;br /&gt;
* [http://www.guuui.com/browse.php?cid=152 Shopping Carts - GUUUI]&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Actor.jpg&amp;diff=15889</id>
		<title>File:Actor.jpg</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Actor.jpg&amp;diff=15889"/>
		<updated>2008-07-26T23:27:44Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15252</id>
		<title>CSC/ECE 517 Summer 2008/wiki3 7 ws</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki3_7_ws&amp;diff=15252"/>
		<updated>2008-07-24T12:48:19Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Place holder for wei and mike wiki&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=14272</id>
		<title>CSC/ECE 517 Summer 2008/wiki2 6 cc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=14272"/>
		<updated>2008-07-07T18:10:35Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;''Cohesion and coupling. Cohesion and coupling are concepts that are reasonably easy to understand, but nonetheless, it is worthwhile to gather readable illustrations of where they apply. Browse the hundreds of Web pages that attempt to explain these concepts, picking your favorite examples. Categorize these examples, so that the reader will see the big picture, rather than just a set of redundant illustrations. Many of these pages mention related concepts; list some of them and explain how they relate to cohesion and coupling.''&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29 Cohesion] is a measure of how strongly-related and focused the various responsibilities of a software module are. It is usually expressed as “high” or “low” cohesion when being discussed. High cohesion is desired because it is robust, reliable, reusable and more understandable whereas low cohesion has the opposite of those traits – difficult to maintain, test, reuse and understand. With high cohesion comes low coupling. Coupling is the degree of dependence of internal implementation between different modules – low coupling is where the module doesn't depend on what other module's internal implementation does thus a change in them won't affect the module whereas high coupling is where a change in one module might “break” other modules because they are highly dependent on eachother's internal implementations.  This page will show you different types of cohesion and coupling and examples showing the “big picture” of them. &lt;br /&gt;
&lt;br /&gt;
== Cohesion ==&lt;br /&gt;
&lt;br /&gt;
Cohesion is categorized in “high” and “low” but  it is “measured” by how strongly-related or focused the responsibilities are for the class. In a highly-cohesive system, code readability and reusability is increased while complexity is kept manageable. A class of high cohesiveness could decrease its “cohesiveness” by carrying out more varied activities that have little in common and increasing complexity.  Below we describe the different types of cohesion arranged from highest to lowest cohesion.&lt;br /&gt;
&lt;br /&gt;
=====Functional Cohesion=====&lt;br /&gt;
Functional cohesion describes a module that is designed to perform one and only one task.  A functionally cohesive module may contain multiple methods, but all of these methods are designed to help the user achieve a single task.  The following example illustrates functional cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Stack {&lt;br /&gt;
    public Stack() {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void push(Object obj) {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public Object pop() {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  &lt;br /&gt;
    public Object peek() {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public int isEmpty() {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Sequential Cohesion=====&lt;br /&gt;
Sequential cohesion describes modules whose operations are intended to be executed in sequence with the output of each operation providing input to the subsequently executed operation.  The following example illustrates sequential cohesion.&lt;br /&gt;
&lt;br /&gt;
   class Cube {&lt;br /&gt;
       public ArrayList getInfo(){ &lt;br /&gt;
              ArrayList tempList = new ArrayList();&lt;br /&gt;
              tempList.add(getArea());&lt;br /&gt;
              tempList.add(getVolume());&lt;br /&gt;
              return tempList;&lt;br /&gt;
       }&lt;br /&gt;
       public double getArea(){return 6*side*side;} &lt;br /&gt;
       public double getVolume(){return side*side*side;}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
===== Information cohesion =====&lt;br /&gt;
Information cohesion can do several things with the same data - a class with various methods using same data.  The following example illustrates information cohesion.&lt;br /&gt;
&lt;br /&gt;
     class Circle {&lt;br /&gt;
          double radius;	      &lt;br /&gt;
          public double getArea(){return 3.14*radius*radius;}&lt;br /&gt;
          public double getDiameter(){return 2 * radius;}&lt;br /&gt;
          public double getCircumference(){return 3.14*2*radius;}&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
=====Communicational Cohesion=====&lt;br /&gt;
Communicational cohesion describes modules that perform multiple operations on the same input or output data.  The following example illustrates communication cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class CustomerInformation {&lt;br /&gt;
    public CustomerInformation(int accountNum) {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public String getName() {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float getBalance() {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Procedural Cohesion=====&lt;br /&gt;
Procedural cohesion is similar to sequential cohesion in that the operations exposed are typically grouped because they are executed within a sequence.  Unlike sequential cohesion however, the operations within a procedurally cohesive module can be somewhat unrelated and output from one operation is not necessarily used as input to a subsequently executed operation.  The following example illustrates procedural cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Student {&lt;br /&gt;
    public Student(int studentId) {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void LoadStudent() {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateGrades(int[] grades) {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateAttendance(Date[] dates) {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void SaveStudent() {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Temporal Cohesion=====&lt;br /&gt;
Temporal cohesion describes a module that has several operations grouped by the fact that the operations are executed within temporal proximity.  The following example illustrates temporal cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Startup {&lt;br /&gt;
    public void Initialize() {&lt;br /&gt;
       InitializeLogging();&lt;br /&gt;
       &lt;br /&gt;
       InitializeUI();&lt;br /&gt;
       &lt;br /&gt;
       InitializeDb();&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeLogging() {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeUI() {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeDb() {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Logical Cohesion=====&lt;br /&gt;
Logical cohesion describes a module that groups operations because categorically they are related but the operations themselves are quite different.  Typically, these modules accept a control flag which indicates which operation to execute.  The following example illustrates logical cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class DataStore {&lt;br /&gt;
    public void SaveData(int destination, byte[] data) {&lt;br /&gt;
      switch (destination) {&lt;br /&gt;
        default:&lt;br /&gt;
        case 0:&lt;br /&gt;
          SaveToDb(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 1:&lt;br /&gt;
          SaveToFile(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 2:&lt;br /&gt;
          SaveToWebService(data)&lt;br /&gt;
          break;&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToDb(byte[] data) {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToFile(byte[] data) {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToWebService(byte[] data) {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Coincidental Cohesion=====&lt;br /&gt;
Coincidental cohesion describes a module whose operations are unrelated to one another and the module itself can be used to achieve several different types of tasks.  The following example illustrates coincidental cohesion [http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-cohesion-16069].&lt;br /&gt;
&lt;br /&gt;
  public static class Math {&lt;br /&gt;
    public static int Add(int a, int b) {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public static int Subtract(int a, int b) {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===Advantages and Disadvantages===&lt;br /&gt;
Cohesion is the idea that the module does a single task - be it calculating data, checking file etc. The &amp;quot;single task mindedness&amp;quot; drastically reduces code breaking when other modules are changed. If the module uses data from multiple other modules - if even one module changes or breaks, this module might need to be changed thus more time wasted. With single task modules, individual modules can be changed with very little problem.&lt;br /&gt;
&lt;br /&gt;
==Coupling==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Coupling_%28computer_science%29 Coupling] is categorized low (loose or weak) or high (tight or strong). Low coupling is a relationship where one module interacts with another module through a stable interface and does not need to be concerned with other module's implementation. With low coupling, a change in one module will not require changes in the implementation of another module (since they are not dependent on each other). High coupling introduces problems like one module change into multiple module changes, difficulty of understanding the relationships and difficulty of testing and reusing individual modules because of high dependence. Low coupling facilitates high cohesion and vice versa. Low coupling may also reduce performance, and a highly-coupled system is sometimes desirable to achieve maximum efficiency.  Below we describe the different types of coupling arranged from highest to lowest coupling.&lt;br /&gt;
&lt;br /&gt;
=====Content coupling===== &lt;br /&gt;
Content coupling occurs when one or more modules access the internals of another module.  The following example illustrates content coupling.&lt;br /&gt;
&lt;br /&gt;
  public class Rectangle {&lt;br /&gt;
  &lt;br /&gt;
    public int Top = 0;&lt;br /&gt;
    public int Left = 0;&lt;br /&gt;
    public int Width = 0;&lt;br /&gt;
    public int Height = 0;&lt;br /&gt;
    &lt;br /&gt;
    public Rectangle(int top, int left, int width, int height) {&lt;br /&gt;
      this.Top = top;&lt;br /&gt;
      this.Left = left;&lt;br /&gt;
      this.Width = width;&lt;br /&gt;
      this.Height = Height;&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    public int getArea() {&lt;br /&gt;
      return this.Width * this.Height;&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  public class FloorPlan {&lt;br /&gt;
    Rectangle rectangle = null;&lt;br /&gt;
  &lt;br /&gt;
    public FloorPlan(int width, int height) {&lt;br /&gt;
      rectangle = new Rectangle(0, 0, 50, 100);&lt;br /&gt;
    }&lt;br /&gt;
  &lt;br /&gt;
    public void modifyDimensions(int width, int height) {&lt;br /&gt;
      rectangle.Width = width;&lt;br /&gt;
      rectangle.Height = height;&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public int getArea() {&lt;br /&gt;
      return rectangle.getArea();&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In this example, &amp;lt;code&amp;gt;FloorPlan&amp;lt;/code&amp;gt; is able to directly modify the &amp;lt;code&amp;gt;Width&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;Height&amp;lt;/code&amp;gt; fields of the &amp;lt;code&amp;gt;Rectangle&amp;lt;/code&amp;gt; object.  This coupling creates a dependency from &amp;lt;code&amp;gt;FloorPlan&amp;lt;/code&amp;gt; on the internals of the &amp;lt;code&amp;gt;Rectangle&amp;lt;/code&amp;gt; object that inhibits maintenance of the &amp;lt;code&amp;gt;Rectangle&amp;lt;/code&amp;gt; class.  If someone wanted to go back and change the &amp;lt;code&amp;gt;Width&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;Height&amp;lt;/code&amp;gt; fields of &amp;lt;code&amp;gt;Rectangle&amp;lt;/code&amp;gt; class to use a different data type they would also have to update the &amp;lt;code&amp;gt;FloorPlan&amp;lt;/code&amp;gt; class.   &lt;br /&gt;
&lt;br /&gt;
=====Common coupling===== &lt;br /&gt;
Common coupling occurs when two or more modules modify the same same global variable.  The following example illustrates common coupling.&lt;br /&gt;
&lt;br /&gt;
  #include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
  #include &amp;lt;string.h&amp;gt;&lt;br /&gt;
  &lt;br /&gt;
  #define NUM_FIELDS 3&lt;br /&gt;
  &lt;br /&gt;
  class EmployeeRecordParser {&lt;br /&gt;
    public:&lt;br /&gt;
      EmployeeRecordParser(char* strRow, int nFields) : m_nCount(nFields), m_aryFields(0) {&lt;br /&gt;
  &lt;br /&gt;
        m_aryFields = new char*[m_nCount];&lt;br /&gt;
  &lt;br /&gt;
        char* strField = strtok(strRow, &amp;quot;,&amp;quot;);&lt;br /&gt;
    &lt;br /&gt;
        for (int ct = 0; ct &amp;lt; m_nCount &amp;amp;&amp;amp; strField; ++ct) {&lt;br /&gt;
  &lt;br /&gt;
           m_aryFields[ct] = new char[strlen(strField) + 1];&lt;br /&gt;
 &lt;br /&gt;
           memcpy(m_aryFields[ct], strField, strlen(strField));&lt;br /&gt;
  &lt;br /&gt;
           m_aryFields[ct][strlen(strField)] = 0;&lt;br /&gt;
  &lt;br /&gt;
           strField = strtok(NULL, &amp;quot;,&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
       }&lt;br /&gt;
   	&lt;br /&gt;
      ~EmployeeRecordParser() {&lt;br /&gt;
         if (m_aryFields)			&lt;br /&gt;
           delete [] m_aryFields;&lt;br /&gt;
       }&lt;br /&gt;
  &lt;br /&gt;
       int GetCount() { return m_nCount; }&lt;br /&gt;
       char* operator[](int nIndex) { return GetField(nIndex); }&lt;br /&gt;
       char* GetField(int nIndex) { return nIndex &amp;lt; m_nCount ? m_aryFields[nIndex] : &amp;quot;&amp;quot;; }&lt;br /&gt;
   &lt;br /&gt;
     private:&lt;br /&gt;
       char**	m_aryFields;&lt;br /&gt;
       int	m_nCount;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
  void ParseRecords(char* strFile) {&lt;br /&gt;
    int nRecords = 0;&lt;br /&gt;
    char* strRow = strtok(strFile, &amp;quot;\n&amp;quot;);&lt;br /&gt;
  &lt;br /&gt;
    while (strRow) {		&lt;br /&gt;
  &lt;br /&gt;
      EmployeeRecordParser record(strRow, NUM_FIELDS);&lt;br /&gt;
  &lt;br /&gt;
      printf(&amp;quot;\nEmployee Record %d\n------------------------\n&amp;quot;, ++nRecords);&lt;br /&gt;
  &lt;br /&gt;
      for (int i = 0; i &amp;lt; record.GetCount(); ++i)  {&lt;br /&gt;
        printf(&amp;quot;Field %d: %s\n&amp;quot;, i, record[i]);&lt;br /&gt;
      }&lt;br /&gt;
  &lt;br /&gt;
      strRow = strtok(NULL, &amp;quot;\n&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
  int main() {&lt;br /&gt;
    char str[] = &amp;quot;Tom,Frank,919-777-2333\nMikel,Dundlin,919-234-5512\nRobert,Skoglund,919-232-2904&amp;quot;;&lt;br /&gt;
  &lt;br /&gt;
    ParseRecords(str);&lt;br /&gt;
   &lt;br /&gt;
    return 0;&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In the C++ example above, both the &amp;lt;code&amp;gt;ParseRecords&amp;lt;/code&amp;gt; method and the &amp;lt;code&amp;gt;EmployeeRecordParser&amp;lt;/code&amp;gt; class make use of the globally accessible [http://www.cplusplus.com/reference/clibrary/cstring/strtok.html strtok] function.  Internally, &amp;lt;code&amp;gt;strtok&amp;lt;/code&amp;gt; uses a static variable to track the position of the current string being tokenized, which is also used to determine when the whole string has been parsed.  In this particular example, the coupling on this common function has a side-effect that causes a bug that prevents all the records from being correctly parsed.&lt;br /&gt;
&lt;br /&gt;
=====Control coupling===== &lt;br /&gt;
Control coupling occurs when one module controls the execution flow of another module.  The following example illustrates control coupling.&lt;br /&gt;
&lt;br /&gt;
  enum InfoType { id, name, balance }&lt;br /&gt;
  &lt;br /&gt;
  public class CustomerInfo() {&lt;br /&gt;
    public Object getCustomerInfo(InfoType type) {&lt;br /&gt;
      Object returnVal = null;&lt;br /&gt;
      switch (infoType) {&lt;br /&gt;
        case InfoType.id:                    &lt;br /&gt;
          returnVal = getCustomerId();&lt;br /&gt;
          break;&lt;br /&gt;
  &lt;br /&gt;
        case InfoType.name:&lt;br /&gt;
          returnVal = getCustomerName();&lt;br /&gt;
          break;&lt;br /&gt;
  &lt;br /&gt;
        case InfoType.balance:&lt;br /&gt;
          returnVal = getCustomerBalance();&lt;br /&gt;
          break;&lt;br /&gt;
      }&lt;br /&gt;
      &lt;br /&gt;
      return returnVal;      &lt;br /&gt;
    }&lt;br /&gt;
  &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  public class Client {&lt;br /&gt;
    private customerInfo = new CustomerInfo();&lt;br /&gt;
  &lt;br /&gt;
    public void execute() {&lt;br /&gt;
      int id = (int)customerInfo.getCustomerInfo(InfoType.id);&lt;br /&gt;
      // ...&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Stamp coupling=====&lt;br /&gt;
Stamp coupling occurs when two or more modules access or modify the same data of a shared object.  The following example illustrates stamp coupling.&lt;br /&gt;
&lt;br /&gt;
  public class Customer {&lt;br /&gt;
    private int id = 0;&lt;br /&gt;
    private String name = &amp;quot;&amp;quot;;&lt;br /&gt;
    private float balance = 0.0f;&lt;br /&gt;
  &lt;br /&gt;
    public int getId() { return id; }&lt;br /&gt;
  &lt;br /&gt;
    public void setId(int _id) { id = _id; }&lt;br /&gt;
  &lt;br /&gt;
    public String getName() { return name; }&lt;br /&gt;
  &lt;br /&gt;
    public void setName(String _name) { name = _name; }&lt;br /&gt;
  &lt;br /&gt;
    public float getBalance() { return balance; }&lt;br /&gt;
  &lt;br /&gt;
    public void setBalance(float _balance) { balance = _balance; }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  public class CustomerInfo() {&lt;br /&gt;
    public void save(Customer customer) {&lt;br /&gt;
      int id = customer.getId();&lt;br /&gt;
      String name = gustomer.getName();&lt;br /&gt;
      // ...&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  public class Client {&lt;br /&gt;
    private customerInfo = new CustomerInfo();&lt;br /&gt;
  &lt;br /&gt;
    public void execute() {&lt;br /&gt;
      Customer customer = new Customer();&lt;br /&gt;
  &lt;br /&gt;
      customer.setId(5);&lt;br /&gt;
      customer.setName(&amp;quot;Example&amp;quot;);&lt;br /&gt;
      customer.setBalance(100f);&lt;br /&gt;
      &lt;br /&gt;
      customerInfo.save(customer);&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Data coupling===== &lt;br /&gt;
Data coupling occurs when one module passes primitive type or simple data structure to another module as an argument.  The following example illustrates data coupling.&lt;br /&gt;
&lt;br /&gt;
  public class CustomerInfo&lt;br /&gt;
  {&lt;br /&gt;
    public float getCustomerBalance(int customerId)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
    &lt;br /&gt;
  public class Client&lt;br /&gt;
  {&lt;br /&gt;
    private customerInfo = new CustomerInfo();&lt;br /&gt;
    &lt;br /&gt;
    public void execute(int customerId)&lt;br /&gt;
    {&lt;br /&gt;
        float balance = customerInfo.getCustomerBalance(customerId);&lt;br /&gt;
  &lt;br /&gt;
        // ...    &lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
=====Message coupling=====&lt;br /&gt;
This is the loosest type of coupling.  Modules are not dependent on each other, instead they use a public interface to exchange parameter-less messages.  The following example illustrates messag coupling.&lt;br /&gt;
&lt;br /&gt;
       class superclass {&lt;br /&gt;
           public void processData(){ module1.processData(); }&lt;br /&gt;
       }&lt;br /&gt;
 &lt;br /&gt;
       public Module2 {&lt;br /&gt;
           public void doSomething() { superclass.processData(); }&lt;br /&gt;
       }&lt;br /&gt;
&lt;br /&gt;
=====No coupling===== &lt;br /&gt;
Modules do not communicate at all with one another.&lt;br /&gt;
&lt;br /&gt;
===Advantages and disadvantages===&lt;br /&gt;
Coupling allows interaction between different modules so more complicated tasks can be done. However, a strong coupling will decrease the flexibility of the modules and it will be harder to main and understand. If coupling is too tight, changing one module might have a &amp;quot;snowball effect&amp;quot; and will require changes of other modules that are dependent on it. Coupling must be used with caution and modules must use exactly what it needs and nothing more.&lt;br /&gt;
&lt;br /&gt;
==Related Concepts==&lt;br /&gt;
&lt;br /&gt;
====Measuring Cohesion====&lt;br /&gt;
The goal of well-designed systems is to have highly cohesive modules.  Below are three metrics that can be used to determine the level of cohesion within a system.&lt;br /&gt;
&lt;br /&gt;
'''Lack of Cohesion 1 (LCOM1)'''&lt;br /&gt;
  LCOM1 = (P &amp;gt; Q) ? (P – Q) : 0&lt;br /&gt;
  &lt;br /&gt;
  P = Total number of method pairs that do not use a common field of the class.&lt;br /&gt;
  Q = Total number of method pairs that access at least one common field of the class.&lt;br /&gt;
&lt;br /&gt;
Lower LCOM1 values indicate higher cohesion and better overall design.&lt;br /&gt;
&lt;br /&gt;
'''Lack of Cohesion 2 (LCOM2)'''&lt;br /&gt;
  LCOM2 = 1 – sum(mA)/(m*a)&lt;br /&gt;
  &lt;br /&gt;
  m = Total number of methods in the class.&lt;br /&gt;
  a = Total number of attributes in the class.&lt;br /&gt;
  mA = Total number of methods that access attribute a.&lt;br /&gt;
  sum(mA) = Sum of all mA for all attributes of the class.&lt;br /&gt;
&lt;br /&gt;
Lower LCOM2 values indicate higher cohesion and better overall design.  If the total number of methods or attributes is zero than the value of LCOM2 is undefined.&lt;br /&gt;
&lt;br /&gt;
'''Lack of Cohesion 3 (LCOM3)'''&lt;br /&gt;
&lt;br /&gt;
  LCOM3 = (m – sum(mA)/a) / (m – 1)&lt;br /&gt;
  &lt;br /&gt;
  m = Total number of methods in the class.&lt;br /&gt;
  a = Total number of attributes in the class.&lt;br /&gt;
  mA = Total number of methods that access attribute a.&lt;br /&gt;
  sum(mA) = Sum of all mA for all attributes of the class.&lt;br /&gt;
&lt;br /&gt;
LCOM3 values greater than one indicates low cohesion and should be addressed.  If the total number of methods is less than two or the number of attributes is zero than the value of LCOM3 is undefined.&lt;br /&gt;
&lt;br /&gt;
====Measuring Coupling====&lt;br /&gt;
While it is impossible to avoid some level of coupling within systems, the goal is to reduce coupling as much as possible.  Below are three metrics that can be used to determine the level of coupling within a system.&lt;br /&gt;
&lt;br /&gt;
'''Coupling Between Objects (CBO)'''&lt;br /&gt;
&lt;br /&gt;
  CBO = sum(t)&lt;br /&gt;
  &lt;br /&gt;
  t = Total number of types that are referenced by a particular class, not including any possible super-classes, primitive types or common framework classes.&lt;br /&gt;
&lt;br /&gt;
Lower CBO values indicate lower coupling.&lt;br /&gt;
&lt;br /&gt;
'''Data Abstraction Coupling (DAC)'''&lt;br /&gt;
&lt;br /&gt;
  DAC = sum(a)&lt;br /&gt;
  &lt;br /&gt;
  a = Total number of types that are used for attribute declarations, not including primitive types, common framework classes, or types that are inherited from any possible super-classes.&lt;br /&gt;
&lt;br /&gt;
Lower DC values indicate lower coupling.&lt;br /&gt;
&lt;br /&gt;
'''Method Invocation Coupling (MIC)'''&lt;br /&gt;
&lt;br /&gt;
  MIC = nMIC / (N – 1)&lt;br /&gt;
  &lt;br /&gt;
  N = Total number of classes defined within the project.&lt;br /&gt;
  nMIC = Total number of classes that receive a message from the target class.&lt;br /&gt;
&lt;br /&gt;
Lower MIC values indicate lower coupling.&lt;br /&gt;
&lt;br /&gt;
====Demeter's Law====&lt;br /&gt;
[http://en.wikipedia.org/wiki/Law_of_Demeter Demeter's Law] is a design principle that when applied to object-oriented programming means that object A can reference object B but object A cannot use object B to reference object C.  Complying with this principle prevents object A from knowing that object B uses object C thereby reducing coupling.  If object A needs to access a function of object C then it is up to object B to expose an operation encapsulating the reference to object C.  The following example [http://javaboutique.internet.com/tutorials/coupcoh/index-2.html] illustrates how this could be done.&lt;br /&gt;
&lt;br /&gt;
  public float calculateTotal(Order order) {&lt;br /&gt;
     return order.getProducts().getTotalCost();&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In the example object the object which implements &amp;lt;code&amp;gt;calculateTotal()&amp;lt;/code&amp;gt; is calling &amp;lt;code&amp;gt;getTotalCost&amp;lt;/code&amp;gt; on a &amp;lt;code&amp;gt;Products&amp;lt;/code&amp;gt; object which is exposed through &amp;lt;code&amp;gt;order&amp;lt;/code&amp;gt;.  An alternative to this approach would be for the order object to expose this functionality as suggested by the following example.&lt;br /&gt;
&lt;br /&gt;
  public float calculateTotal(Order order) {&lt;br /&gt;
    return order.getTotalCost()&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
  public class Order {&lt;br /&gt;
    // ...&lt;br /&gt;
  &lt;br /&gt;
    public float getTotalCost() {&lt;br /&gt;
      return products.getTotalCost();&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
Coupling and Cohesion go hand in hand. On one hand cohesion wants modules to do exactly a single task thus reduces problems and making a module handle itself while on the other hand coupling is introduced by how dependent the module is on other modules. Good programming desires high cohesion and low coupling - modules that does one task without affecting other modules while at the same time use as less data/objects from other modules as possible to have low coupling. Although low coupling is desirable, that doesn't mean high coupling doesn't have its uses. In some modules the programmer might want it to be tightly coupled for performance reasons - perhaps a series of modules dependent on each other to bring out the maximum output. A non-IT way of seeing this might be our human body - it is tightly coupled and parts/modules are all dependent on one and another - &amp;quot;removing or fixing&amp;quot; one will involve many other; Even though high coupling is bad but the human body functions much better tightly coupled than loosely coupled. So basically even though high cohesion and lose coupling is very desirable, the programmer has to view the design of the system to figure out what the best approach is.&lt;br /&gt;
&lt;br /&gt;
== See also ==&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29 Wikipedia: Cohesion]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Coupling_%28computer_science%29 Wikipedia: Coupling]&lt;br /&gt;
*[http://www.cs.kent.edu/~jmaletic/cs63901/downloads/CouplingCohesion.pdf Software Engineeriing Presentation: Coupling and Cohesion]&lt;br /&gt;
*[http://www.frontendart.com/monitor/help/node23.html More Cohesion Metrics]&lt;br /&gt;
*[http://www.frontendart.com/monitor/help/node22.html More Coupling Metrics]&lt;br /&gt;
*[http://javaboutique.internet.com/tutorials/coupcoh/index-2.html Example: Measuring Coupling and Cohesion]&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
#http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-cohesion-16069&lt;br /&gt;
#http://www.waysys.com/ws_content_bl_pgssd_ch06.html&lt;br /&gt;
#http://www.site.uottawa.ca:4321/oose/index.html#cohesion&lt;br /&gt;
#http://javaboutique.internet.com/tutorials/coupcoh/index-2.html&lt;br /&gt;
#http://bmrc.berkeley.edu/courseware/cs169/spring01/lectures/objects/sld001.htm&lt;br /&gt;
#http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-coupling-data-and-otherwise-16061&lt;br /&gt;
#http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29&lt;br /&gt;
#http://www.cs.sjsu.edu/faculty/pearce/modules/lectures/ood/metrics/Cohesion.htm&lt;br /&gt;
#http://class.ee.iastate.edu/berleant/home/Courses/SoftwareEngineering/CprE486fall2004/designModularity.htm&lt;br /&gt;
#http://www.eli.sdsu.edu/courses/spring99/cs535/notes/cohesion/cohesion.html#Heading8&lt;br /&gt;
#http://www.site.uottawa.ca:4321/oose/index.html#sequentialcohesion&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13664</id>
		<title>CSC/ECE 517 Summer 2008/wiki2 6 cc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13664"/>
		<updated>2008-06-25T02:42:31Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;''Cohesion and coupling. Cohesion and coupling are concepts that are reasonably easy to understand, but nonetheless, it is worthwhile to gather readable illustrations of where they apply. Browse the hundreds of Web pages that attempt to explain these concepts, picking your favorite examples. Categorize these examples, so that the reader will see the big picture, rather than just a set of redundant illustrations. Many of these pages mention related concepts; list some of them and explain how they relate to cohesion and coupling.''&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Cohesion is a measure of how strongly-related and focused the various responsibilities of a software module are. It is usually expressed as “high” or “low” cohesion when being discussed. High cohesion is desired because it is robust, reliable, reusable and more understandable whereas low cohesion has the opposite of those traits – difficult to maintain, test,reuse and understand. With high cohesion comes low coupling. Coupling is the degree of dependence of   internal implementation between different modules – low coupling is where the module doesn't depend on what other module's internal  implementation does thus a change in them won't affect the module whereas high coupling is where a change in one module might “break” other modules because they are highly dependent on eachother's internal implementations. This page will show you different types of cohesion and coupling and examples showing the “big picture” of them. &lt;br /&gt;
&lt;br /&gt;
== Cohesion ==&lt;br /&gt;
&lt;br /&gt;
Cohesion is categorized in “high” and “low” but  it is “measured” by how strongly-related or focused the responsibilities are for the class. In a highly-cohesive system, code readability and reusability is increased while complexity is kept manageable. A class of high cohesiveness could decrease its “cohesiveness” by carrying out more varied activities that have little in common and increasing complexity.&lt;br /&gt;
&lt;br /&gt;
=== Types of Cohesion ===&lt;br /&gt;
The types below are in order from &amp;quot;Highest&amp;quot; to &amp;quot;Lowest&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Functional Cohesion=====&lt;br /&gt;
Functional cohesion describes a module that is designed to perform one and only one task.  A functionally cohesive module may contain multiple methods, but all of these methods are designed to help the user achieve a single task.  The following example illustrates functional cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Stack &lt;br /&gt;
  {&lt;br /&gt;
    public Stack()   &lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void push(Object obj)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public Object pop()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public int getSize()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
   &lt;br /&gt;
=====Sequential Cohesion=====&lt;br /&gt;
Sequential cohesion describes modules whose operations are intended to executed in sequence with the output of each operation providing input to the subsequently executed operation.  The following example illustrates sequential cohesion [1].&lt;br /&gt;
&lt;br /&gt;
   class Cube {&lt;br /&gt;
       public ArrayList getInfo(){ &lt;br /&gt;
              ArrayList tempList = new ArrayList();&lt;br /&gt;
              tempList.add(getArea());&lt;br /&gt;
              tempList.add(getVolume());&lt;br /&gt;
              return tempList;&lt;br /&gt;
       }&lt;br /&gt;
       public double getArea(){return 6*side*side;} &lt;br /&gt;
       public double getVolume(){return side*side*side;}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
===== Information cohesion =====&lt;br /&gt;
Information cohesion can do several things with the same data -  a class with various methods using same data.&lt;br /&gt;
&lt;br /&gt;
     class Circle {&lt;br /&gt;
          double radius;	      &lt;br /&gt;
          public double getArea(){return 3.14*radius*radius;}&lt;br /&gt;
          public double getDiameter(){return 2 * radius;}&lt;br /&gt;
          public double getCircumference(){return 3.14*2*radius;}&lt;br /&gt;
     }&lt;br /&gt;
=====Communicational Cohesion=====&lt;br /&gt;
Communicational cohesion describes modules that perform multiple operations on the same input or output data [1].  The following example illustrates communication cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class CustomerInformation&lt;br /&gt;
  {&lt;br /&gt;
    public CustomerInformation(int accountNum)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public String getName()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float getBalance()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Procedural Cohesion=====&lt;br /&gt;
Procedural cohesion is similar to sequential cohesion in that the operations exposed are typically grouped because they are executed within a sequence.  Unlike sequential cohesion however, the operations within a procedurally cohesive module can be somewhat unrelated and output from one operation is not necessarily use as input to a following operation.  The following example illustrates procedural cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Student&lt;br /&gt;
  {&lt;br /&gt;
    public Student(int studentId)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void LoadStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateGrades(int[] grades)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateAttendance(Date[] dates)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void SaveStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Temporal Cohesion=====&lt;br /&gt;
Temporal cohesion describes a module that has several operations grouped by the fact that the operations are executed within temporal proximity.  The following example illustrates temporal cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Startup&lt;br /&gt;
  {&lt;br /&gt;
    public void InitializeLogging()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeUI()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeDb()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Logical Cohesion=====&lt;br /&gt;
Logical cohesion describes a module that groups operations because categorically they are related but the operations themselves are quite different.  Typically, these modules accept a control flag which indicates which operation to execute.  The following example illustrates logical cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class DataStore&lt;br /&gt;
  {&lt;br /&gt;
    public void SaveData(int destination, byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      switch (destination)&lt;br /&gt;
      {&lt;br /&gt;
        default:&lt;br /&gt;
        case 0:&lt;br /&gt;
          SaveToDb(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 1:&lt;br /&gt;
          SaveToFile(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 2:&lt;br /&gt;
          SaveToWebService(data)&lt;br /&gt;
          break;&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToDb(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToFile(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToWebService(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Coincidental Cohesion=====&lt;br /&gt;
Coincidental cohesion describes a module whose operations are unrelated to one another and the module itself can be used to achieve several different types of tasks.  typically used to accomplish several unrelated tasks.  The following example illustrates coincidental cohesion [1].&lt;br /&gt;
&lt;br /&gt;
  public static class Math&lt;br /&gt;
  {&lt;br /&gt;
    public static int Add(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public static int Subtract(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===Advantages and disadvantages===&lt;br /&gt;
&lt;br /&gt;
Cohesion is the idea that the module does a single task - be it calculating data, checking file etc. The &amp;quot;single task mindedness&amp;quot; drastically reduces codes breaking when other modules are changed. If the module uses data from multiple other modules - if even one module changes or breaks, this module might need to be changed thus more time wasted. With single task modules, individual modules can be changed with very little problem.&lt;br /&gt;
&lt;br /&gt;
==Coupling==&lt;br /&gt;
&lt;br /&gt;
Coupling is categorized low (loose and weak) or high(tight and strong). Low coupling is a relationship where one module interacts with another module through a stable interface and does not need to be concerned with other module's implementation. With low coupling, a change in one module will not require changes in the implementation of another module (since they are not dependent of each other). High coupling introduces problems like one module change into multiple module changes, difficulty of understanding the relationships and difficulty of testing and reusing individual modules because of high dependence. Low coupling facilitates high cohesion and vice versa. Low coupling may also reduce performance, and a highly-coupled system is sometimes desirable to achieve maximum efficiency.&lt;br /&gt;
&lt;br /&gt;
===Types of coupling===&lt;br /&gt;
The types below are ordered from highest to lowest coupling.&lt;br /&gt;
&lt;br /&gt;
=====Content coupling===== &lt;br /&gt;
Content coupling is when one module modifies or relies on the internal workings of another module. Therefore changing the way the second module produces data will lead to changing the dependent module. &lt;br /&gt;
&lt;br /&gt;
    class Circle {&lt;br /&gt;
        public double getAreaDifference() { return getArea()-  square.getArea();}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    class Square {&lt;br /&gt;
        public String getArea() {  //was double getArea()&lt;br /&gt;
             return area;   &lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
Notice how the Square's getArea() was double but now changed to String. Now class Circle will get error because of incompatible types. &lt;br /&gt;
&lt;br /&gt;
=====Common coupling===== &lt;br /&gt;
Common coupling is when two modules share the same global variable.Changing the shared resource implies changing all the modules using it. &lt;br /&gt;
&lt;br /&gt;
     class Circle{&lt;br /&gt;
         String radius;//was double radius;&lt;br /&gt;
         public double getArea() {return 3.14*radius*radius;}&lt;br /&gt;
         public double getCircumference() {return 2*3.14*radius;}&lt;br /&gt;
     }&lt;br /&gt;
Notice how the radius was double but now String. Now the getArea() and getCircumference() methods will break because the global variables they both use has been changed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====Control coupling===== &lt;br /&gt;
Control coupling is one module controlling the logic of another, by passing it information on what to do.&lt;br /&gt;
&lt;br /&gt;
    class FileController {&lt;br /&gt;
        public void checkFile(File file)  {&lt;br /&gt;
             if (file.size() &amp;gt;5000000)//5 megabytes  &lt;br /&gt;
                 processFile(true); &lt;br /&gt;
             else processFile(false); 	&lt;br /&gt;
         }&lt;br /&gt;
&lt;br /&gt;
        public void processFile(boolean delete) {&lt;br /&gt;
             if (delete)&lt;br /&gt;
                 deleteFile();      	&lt;br /&gt;
             else&lt;br /&gt;
                 closeFile();&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
This Class basically checks the file size and if it is over 5 megs it will tell processFile(boolean) to delete it, else it will close the file. So checkFile(File) is controlling processFile(boolean).&lt;br /&gt;
&lt;br /&gt;
=====Stamp coupling=====&lt;br /&gt;
Stamp coupling is when modules share a composite data structure and use only a part of it, possibly a different part. This may lead to changing the way a module reads a record because a field, which the module doesn't need, has been modified. &lt;br /&gt;
&lt;br /&gt;
     class CarInfo {  &lt;br /&gt;
          String carType;  &lt;br /&gt;
          int numberOfWheels;&lt;br /&gt;
          double weight;&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
     class WeightStation {&lt;br /&gt;
       public checkWeight(CarInfo carInfo) {&lt;br /&gt;
          if (carInfo.getWeight &amp;gt;4000) &lt;br /&gt;
                System.out.println(&amp;quot;car over weight limit&amp;quot;);&lt;br /&gt;
          else&lt;br /&gt;
             System.out.println(&amp;quot;car ok&amp;quot;);&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
WeightStation only needs carweight but if CarInfo ever changes its data and WeightStation happens to want to use something else errors could occur.&lt;br /&gt;
&lt;br /&gt;
=====Data coupling===== &lt;br /&gt;
Data coupling is when modules share data through, for example, parameters. Each datum is an elementary piece, and these are the only data which are shared.&lt;br /&gt;
&lt;br /&gt;
       Public double calculateRoot(int value) {&lt;br /&gt;
           return value^(1/2);&lt;br /&gt;
       }&lt;br /&gt;
 &lt;br /&gt;
=====Message coupling=====&lt;br /&gt;
This is the loosest type of coupling. Modules are not dependent on each other, instead they use a public interface to exchange parameter-less messages.&lt;br /&gt;
&lt;br /&gt;
       class superclass {&lt;br /&gt;
           public void processData(){ module1.processData();}&lt;br /&gt;
        } &lt;br /&gt;
       public Module2 {&lt;br /&gt;
           public void doSomething() { superclass.processData();}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====No coupling===== &lt;br /&gt;
Modules do not communicate at all with one another.&lt;br /&gt;
&lt;br /&gt;
===Advantages and disadvantages===&lt;br /&gt;
Coupling allows interaction between different modules so more complicated tasks can be done. However, a strong coupling will decrease the flexibility of the modules and it will be harder to main and understand. If coupling is too tight, changing one module might have a &amp;quot;snowball effect&amp;quot; and will require changes of other modules that are dependent on it. Coupling must be used with caution and modules must use exactly what it needs and nothing more.&lt;br /&gt;
&lt;br /&gt;
==Coupling and Cohesion review==&lt;br /&gt;
Coupling and Cohesion goes hand in hand. On one hand cohesion wants modules to do exactly a single task thus reduces problems and making a module handle itself. Coupling is inevitably used by cohesion to complete tasks and thus could introduce problems. So good programming desires high cohesion and low coupling - modules that does one task without affecting other modules while at the sametime use as less data/objects from other modules as possible to have low coupling.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Related Concepts==&lt;br /&gt;
&lt;br /&gt;
====Measuring Cohesion====&lt;br /&gt;
&lt;br /&gt;
====Measuring Coupling====&lt;br /&gt;
&lt;br /&gt;
====Demeter's Law====&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
# http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-cohesion-16069&lt;br /&gt;
# http://www.waysys.com/ws_content_bl_pgssd_ch06.html&lt;br /&gt;
# http://www.site.uottawa.ca:4321/oose/index.html#cohesion&lt;br /&gt;
# http://javaboutique.internet.com/tutorials/coupcoh/index-2.html&lt;br /&gt;
# http://bmrc.berkeley.edu/courseware/cs169/spring01/lectures/objects/sld001.htm&lt;br /&gt;
# http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-coupling-data-and-otherwise-16061&lt;br /&gt;
#http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29&lt;br /&gt;
#http://www.cs.sjsu.edu/faculty/pearce/modules/lectures/ood/metrics/Cohesion.htm&lt;br /&gt;
#http://class.ee.iastate.edu/berleant/home/Courses/SoftwareEngineering/CprE486fall2004/designModularity.htm&lt;br /&gt;
#http://www.eli.sdsu.edu/courses/spring99/cs535/notes/cohesion/cohesion.html#Heading8&lt;br /&gt;
#http://www.site.uottawa.ca:4321/oose/index.html#sequentialcohesion&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13663</id>
		<title>CSC/ECE 517 Summer 2008/wiki2 6 cc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13663"/>
		<updated>2008-06-25T02:41:56Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Advantages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;''Cohesion and coupling. Cohesion and coupling are concepts that are reasonably easy to understand, but nonetheless, it is worthwhile to gather readable illustrations of where they apply. Browse the hundreds of Web pages that attempt to explain these concepts, picking your favorite examples. Categorize these examples, so that the reader will see the big picture, rather than just a set of redundant illustrations. Many of these pages mention related concepts; list some of them and explain how they relate to cohesion and coupling.''&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Cohesion is a measure of how strongly-related and focused the various responsibilities of a software module are. It is usually expressed as “high” or “low” cohesion when being discussed. High cohesion is desired because it is robust, reliable, reusable and more understandable whereas low cohesion has the opposite of those traits – difficult to maintain, test,reuse and understand. With high cohesion comes low coupling. Coupling is the degree of dependence of   internal implementation between different modules – low coupling is where the module doesn't depend on what other module's internal  implementation does thus a change in them won't affect the module whereas high coupling is where a change in one module might “break” other modules because they are highly dependent on eachother's internal implementations. This page will show you different types of cohesion and coupling and examples showing the “big picture” of them. &lt;br /&gt;
&lt;br /&gt;
== Cohesion ==&lt;br /&gt;
&lt;br /&gt;
Cohesion is categorized in “high” and “low” but  it is “measured” by how strongly-related or focused the responsibilities are for the class. In a highly-cohesive system, code readability and reusability is increased while complexity is kept manageable. A class of high cohesiveness could decrease its “cohesiveness” by carrying out more varied activities that have little in common and increasing complexity.&lt;br /&gt;
&lt;br /&gt;
=== Types of Cohesion ===&lt;br /&gt;
The types below are in order from &amp;quot;Highest&amp;quot; to &amp;quot;Lowest&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Functional Cohesion=====&lt;br /&gt;
Functional cohesion describes a module that is designed to perform one and only one task.  A functionally cohesive module may contain multiple methods, but all of these methods are designed to help the user achieve a single task.  The following example illustrates functional cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Stack &lt;br /&gt;
  {&lt;br /&gt;
    public Stack()   &lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void push(Object obj)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public Object pop()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public int getSize()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
   &lt;br /&gt;
=====Sequential Cohesion=====&lt;br /&gt;
Sequential cohesion describes modules whose operations are intended to executed in sequence with the output of each operation providing input to the subsequently executed operation.  The following example illustrates sequential cohesion [1].&lt;br /&gt;
&lt;br /&gt;
   class Cube {&lt;br /&gt;
       public ArrayList getInfo(){ &lt;br /&gt;
              ArrayList tempList = new ArrayList();&lt;br /&gt;
              tempList.add(getArea());&lt;br /&gt;
              tempList.add(getVolume());&lt;br /&gt;
              return tempList;&lt;br /&gt;
       }&lt;br /&gt;
       public double getArea(){return 6*side*side;} &lt;br /&gt;
       public double getVolume(){return side*side*side;}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
===== Information cohesion =====&lt;br /&gt;
Information cohesion can do several things with the same data -  a class with various methods using same data.&lt;br /&gt;
&lt;br /&gt;
     class Circle {&lt;br /&gt;
          double radius;	      &lt;br /&gt;
          public double getArea(){return 3.14*radius*radius;}&lt;br /&gt;
          public double getDiameter(){return 2 * radius;}&lt;br /&gt;
          public double getCircumference(){return 3.14*2*radius;}&lt;br /&gt;
     }&lt;br /&gt;
=====Communicational Cohesion=====&lt;br /&gt;
Communicational cohesion describes modules that perform multiple operations on the same input or output data [1].  The following example illustrates communication cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class CustomerInformation&lt;br /&gt;
  {&lt;br /&gt;
    public CustomerInformation(int accountNum)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public String getName()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float getBalance()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Procedural Cohesion=====&lt;br /&gt;
Procedural cohesion is similar to sequential cohesion in that the operations exposed are typically grouped because they are executed within a sequence.  Unlike sequential cohesion however, the operations within a procedurally cohesive module can be somewhat unrelated and output from one operation is not necessarily use as input to a following operation.  The following example illustrates procedural cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Student&lt;br /&gt;
  {&lt;br /&gt;
    public Student(int studentId)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void LoadStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateGrades(int[] grades)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateAttendance(Date[] dates)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void SaveStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Temporal Cohesion=====&lt;br /&gt;
Temporal cohesion describes a module that has several operations grouped by the fact that the operations are executed within temporal proximity.  The following example illustrates temporal cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Startup&lt;br /&gt;
  {&lt;br /&gt;
    public void InitializeLogging()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeUI()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeDb()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Logical Cohesion=====&lt;br /&gt;
Logical cohesion describes a module that groups operations because categorically they are related but the operations themselves are quite different.  Typically, these modules accept a control flag which indicates which operation to execute.  The following example illustrates logical cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class DataStore&lt;br /&gt;
  {&lt;br /&gt;
    public void SaveData(int destination, byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      switch (destination)&lt;br /&gt;
      {&lt;br /&gt;
        default:&lt;br /&gt;
        case 0:&lt;br /&gt;
          SaveToDb(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 1:&lt;br /&gt;
          SaveToFile(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 2:&lt;br /&gt;
          SaveToWebService(data)&lt;br /&gt;
          break;&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToDb(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToFile(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToWebService(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Coincidental Cohesion=====&lt;br /&gt;
Coincidental cohesion describes a module whose operations are unrelated to one another and the module itself can be used to achieve several different types of tasks.  typically used to accomplish several unrelated tasks.  The following example illustrates coincidental cohesion [1].&lt;br /&gt;
&lt;br /&gt;
  public static class Math&lt;br /&gt;
  {&lt;br /&gt;
    public static int Add(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public static int Subtract(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===Advantages and disadvantages===&lt;br /&gt;
&lt;br /&gt;
Cohesion is the idea that the module does a single task - be it calculating data, checking file etc. The &amp;quot;single task mindedness&amp;quot; drastically reduces codes breaking when other modules are changed. If the module uses data from multiple other modules - if even one module changes or breaks, this module might need to be changed thus more time wasted. With single task modules, individual modules can be changed with very little problem.&lt;br /&gt;
&lt;br /&gt;
==Coupling==&lt;br /&gt;
&lt;br /&gt;
Coupling is categorized low (loose and weak) or high(tight and strong). Low coupling is a relationship where one module interacts with another module through a stable interface and does not need to be concerned with other module's implementation. With low coupling, a change in one module will not require changes in the implementation of another module (since they are not dependent of each other). High coupling introduces problems like one module change into multiple module changes, difficulty of understanding the relationships and difficulty of testing and reusing individual modules because of high dependence. Low coupling facilitates high cohesion and vice versa. Low coupling may also reduce performance, and a highly-coupled system is sometimes desirable to achieve maximum efficiency.&lt;br /&gt;
&lt;br /&gt;
===Types of coupling===&lt;br /&gt;
The types below are ordered from highest to lowest coupling.&lt;br /&gt;
&lt;br /&gt;
=====Content coupling===== &lt;br /&gt;
Content coupling is when one module modifies or relies on the internal workings of another module. Therefore changing the way the second module produces data will lead to changing the dependent module. &lt;br /&gt;
&lt;br /&gt;
    class Circle {&lt;br /&gt;
        public double getAreaDifference() { return getArea()-  square.getArea();}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    class Square {&lt;br /&gt;
        public String getArea() {  //was double getArea()&lt;br /&gt;
             return area;   &lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
Notice how the Square's getArea() was double but now changed to String. Now class Circle will get error because of incompatible types. &lt;br /&gt;
&lt;br /&gt;
=====Common coupling===== &lt;br /&gt;
Common coupling is when two modules share the same global variable.Changing the shared resource implies changing all the modules using it. &lt;br /&gt;
&lt;br /&gt;
     class Circle{&lt;br /&gt;
         String radius;//was double radius;&lt;br /&gt;
         public double getArea() {return 3.14*radius*radius;}&lt;br /&gt;
         public double getCircumference() {return 2*3.14*radius;}&lt;br /&gt;
     }&lt;br /&gt;
Notice how the radius was double but now String. Now the getArea() and getCircumference() methods will break because the global variables they both use has been changed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====Control coupling===== &lt;br /&gt;
Control coupling is one module controlling the logic of another, by passing it information on what to do.&lt;br /&gt;
&lt;br /&gt;
    class FileController {&lt;br /&gt;
        public void checkFile(File file)  {&lt;br /&gt;
             if (file.size() &amp;gt;5000000)//5 megabytes  &lt;br /&gt;
                 processFile(true); &lt;br /&gt;
             else processFile(false); 	&lt;br /&gt;
         }&lt;br /&gt;
&lt;br /&gt;
        public void processFile(boolean delete) {&lt;br /&gt;
             if (delete)&lt;br /&gt;
                 deleteFile();      	&lt;br /&gt;
             else&lt;br /&gt;
                 closeFile();&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
This Class basically checks the file size and if it is over 5 megs it will tell processFile(boolean) to delete it, else it will close the file. So checkFile(File) is controlling processFile(boolean).&lt;br /&gt;
&lt;br /&gt;
=====Stamp coupling=====&lt;br /&gt;
Stamp coupling is when modules share a composite data structure and use only a part of it, possibly a different part. This may lead to changing the way a module reads a record because a field, which the module doesn't need, has been modified. &lt;br /&gt;
&lt;br /&gt;
     class CarInfo {  &lt;br /&gt;
          String carType;  &lt;br /&gt;
          int numberOfWheels;&lt;br /&gt;
          double weight;&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
     class WeightStation {&lt;br /&gt;
       public checkWeight(CarInfo carInfo) {&lt;br /&gt;
          if (carInfo.getWeight &amp;gt;4000) &lt;br /&gt;
                System.out.println(&amp;quot;car over weight limit&amp;quot;);&lt;br /&gt;
          else&lt;br /&gt;
             System.out.println(&amp;quot;car ok&amp;quot;);&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
WeightStation only needs carweight but if CarInfo ever changes its data and WeightStation happens to want to use something else errors could occur.&lt;br /&gt;
&lt;br /&gt;
=====Data coupling===== &lt;br /&gt;
Data coupling is when modules share data through, for example, parameters. Each datum is an elementary piece, and these are the only data which are shared.&lt;br /&gt;
&lt;br /&gt;
       Public double calculateRoot(int value) {&lt;br /&gt;
           return value^(1/2);&lt;br /&gt;
       }&lt;br /&gt;
 &lt;br /&gt;
=====Message coupling=====&lt;br /&gt;
This is the loosest type of coupling. Modules are not dependent on each other, instead they use a public interface to exchange parameter-less messages.&lt;br /&gt;
&lt;br /&gt;
       class superclass {&lt;br /&gt;
           public void processData(){ module1.processData();}&lt;br /&gt;
        } &lt;br /&gt;
       public Module2 {&lt;br /&gt;
           public void doSomething() { superclass.processData();}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====No coupling===== &lt;br /&gt;
Modules do not communicate at all with one another.&lt;br /&gt;
&lt;br /&gt;
===Advantages and disadvantages===&lt;br /&gt;
Coupling allows interaction between different modules so more complicated tasks can be done. However, a strong coupling will decrease the flexibility of the modules and it will be harder to main and understand. If coupling is too tight, changing one module might have a &amp;quot;snowball effect&amp;quot; and will require changes of other modules that are dependent on it. Coupling must be used with caution and modules must use exactly what it needs and nothing more.&lt;br /&gt;
&lt;br /&gt;
==Coupling and Cohesion review==&lt;br /&gt;
Coupling and Cohesion goes hand in hand. On one hand cohesion wants modules to do exactly a single task thus reduces problems and making a module handle itself. Coupling is inevitably used by cohesion to complete tasks and thus could introduce problems. So good programming desires high cohesion and low coupling - modules that does one task without affecting other modules while at the sametime use as less data/objects from other modules as possible to have low coupling.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Related Concepts==&lt;br /&gt;
&lt;br /&gt;
====Measuring Cohesion====&lt;br /&gt;
&lt;br /&gt;
====Measuring Coupling====&lt;br /&gt;
&lt;br /&gt;
====Demeter's Law====&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
# http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-cohesion-16069&lt;br /&gt;
# http://www.waysys.com/ws_content_bl_pgssd_ch06.html&lt;br /&gt;
# http://www.site.uottawa.ca:4321/oose/index.html#cohesion&lt;br /&gt;
# http://javaboutique.internet.com/tutorials/coupcoh/index-2.html&lt;br /&gt;
# http://bmrc.berkeley.edu/courseware/cs169/spring01/lectures/objects/sld001.htm&lt;br /&gt;
# http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-coupling-data-and-otherwise-16061&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13662</id>
		<title>CSC/ECE 517 Summer 2008/wiki2 6 cc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13662"/>
		<updated>2008-06-25T02:41:24Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Related Concepts */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;''Cohesion and coupling. Cohesion and coupling are concepts that are reasonably easy to understand, but nonetheless, it is worthwhile to gather readable illustrations of where they apply. Browse the hundreds of Web pages that attempt to explain these concepts, picking your favorite examples. Categorize these examples, so that the reader will see the big picture, rather than just a set of redundant illustrations. Many of these pages mention related concepts; list some of them and explain how they relate to cohesion and coupling.''&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Cohesion is a measure of how strongly-related and focused the various responsibilities of a software module are. It is usually expressed as “high” or “low” cohesion when being discussed. High cohesion is desired because it is robust, reliable, reusable and more understandable whereas low cohesion has the opposite of those traits – difficult to maintain, test,reuse and understand. With high cohesion comes low coupling. Coupling is the degree of dependence of   internal implementation between different modules – low coupling is where the module doesn't depend on what other module's internal  implementation does thus a change in them won't affect the module whereas high coupling is where a change in one module might “break” other modules because they are highly dependent on eachother's internal implementations. This page will show you different types of cohesion and coupling and examples showing the “big picture” of them. &lt;br /&gt;
&lt;br /&gt;
== Cohesion ==&lt;br /&gt;
&lt;br /&gt;
Cohesion is categorized in “high” and “low” but  it is “measured” by how strongly-related or focused the responsibilities are for the class. In a highly-cohesive system, code readability and reusability is increased while complexity is kept manageable. A class of high cohesiveness could decrease its “cohesiveness” by carrying out more varied activities that have little in common and increasing complexity.&lt;br /&gt;
&lt;br /&gt;
=== Types of Cohesion ===&lt;br /&gt;
The types below are in order from &amp;quot;Highest&amp;quot; to &amp;quot;Lowest&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Functional Cohesion=====&lt;br /&gt;
Functional cohesion describes a module that is designed to perform one and only one task.  A functionally cohesive module may contain multiple methods, but all of these methods are designed to help the user achieve a single task.  The following example illustrates functional cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Stack &lt;br /&gt;
  {&lt;br /&gt;
    public Stack()   &lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void push(Object obj)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public Object pop()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public int getSize()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
   &lt;br /&gt;
=====Sequential Cohesion=====&lt;br /&gt;
Sequential cohesion describes modules whose operations are intended to executed in sequence with the output of each operation providing input to the subsequently executed operation.  The following example illustrates sequential cohesion [1].&lt;br /&gt;
&lt;br /&gt;
   class Cube {&lt;br /&gt;
       public ArrayList getInfo(){ &lt;br /&gt;
              ArrayList tempList = new ArrayList();&lt;br /&gt;
              tempList.add(getArea());&lt;br /&gt;
              tempList.add(getVolume());&lt;br /&gt;
              return tempList;&lt;br /&gt;
       }&lt;br /&gt;
       public double getArea(){return 6*side*side;} &lt;br /&gt;
       public double getVolume(){return side*side*side;}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
===== Information cohesion =====&lt;br /&gt;
Information cohesion can do several things with the same data -  a class with various methods using same data.&lt;br /&gt;
&lt;br /&gt;
     class Circle {&lt;br /&gt;
          double radius;	      &lt;br /&gt;
          public double getArea(){return 3.14*radius*radius;}&lt;br /&gt;
          public double getDiameter(){return 2 * radius;}&lt;br /&gt;
          public double getCircumference(){return 3.14*2*radius;}&lt;br /&gt;
     }&lt;br /&gt;
=====Communicational Cohesion=====&lt;br /&gt;
Communicational cohesion describes modules that perform multiple operations on the same input or output data [1].  The following example illustrates communication cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class CustomerInformation&lt;br /&gt;
  {&lt;br /&gt;
    public CustomerInformation(int accountNum)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public String getName()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float getBalance()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Procedural Cohesion=====&lt;br /&gt;
Procedural cohesion is similar to sequential cohesion in that the operations exposed are typically grouped because they are executed within a sequence.  Unlike sequential cohesion however, the operations within a procedurally cohesive module can be somewhat unrelated and output from one operation is not necessarily use as input to a following operation.  The following example illustrates procedural cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Student&lt;br /&gt;
  {&lt;br /&gt;
    public Student(int studentId)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void LoadStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateGrades(int[] grades)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateAttendance(Date[] dates)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void SaveStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Temporal Cohesion=====&lt;br /&gt;
Temporal cohesion describes a module that has several operations grouped by the fact that the operations are executed within temporal proximity.  The following example illustrates temporal cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Startup&lt;br /&gt;
  {&lt;br /&gt;
    public void InitializeLogging()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeUI()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeDb()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Logical Cohesion=====&lt;br /&gt;
Logical cohesion describes a module that groups operations because categorically they are related but the operations themselves are quite different.  Typically, these modules accept a control flag which indicates which operation to execute.  The following example illustrates logical cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class DataStore&lt;br /&gt;
  {&lt;br /&gt;
    public void SaveData(int destination, byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      switch (destination)&lt;br /&gt;
      {&lt;br /&gt;
        default:&lt;br /&gt;
        case 0:&lt;br /&gt;
          SaveToDb(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 1:&lt;br /&gt;
          SaveToFile(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 2:&lt;br /&gt;
          SaveToWebService(data)&lt;br /&gt;
          break;&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToDb(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToFile(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToWebService(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Coincidental Cohesion=====&lt;br /&gt;
Coincidental cohesion describes a module whose operations are unrelated to one another and the module itself can be used to achieve several different types of tasks.  typically used to accomplish several unrelated tasks.  The following example illustrates coincidental cohesion [1].&lt;br /&gt;
&lt;br /&gt;
  public static class Math&lt;br /&gt;
  {&lt;br /&gt;
    public static int Add(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public static int Subtract(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===Advantages and disadvantages===&lt;br /&gt;
&lt;br /&gt;
Cohesion is the idea that the module does a single task - be it calculating data, checking file etc. The &amp;quot;single task mindedness&amp;quot; drastically reduces codes breaking when other modules are changed. If the module uses data from multiple other modules - if even one module changes or breaks, this module might need to be changed thus more time wasted. With single task modules, individual modules can be changed with very little problem.&lt;br /&gt;
&lt;br /&gt;
==Coupling==&lt;br /&gt;
&lt;br /&gt;
Coupling is categorized low (loose and weak) or high(tight and strong). Low coupling is a relationship where one module interacts with another module through a stable interface and does not need to be concerned with other module's implementation. With low coupling, a change in one module will not require changes in the implementation of another module (since they are not dependent of each other). High coupling introduces problems like one module change into multiple module changes, difficulty of understanding the relationships and difficulty of testing and reusing individual modules because of high dependence. Low coupling facilitates high cohesion and vice versa. Low coupling may also reduce performance, and a highly-coupled system is sometimes desirable to achieve maximum efficiency.&lt;br /&gt;
&lt;br /&gt;
===Types of coupling===&lt;br /&gt;
The types below are ordered from highest to lowest coupling.&lt;br /&gt;
&lt;br /&gt;
=====Content coupling===== &lt;br /&gt;
Content coupling is when one module modifies or relies on the internal workings of another module. Therefore changing the way the second module produces data will lead to changing the dependent module. &lt;br /&gt;
&lt;br /&gt;
    class Circle {&lt;br /&gt;
        public double getAreaDifference() { return getArea()-  square.getArea();}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    class Square {&lt;br /&gt;
        public String getArea() {  //was double getArea()&lt;br /&gt;
             return area;   &lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
Notice how the Square's getArea() was double but now changed to String. Now class Circle will get error because of incompatible types. &lt;br /&gt;
&lt;br /&gt;
=====Common coupling===== &lt;br /&gt;
Common coupling is when two modules share the same global variable.Changing the shared resource implies changing all the modules using it. &lt;br /&gt;
&lt;br /&gt;
     class Circle{&lt;br /&gt;
         String radius;//was double radius;&lt;br /&gt;
         public double getArea() {return 3.14*radius*radius;}&lt;br /&gt;
         public double getCircumference() {return 2*3.14*radius;}&lt;br /&gt;
     }&lt;br /&gt;
Notice how the radius was double but now String. Now the getArea() and getCircumference() methods will break because the global variables they both use has been changed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====Control coupling===== &lt;br /&gt;
Control coupling is one module controlling the logic of another, by passing it information on what to do.&lt;br /&gt;
&lt;br /&gt;
    class FileController {&lt;br /&gt;
        public void checkFile(File file)  {&lt;br /&gt;
             if (file.size() &amp;gt;5000000)//5 megabytes  &lt;br /&gt;
                 processFile(true); &lt;br /&gt;
             else processFile(false); 	&lt;br /&gt;
         }&lt;br /&gt;
&lt;br /&gt;
        public void processFile(boolean delete) {&lt;br /&gt;
             if (delete)&lt;br /&gt;
                 deleteFile();      	&lt;br /&gt;
             else&lt;br /&gt;
                 closeFile();&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
This Class basically checks the file size and if it is over 5 megs it will tell processFile(boolean) to delete it, else it will close the file. So checkFile(File) is controlling processFile(boolean).&lt;br /&gt;
&lt;br /&gt;
=====Stamp coupling=====&lt;br /&gt;
Stamp coupling is when modules share a composite data structure and use only a part of it, possibly a different part. This may lead to changing the way a module reads a record because a field, which the module doesn't need, has been modified. &lt;br /&gt;
&lt;br /&gt;
     class CarInfo {  &lt;br /&gt;
          String carType;  &lt;br /&gt;
          int numberOfWheels;&lt;br /&gt;
          double weight;&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
     class WeightStation {&lt;br /&gt;
       public checkWeight(CarInfo carInfo) {&lt;br /&gt;
          if (carInfo.getWeight &amp;gt;4000) &lt;br /&gt;
                System.out.println(&amp;quot;car over weight limit&amp;quot;);&lt;br /&gt;
          else&lt;br /&gt;
             System.out.println(&amp;quot;car ok&amp;quot;);&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
WeightStation only needs carweight but if CarInfo ever changes its data and WeightStation happens to want to use something else errors could occur.&lt;br /&gt;
&lt;br /&gt;
=====Data coupling===== &lt;br /&gt;
Data coupling is when modules share data through, for example, parameters. Each datum is an elementary piece, and these are the only data which are shared.&lt;br /&gt;
&lt;br /&gt;
       Public double calculateRoot(int value) {&lt;br /&gt;
           return value^(1/2);&lt;br /&gt;
       }&lt;br /&gt;
 &lt;br /&gt;
=====Message coupling=====&lt;br /&gt;
This is the loosest type of coupling. Modules are not dependent on each other, instead they use a public interface to exchange parameter-less messages.&lt;br /&gt;
&lt;br /&gt;
       class superclass {&lt;br /&gt;
           public void processData(){ module1.processData();}&lt;br /&gt;
        } &lt;br /&gt;
       public Module2 {&lt;br /&gt;
           public void doSomething() { superclass.processData();}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====No coupling===== &lt;br /&gt;
Modules do not communicate at all with one another.&lt;br /&gt;
&lt;br /&gt;
===Advantages===&lt;br /&gt;
Coupling allows interaction between different modules so more complicated tasks can be done. However, a strong coupling will decrease the flexibility of the modules and it will be harder to main and understand. If coupling is too tight, changing one module might have a &amp;quot;snowball effect&amp;quot; and will require changes of other modules that are dependent on it. Coupling must be used with caution and modules must use exactly what it needs and nothing more.&lt;br /&gt;
&lt;br /&gt;
==Coupling and Cohesion review==&lt;br /&gt;
Coupling and Cohesion goes hand in hand. On one hand cohesion wants modules to do exactly a single task thus reduces problems and making a module handle itself. Coupling is inevitably used by cohesion to complete tasks and thus could introduce problems. So good programming desires high cohesion and low coupling - modules that does one task without affecting other modules while at the sametime use as less data/objects from other modules as possible to have low coupling.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Related Concepts==&lt;br /&gt;
&lt;br /&gt;
====Measuring Cohesion====&lt;br /&gt;
&lt;br /&gt;
====Measuring Coupling====&lt;br /&gt;
&lt;br /&gt;
====Demeter's Law====&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
# http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-cohesion-16069&lt;br /&gt;
# http://www.waysys.com/ws_content_bl_pgssd_ch06.html&lt;br /&gt;
# http://www.site.uottawa.ca:4321/oose/index.html#cohesion&lt;br /&gt;
# http://javaboutique.internet.com/tutorials/coupcoh/index-2.html&lt;br /&gt;
# http://bmrc.berkeley.edu/courseware/cs169/spring01/lectures/objects/sld001.htm&lt;br /&gt;
# http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-coupling-data-and-otherwise-16061&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13661</id>
		<title>CSC/ECE 517 Summer 2008/wiki2 6 cc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13661"/>
		<updated>2008-06-25T02:40:31Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Advantages and disadvantages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;''Cohesion and coupling. Cohesion and coupling are concepts that are reasonably easy to understand, but nonetheless, it is worthwhile to gather readable illustrations of where they apply. Browse the hundreds of Web pages that attempt to explain these concepts, picking your favorite examples. Categorize these examples, so that the reader will see the big picture, rather than just a set of redundant illustrations. Many of these pages mention related concepts; list some of them and explain how they relate to cohesion and coupling.''&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Cohesion is a measure of how strongly-related and focused the various responsibilities of a software module are. It is usually expressed as “high” or “low” cohesion when being discussed. High cohesion is desired because it is robust, reliable, reusable and more understandable whereas low cohesion has the opposite of those traits – difficult to maintain, test,reuse and understand. With high cohesion comes low coupling. Coupling is the degree of dependence of   internal implementation between different modules – low coupling is where the module doesn't depend on what other module's internal  implementation does thus a change in them won't affect the module whereas high coupling is where a change in one module might “break” other modules because they are highly dependent on eachother's internal implementations. This page will show you different types of cohesion and coupling and examples showing the “big picture” of them. &lt;br /&gt;
&lt;br /&gt;
== Cohesion ==&lt;br /&gt;
&lt;br /&gt;
Cohesion is categorized in “high” and “low” but  it is “measured” by how strongly-related or focused the responsibilities are for the class. In a highly-cohesive system, code readability and reusability is increased while complexity is kept manageable. A class of high cohesiveness could decrease its “cohesiveness” by carrying out more varied activities that have little in common and increasing complexity.&lt;br /&gt;
&lt;br /&gt;
=== Types of Cohesion ===&lt;br /&gt;
The types below are in order from &amp;quot;Highest&amp;quot; to &amp;quot;Lowest&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Functional Cohesion=====&lt;br /&gt;
Functional cohesion describes a module that is designed to perform one and only one task.  A functionally cohesive module may contain multiple methods, but all of these methods are designed to help the user achieve a single task.  The following example illustrates functional cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Stack &lt;br /&gt;
  {&lt;br /&gt;
    public Stack()   &lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void push(Object obj)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public Object pop()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public int getSize()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
   &lt;br /&gt;
=====Sequential Cohesion=====&lt;br /&gt;
Sequential cohesion describes modules whose operations are intended to executed in sequence with the output of each operation providing input to the subsequently executed operation.  The following example illustrates sequential cohesion [1].&lt;br /&gt;
&lt;br /&gt;
   class Cube {&lt;br /&gt;
       public ArrayList getInfo(){ &lt;br /&gt;
              ArrayList tempList = new ArrayList();&lt;br /&gt;
              tempList.add(getArea());&lt;br /&gt;
              tempList.add(getVolume());&lt;br /&gt;
              return tempList;&lt;br /&gt;
       }&lt;br /&gt;
       public double getArea(){return 6*side*side;} &lt;br /&gt;
       public double getVolume(){return side*side*side;}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
===== Information cohesion =====&lt;br /&gt;
Information cohesion can do several things with the same data -  a class with various methods using same data.&lt;br /&gt;
&lt;br /&gt;
     class Circle {&lt;br /&gt;
          double radius;	      &lt;br /&gt;
          public double getArea(){return 3.14*radius*radius;}&lt;br /&gt;
          public double getDiameter(){return 2 * radius;}&lt;br /&gt;
          public double getCircumference(){return 3.14*2*radius;}&lt;br /&gt;
     }&lt;br /&gt;
=====Communicational Cohesion=====&lt;br /&gt;
Communicational cohesion describes modules that perform multiple operations on the same input or output data [1].  The following example illustrates communication cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class CustomerInformation&lt;br /&gt;
  {&lt;br /&gt;
    public CustomerInformation(int accountNum)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public String getName()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float getBalance()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Procedural Cohesion=====&lt;br /&gt;
Procedural cohesion is similar to sequential cohesion in that the operations exposed are typically grouped because they are executed within a sequence.  Unlike sequential cohesion however, the operations within a procedurally cohesive module can be somewhat unrelated and output from one operation is not necessarily use as input to a following operation.  The following example illustrates procedural cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Student&lt;br /&gt;
  {&lt;br /&gt;
    public Student(int studentId)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void LoadStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateGrades(int[] grades)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateAttendance(Date[] dates)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void SaveStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Temporal Cohesion=====&lt;br /&gt;
Temporal cohesion describes a module that has several operations grouped by the fact that the operations are executed within temporal proximity.  The following example illustrates temporal cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Startup&lt;br /&gt;
  {&lt;br /&gt;
    public void InitializeLogging()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeUI()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeDb()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Logical Cohesion=====&lt;br /&gt;
Logical cohesion describes a module that groups operations because categorically they are related but the operations themselves are quite different.  Typically, these modules accept a control flag which indicates which operation to execute.  The following example illustrates logical cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class DataStore&lt;br /&gt;
  {&lt;br /&gt;
    public void SaveData(int destination, byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      switch (destination)&lt;br /&gt;
      {&lt;br /&gt;
        default:&lt;br /&gt;
        case 0:&lt;br /&gt;
          SaveToDb(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 1:&lt;br /&gt;
          SaveToFile(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 2:&lt;br /&gt;
          SaveToWebService(data)&lt;br /&gt;
          break;&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToDb(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToFile(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToWebService(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Coincidental Cohesion=====&lt;br /&gt;
Coincidental cohesion describes a module whose operations are unrelated to one another and the module itself can be used to achieve several different types of tasks.  typically used to accomplish several unrelated tasks.  The following example illustrates coincidental cohesion [1].&lt;br /&gt;
&lt;br /&gt;
  public static class Math&lt;br /&gt;
  {&lt;br /&gt;
    public static int Add(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public static int Subtract(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===Advantages and disadvantages===&lt;br /&gt;
&lt;br /&gt;
Cohesion is the idea that the module does a single task - be it calculating data, checking file etc. The &amp;quot;single task mindedness&amp;quot; drastically reduces codes breaking when other modules are changed. If the module uses data from multiple other modules - if even one module changes or breaks, this module might need to be changed thus more time wasted. With single task modules, individual modules can be changed with very little problem.&lt;br /&gt;
&lt;br /&gt;
==Coupling==&lt;br /&gt;
&lt;br /&gt;
Coupling is categorized low (loose and weak) or high(tight and strong). Low coupling is a relationship where one module interacts with another module through a stable interface and does not need to be concerned with other module's implementation. With low coupling, a change in one module will not require changes in the implementation of another module (since they are not dependent of each other). High coupling introduces problems like one module change into multiple module changes, difficulty of understanding the relationships and difficulty of testing and reusing individual modules because of high dependence. Low coupling facilitates high cohesion and vice versa. Low coupling may also reduce performance, and a highly-coupled system is sometimes desirable to achieve maximum efficiency.&lt;br /&gt;
&lt;br /&gt;
===Types of coupling===&lt;br /&gt;
The types below are ordered from highest to lowest coupling.&lt;br /&gt;
&lt;br /&gt;
=====Content coupling===== &lt;br /&gt;
Content coupling is when one module modifies or relies on the internal workings of another module. Therefore changing the way the second module produces data will lead to changing the dependent module. &lt;br /&gt;
&lt;br /&gt;
    class Circle {&lt;br /&gt;
        public double getAreaDifference() { return getArea()-  square.getArea();}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    class Square {&lt;br /&gt;
        public String getArea() {  //was double getArea()&lt;br /&gt;
             return area;   &lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
Notice how the Square's getArea() was double but now changed to String. Now class Circle will get error because of incompatible types. &lt;br /&gt;
&lt;br /&gt;
=====Common coupling===== &lt;br /&gt;
Common coupling is when two modules share the same global variable.Changing the shared resource implies changing all the modules using it. &lt;br /&gt;
&lt;br /&gt;
     class Circle{&lt;br /&gt;
         String radius;//was double radius;&lt;br /&gt;
         public double getArea() {return 3.14*radius*radius;}&lt;br /&gt;
         public double getCircumference() {return 2*3.14*radius;}&lt;br /&gt;
     }&lt;br /&gt;
Notice how the radius was double but now String. Now the getArea() and getCircumference() methods will break because the global variables they both use has been changed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====Control coupling===== &lt;br /&gt;
Control coupling is one module controlling the logic of another, by passing it information on what to do.&lt;br /&gt;
&lt;br /&gt;
    class FileController {&lt;br /&gt;
        public void checkFile(File file)  {&lt;br /&gt;
             if (file.size() &amp;gt;5000000)//5 megabytes  &lt;br /&gt;
                 processFile(true); &lt;br /&gt;
             else processFile(false); 	&lt;br /&gt;
         }&lt;br /&gt;
&lt;br /&gt;
        public void processFile(boolean delete) {&lt;br /&gt;
             if (delete)&lt;br /&gt;
                 deleteFile();      	&lt;br /&gt;
             else&lt;br /&gt;
                 closeFile();&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
This Class basically checks the file size and if it is over 5 megs it will tell processFile(boolean) to delete it, else it will close the file. So checkFile(File) is controlling processFile(boolean).&lt;br /&gt;
&lt;br /&gt;
=====Stamp coupling=====&lt;br /&gt;
Stamp coupling is when modules share a composite data structure and use only a part of it, possibly a different part. This may lead to changing the way a module reads a record because a field, which the module doesn't need, has been modified. &lt;br /&gt;
&lt;br /&gt;
     class CarInfo {  &lt;br /&gt;
          String carType;  &lt;br /&gt;
          int numberOfWheels;&lt;br /&gt;
          double weight;&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
     class WeightStation {&lt;br /&gt;
       public checkWeight(CarInfo carInfo) {&lt;br /&gt;
          if (carInfo.getWeight &amp;gt;4000) &lt;br /&gt;
                System.out.println(&amp;quot;car over weight limit&amp;quot;);&lt;br /&gt;
          else&lt;br /&gt;
             System.out.println(&amp;quot;car ok&amp;quot;);&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
WeightStation only needs carweight but if CarInfo ever changes its data and WeightStation happens to want to use something else errors could occur.&lt;br /&gt;
&lt;br /&gt;
=====Data coupling===== &lt;br /&gt;
Data coupling is when modules share data through, for example, parameters. Each datum is an elementary piece, and these are the only data which are shared.&lt;br /&gt;
&lt;br /&gt;
       Public double calculateRoot(int value) {&lt;br /&gt;
           return value^(1/2);&lt;br /&gt;
       }&lt;br /&gt;
 &lt;br /&gt;
=====Message coupling=====&lt;br /&gt;
This is the loosest type of coupling. Modules are not dependent on each other, instead they use a public interface to exchange parameter-less messages.&lt;br /&gt;
&lt;br /&gt;
       class superclass {&lt;br /&gt;
           public void processData(){ module1.processData();}&lt;br /&gt;
        } &lt;br /&gt;
       public Module2 {&lt;br /&gt;
           public void doSomething() { superclass.processData();}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====No coupling===== &lt;br /&gt;
Modules do not communicate at all with one another.&lt;br /&gt;
&lt;br /&gt;
==Related Concepts==&lt;br /&gt;
&lt;br /&gt;
====Measuring Cohesion====&lt;br /&gt;
&lt;br /&gt;
====Measuring Coupling====&lt;br /&gt;
&lt;br /&gt;
====Demeter's Law====&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
# http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-cohesion-16069&lt;br /&gt;
# http://www.waysys.com/ws_content_bl_pgssd_ch06.html&lt;br /&gt;
# http://www.site.uottawa.ca:4321/oose/index.html#cohesion&lt;br /&gt;
# http://javaboutique.internet.com/tutorials/coupcoh/index-2.html&lt;br /&gt;
# http://bmrc.berkeley.edu/courseware/cs169/spring01/lectures/objects/sld001.htm&lt;br /&gt;
# http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-coupling-data-and-otherwise-16061&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13660</id>
		<title>CSC/ECE 517 Summer 2008/wiki2 6 cc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13660"/>
		<updated>2008-06-25T02:40:22Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Coupling */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;''Cohesion and coupling. Cohesion and coupling are concepts that are reasonably easy to understand, but nonetheless, it is worthwhile to gather readable illustrations of where they apply. Browse the hundreds of Web pages that attempt to explain these concepts, picking your favorite examples. Categorize these examples, so that the reader will see the big picture, rather than just a set of redundant illustrations. Many of these pages mention related concepts; list some of them and explain how they relate to cohesion and coupling.''&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Cohesion is a measure of how strongly-related and focused the various responsibilities of a software module are. It is usually expressed as “high” or “low” cohesion when being discussed. High cohesion is desired because it is robust, reliable, reusable and more understandable whereas low cohesion has the opposite of those traits – difficult to maintain, test,reuse and understand. With high cohesion comes low coupling. Coupling is the degree of dependence of   internal implementation between different modules – low coupling is where the module doesn't depend on what other module's internal  implementation does thus a change in them won't affect the module whereas high coupling is where a change in one module might “break” other modules because they are highly dependent on eachother's internal implementations. This page will show you different types of cohesion and coupling and examples showing the “big picture” of them. &lt;br /&gt;
&lt;br /&gt;
== Cohesion ==&lt;br /&gt;
&lt;br /&gt;
Cohesion is categorized in “high” and “low” but  it is “measured” by how strongly-related or focused the responsibilities are for the class. In a highly-cohesive system, code readability and reusability is increased while complexity is kept manageable. A class of high cohesiveness could decrease its “cohesiveness” by carrying out more varied activities that have little in common and increasing complexity.&lt;br /&gt;
&lt;br /&gt;
=== Types of Cohesion ===&lt;br /&gt;
The types below are in order from &amp;quot;Highest&amp;quot; to &amp;quot;Lowest&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Functional Cohesion=====&lt;br /&gt;
Functional cohesion describes a module that is designed to perform one and only one task.  A functionally cohesive module may contain multiple methods, but all of these methods are designed to help the user achieve a single task.  The following example illustrates functional cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Stack &lt;br /&gt;
  {&lt;br /&gt;
    public Stack()   &lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void push(Object obj)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public Object pop()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public int getSize()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
   &lt;br /&gt;
=====Sequential Cohesion=====&lt;br /&gt;
Sequential cohesion describes modules whose operations are intended to executed in sequence with the output of each operation providing input to the subsequently executed operation.  The following example illustrates sequential cohesion [1].&lt;br /&gt;
&lt;br /&gt;
   class Cube {&lt;br /&gt;
       public ArrayList getInfo(){ &lt;br /&gt;
              ArrayList tempList = new ArrayList();&lt;br /&gt;
              tempList.add(getArea());&lt;br /&gt;
              tempList.add(getVolume());&lt;br /&gt;
              return tempList;&lt;br /&gt;
       }&lt;br /&gt;
       public double getArea(){return 6*side*side;} &lt;br /&gt;
       public double getVolume(){return side*side*side;}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
===== Information cohesion =====&lt;br /&gt;
Information cohesion can do several things with the same data -  a class with various methods using same data.&lt;br /&gt;
&lt;br /&gt;
     class Circle {&lt;br /&gt;
          double radius;	      &lt;br /&gt;
          public double getArea(){return 3.14*radius*radius;}&lt;br /&gt;
          public double getDiameter(){return 2 * radius;}&lt;br /&gt;
          public double getCircumference(){return 3.14*2*radius;}&lt;br /&gt;
     }&lt;br /&gt;
=====Communicational Cohesion=====&lt;br /&gt;
Communicational cohesion describes modules that perform multiple operations on the same input or output data [1].  The following example illustrates communication cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class CustomerInformation&lt;br /&gt;
  {&lt;br /&gt;
    public CustomerInformation(int accountNum)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public String getName()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float getBalance()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Procedural Cohesion=====&lt;br /&gt;
Procedural cohesion is similar to sequential cohesion in that the operations exposed are typically grouped because they are executed within a sequence.  Unlike sequential cohesion however, the operations within a procedurally cohesive module can be somewhat unrelated and output from one operation is not necessarily use as input to a following operation.  The following example illustrates procedural cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Student&lt;br /&gt;
  {&lt;br /&gt;
    public Student(int studentId)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void LoadStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateGrades(int[] grades)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateAttendance(Date[] dates)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void SaveStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Temporal Cohesion=====&lt;br /&gt;
Temporal cohesion describes a module that has several operations grouped by the fact that the operations are executed within temporal proximity.  The following example illustrates temporal cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Startup&lt;br /&gt;
  {&lt;br /&gt;
    public void InitializeLogging()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeUI()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeDb()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Logical Cohesion=====&lt;br /&gt;
Logical cohesion describes a module that groups operations because categorically they are related but the operations themselves are quite different.  Typically, these modules accept a control flag which indicates which operation to execute.  The following example illustrates logical cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class DataStore&lt;br /&gt;
  {&lt;br /&gt;
    public void SaveData(int destination, byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      switch (destination)&lt;br /&gt;
      {&lt;br /&gt;
        default:&lt;br /&gt;
        case 0:&lt;br /&gt;
          SaveToDb(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 1:&lt;br /&gt;
          SaveToFile(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 2:&lt;br /&gt;
          SaveToWebService(data)&lt;br /&gt;
          break;&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToDb(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToFile(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToWebService(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Coincidental Cohesion=====&lt;br /&gt;
Coincidental cohesion describes a module whose operations are unrelated to one another and the module itself can be used to achieve several different types of tasks.  typically used to accomplish several unrelated tasks.  The following example illustrates coincidental cohesion [1].&lt;br /&gt;
&lt;br /&gt;
  public static class Math&lt;br /&gt;
  {&lt;br /&gt;
    public static int Add(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public static int Subtract(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
===Advantages and disadvantages===&lt;br /&gt;
&lt;br /&gt;
     Cohesion is the idea that the module does a single task - be it calculating data, checking file etc. The &amp;quot;single task mindedness&amp;quot; drastically reduces codes breaking when other modules are changed. If the module uses data from multiple other modules - if even one module changes or breaks, this module might need to be changed thus more time wasted. With single task modules, individual modules can be changed with very little problem.&lt;br /&gt;
&lt;br /&gt;
==Coupling==&lt;br /&gt;
&lt;br /&gt;
Coupling is categorized low (loose and weak) or high(tight and strong). Low coupling is a relationship where one module interacts with another module through a stable interface and does not need to be concerned with other module's implementation. With low coupling, a change in one module will not require changes in the implementation of another module (since they are not dependent of each other). High coupling introduces problems like one module change into multiple module changes, difficulty of understanding the relationships and difficulty of testing and reusing individual modules because of high dependence. Low coupling facilitates high cohesion and vice versa. Low coupling may also reduce performance, and a highly-coupled system is sometimes desirable to achieve maximum efficiency.&lt;br /&gt;
&lt;br /&gt;
===Types of coupling===&lt;br /&gt;
The types below are ordered from highest to lowest coupling.&lt;br /&gt;
&lt;br /&gt;
=====Content coupling===== &lt;br /&gt;
Content coupling is when one module modifies or relies on the internal workings of another module. Therefore changing the way the second module produces data will lead to changing the dependent module. &lt;br /&gt;
&lt;br /&gt;
    class Circle {&lt;br /&gt;
        public double getAreaDifference() { return getArea()-  square.getArea();}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    class Square {&lt;br /&gt;
        public String getArea() {  //was double getArea()&lt;br /&gt;
             return area;   &lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
Notice how the Square's getArea() was double but now changed to String. Now class Circle will get error because of incompatible types. &lt;br /&gt;
&lt;br /&gt;
=====Common coupling===== &lt;br /&gt;
Common coupling is when two modules share the same global variable.Changing the shared resource implies changing all the modules using it. &lt;br /&gt;
&lt;br /&gt;
     class Circle{&lt;br /&gt;
         String radius;//was double radius;&lt;br /&gt;
         public double getArea() {return 3.14*radius*radius;}&lt;br /&gt;
         public double getCircumference() {return 2*3.14*radius;}&lt;br /&gt;
     }&lt;br /&gt;
Notice how the radius was double but now String. Now the getArea() and getCircumference() methods will break because the global variables they both use has been changed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====Control coupling===== &lt;br /&gt;
Control coupling is one module controlling the logic of another, by passing it information on what to do.&lt;br /&gt;
&lt;br /&gt;
    class FileController {&lt;br /&gt;
        public void checkFile(File file)  {&lt;br /&gt;
             if (file.size() &amp;gt;5000000)//5 megabytes  &lt;br /&gt;
                 processFile(true); &lt;br /&gt;
             else processFile(false); 	&lt;br /&gt;
         }&lt;br /&gt;
&lt;br /&gt;
        public void processFile(boolean delete) {&lt;br /&gt;
             if (delete)&lt;br /&gt;
                 deleteFile();      	&lt;br /&gt;
             else&lt;br /&gt;
                 closeFile();&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
This Class basically checks the file size and if it is over 5 megs it will tell processFile(boolean) to delete it, else it will close the file. So checkFile(File) is controlling processFile(boolean).&lt;br /&gt;
&lt;br /&gt;
=====Stamp coupling=====&lt;br /&gt;
Stamp coupling is when modules share a composite data structure and use only a part of it, possibly a different part. This may lead to changing the way a module reads a record because a field, which the module doesn't need, has been modified. &lt;br /&gt;
&lt;br /&gt;
     class CarInfo {  &lt;br /&gt;
          String carType;  &lt;br /&gt;
          int numberOfWheels;&lt;br /&gt;
          double weight;&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
     class WeightStation {&lt;br /&gt;
       public checkWeight(CarInfo carInfo) {&lt;br /&gt;
          if (carInfo.getWeight &amp;gt;4000) &lt;br /&gt;
                System.out.println(&amp;quot;car over weight limit&amp;quot;);&lt;br /&gt;
          else&lt;br /&gt;
             System.out.println(&amp;quot;car ok&amp;quot;);&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
WeightStation only needs carweight but if CarInfo ever changes its data and WeightStation happens to want to use something else errors could occur.&lt;br /&gt;
&lt;br /&gt;
=====Data coupling===== &lt;br /&gt;
Data coupling is when modules share data through, for example, parameters. Each datum is an elementary piece, and these are the only data which are shared.&lt;br /&gt;
&lt;br /&gt;
       Public double calculateRoot(int value) {&lt;br /&gt;
           return value^(1/2);&lt;br /&gt;
       }&lt;br /&gt;
 &lt;br /&gt;
=====Message coupling=====&lt;br /&gt;
This is the loosest type of coupling. Modules are not dependent on each other, instead they use a public interface to exchange parameter-less messages.&lt;br /&gt;
&lt;br /&gt;
       class superclass {&lt;br /&gt;
           public void processData(){ module1.processData();}&lt;br /&gt;
        } &lt;br /&gt;
       public Module2 {&lt;br /&gt;
           public void doSomething() { superclass.processData();}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====No coupling===== &lt;br /&gt;
Modules do not communicate at all with one another.&lt;br /&gt;
&lt;br /&gt;
==Related Concepts==&lt;br /&gt;
&lt;br /&gt;
====Measuring Cohesion====&lt;br /&gt;
&lt;br /&gt;
====Measuring Coupling====&lt;br /&gt;
&lt;br /&gt;
====Demeter's Law====&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
# http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-cohesion-16069&lt;br /&gt;
# http://www.waysys.com/ws_content_bl_pgssd_ch06.html&lt;br /&gt;
# http://www.site.uottawa.ca:4321/oose/index.html#cohesion&lt;br /&gt;
# http://javaboutique.internet.com/tutorials/coupcoh/index-2.html&lt;br /&gt;
# http://bmrc.berkeley.edu/courseware/cs169/spring01/lectures/objects/sld001.htm&lt;br /&gt;
# http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-coupling-data-and-otherwise-16061&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13659</id>
		<title>CSC/ECE 517 Summer 2008/wiki2 6 cc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13659"/>
		<updated>2008-06-25T02:38:56Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Sequential Cohesion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;''Cohesion and coupling. Cohesion and coupling are concepts that are reasonably easy to understand, but nonetheless, it is worthwhile to gather readable illustrations of where they apply. Browse the hundreds of Web pages that attempt to explain these concepts, picking your favorite examples. Categorize these examples, so that the reader will see the big picture, rather than just a set of redundant illustrations. Many of these pages mention related concepts; list some of them and explain how they relate to cohesion and coupling.''&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
Cohesion is a measure of how strongly-related and focused the various responsibilities of a software module are. It is usually expressed as “high” or “low” cohesion when being discussed. High cohesion is desired because it is robust, reliable, reusable and more understandable whereas low cohesion has the opposite of those traits – difficult to maintain, test,reuse and understand. With high cohesion comes low coupling. Coupling is the degree of dependence of   internal implementation between different modules – low coupling is where the module doesn't depend on what other module's internal  implementation does thus a change in them won't affect the module whereas high coupling is where a change in one module might “break” other modules because they are highly dependent on eachother's internal implementations. This page will show you different types of cohesion and coupling and examples showing the “big picture” of them. &lt;br /&gt;
&lt;br /&gt;
== Cohesion ==&lt;br /&gt;
&lt;br /&gt;
Cohesion is categorized in “high” and “low” but  it is “measured” by how strongly-related or focused the responsibilities are for the class. In a highly-cohesive system, code readability and reusability is increased while complexity is kept manageable. A class of high cohesiveness could decrease its “cohesiveness” by carrying out more varied activities that have little in common and increasing complexity.&lt;br /&gt;
&lt;br /&gt;
=== Types of Cohesion ===&lt;br /&gt;
The types below are in order from &amp;quot;Highest&amp;quot; to &amp;quot;Lowest&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Functional Cohesion=====&lt;br /&gt;
Functional cohesion describes a module that is designed to perform one and only one task.  A functionally cohesive module may contain multiple methods, but all of these methods are designed to help the user achieve a single task.  The following example illustrates functional cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Stack &lt;br /&gt;
  {&lt;br /&gt;
    public Stack()   &lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void push(Object obj)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public Object pop()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public int getSize()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
   &lt;br /&gt;
=====Sequential Cohesion=====&lt;br /&gt;
Sequential cohesion describes modules whose operations are intended to executed in sequence with the output of each operation providing input to the subsequently executed operation.  The following example illustrates sequential cohesion [1].&lt;br /&gt;
&lt;br /&gt;
   class Cube {&lt;br /&gt;
       public ArrayList getInfo(){ &lt;br /&gt;
              ArrayList tempList = new ArrayList();&lt;br /&gt;
              tempList.add(getArea());&lt;br /&gt;
              tempList.add(getVolume());&lt;br /&gt;
              return tempList;&lt;br /&gt;
       }&lt;br /&gt;
       public double getArea(){return 6*side*side;} &lt;br /&gt;
       public double getVolume(){return side*side*side;}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
===== Information cohesion =====&lt;br /&gt;
Information cohesion can do several things with the same data -  a class with various methods using same data.&lt;br /&gt;
&lt;br /&gt;
     class Circle {&lt;br /&gt;
          double radius;	      &lt;br /&gt;
          public double getArea(){return 3.14*radius*radius;}&lt;br /&gt;
          public double getDiameter(){return 2 * radius;}&lt;br /&gt;
          public double getCircumference(){return 3.14*2*radius;}&lt;br /&gt;
     }&lt;br /&gt;
=====Communicational Cohesion=====&lt;br /&gt;
Communicational cohesion describes modules that perform multiple operations on the same input or output data [1].  The following example illustrates communication cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class CustomerInformation&lt;br /&gt;
  {&lt;br /&gt;
    public CustomerInformation(int accountNum)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public String getName()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float getBalance()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Procedural Cohesion=====&lt;br /&gt;
Procedural cohesion is similar to sequential cohesion in that the operations exposed are typically grouped because they are executed within a sequence.  Unlike sequential cohesion however, the operations within a procedurally cohesive module can be somewhat unrelated and output from one operation is not necessarily use as input to a following operation.  The following example illustrates procedural cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Student&lt;br /&gt;
  {&lt;br /&gt;
    public Student(int studentId)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void LoadStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateGrades(int[] grades)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateAttendance(Date[] dates)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void SaveStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Temporal Cohesion=====&lt;br /&gt;
Temporal cohesion describes a module that has several operations grouped by the fact that the operations are executed within temporal proximity.  The following example illustrates temporal cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Startup&lt;br /&gt;
  {&lt;br /&gt;
    public void InitializeLogging()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeUI()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeDb()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Logical Cohesion=====&lt;br /&gt;
Logical cohesion describes a module that groups operations because categorically they are related but the operations themselves are quite different.  Typically, these modules accept a control flag which indicates which operation to execute.  The following example illustrates logical cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class DataStore&lt;br /&gt;
  {&lt;br /&gt;
    public void SaveData(int destination, byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      switch (destination)&lt;br /&gt;
      {&lt;br /&gt;
        default:&lt;br /&gt;
        case 0:&lt;br /&gt;
          SaveToDb(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 1:&lt;br /&gt;
          SaveToFile(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 2:&lt;br /&gt;
          SaveToWebService(data)&lt;br /&gt;
          break;&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToDb(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToFile(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToWebService(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Coincidental Cohesion=====&lt;br /&gt;
Coincidental cohesion describes a module whose operations are unrelated to one another and the module itself can be used to achieve several different types of tasks.  typically used to accomplish several unrelated tasks.  The following example illustrates coincidental cohesion [1].&lt;br /&gt;
&lt;br /&gt;
  public static class Math&lt;br /&gt;
  {&lt;br /&gt;
    public static int Add(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public static int Subtract(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
==Coupling==&lt;br /&gt;
&lt;br /&gt;
Coupling is categorized low (loose and weak) or high(tight and strong). Low coupling is a relationship where one module interacts with another module through a stable interface and does not need to be concerned with other module's implementation. With low coupling, a change in one module will not require changes in the implementation of another module (since they are not dependent of each other). High coupling introduces problems like one module change into multiple module changes, difficulty of understanding the relationships and difficulty of testing and reusing individual modules because of high dependence. Low coupling facilitates high cohesion and vice versa. Low coupling may also reduce performance, and a highly-coupled system is sometimes desirable to achieve maximum efficiency.&lt;br /&gt;
&lt;br /&gt;
===Types of coupling===&lt;br /&gt;
The types below are ordered from highest to lowest coupling.&lt;br /&gt;
&lt;br /&gt;
=====Content coupling===== &lt;br /&gt;
Content coupling is when one module modifies or relies on the internal workings of another module. Therefore changing the way the second module produces data will lead to changing the dependent module. &lt;br /&gt;
&lt;br /&gt;
    class Circle {&lt;br /&gt;
        public double getAreaDifference() { return getArea()-  square.getArea();}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    class Square {&lt;br /&gt;
        public String getArea() {  //was double getArea()&lt;br /&gt;
             return area;   &lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
Notice how the Square's getArea() was double but now changed to String. Now class Circle will get error because of incompatible types. &lt;br /&gt;
&lt;br /&gt;
=====Common coupling===== &lt;br /&gt;
Common coupling is when two modules share the same global variable.Changing the shared resource implies changing all the modules using it. &lt;br /&gt;
&lt;br /&gt;
     class Circle{&lt;br /&gt;
         String radius;//was double radius;&lt;br /&gt;
         public double getArea() {return 3.14*radius*radius;}&lt;br /&gt;
         public double getCircumference() {return 2*3.14*radius;}&lt;br /&gt;
     }&lt;br /&gt;
Notice how the radius was double but now String. Now the getArea() and getCircumference() methods will break because the global variables they both use has been changed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====Control coupling===== &lt;br /&gt;
Control coupling is one module controlling the logic of another, by passing it information on what to do.&lt;br /&gt;
&lt;br /&gt;
    class FileController {&lt;br /&gt;
        public void checkFile(File file)  {&lt;br /&gt;
             if (file.size() &amp;gt;5000000)//5 megabytes  &lt;br /&gt;
                 processFile(true); &lt;br /&gt;
             else processFile(false); 	&lt;br /&gt;
         }&lt;br /&gt;
&lt;br /&gt;
        public void processFile(boolean delete) {&lt;br /&gt;
             if (delete)&lt;br /&gt;
                 deleteFile();      	&lt;br /&gt;
             else&lt;br /&gt;
                 closeFile();&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
This Class basically checks the file size and if it is over 5 megs it will tell processFile(boolean) to delete it, else it will close the file. So checkFile(File) is controlling processFile(boolean).&lt;br /&gt;
&lt;br /&gt;
=====Stamp coupling=====&lt;br /&gt;
Stamp coupling is when modules share a composite data structure and use only a part of it, possibly a different part. This may lead to changing the way a module reads a record because a field, which the module doesn't need, has been modified. &lt;br /&gt;
&lt;br /&gt;
     class CarInfo {  &lt;br /&gt;
          String carType;  &lt;br /&gt;
          int numberOfWheels;&lt;br /&gt;
          double weight;&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
     class WeightStation {&lt;br /&gt;
       public checkWeight(CarInfo carInfo) {&lt;br /&gt;
          if (carInfo.getWeight &amp;gt;4000) &lt;br /&gt;
                System.out.println(&amp;quot;car over weight limit&amp;quot;);&lt;br /&gt;
          else&lt;br /&gt;
             System.out.println(&amp;quot;car ok&amp;quot;);&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
WeightStation only needs carweight but if CarInfo ever changes its data and WeightStation happens to want to use something else errors could occur.&lt;br /&gt;
&lt;br /&gt;
=====Data coupling===== &lt;br /&gt;
Data coupling is when modules share data through, for example, parameters. Each datum is an elementary piece, and these are the only data which are shared.&lt;br /&gt;
&lt;br /&gt;
       Public double calculateRoot(int value) {&lt;br /&gt;
           return value^(1/2);&lt;br /&gt;
       }&lt;br /&gt;
 &lt;br /&gt;
=====Message coupling=====&lt;br /&gt;
This is the loosest type of coupling. Modules are not dependent on each other, instead they use a public interface to exchange parameter-less messages.&lt;br /&gt;
&lt;br /&gt;
       class superclass {&lt;br /&gt;
           public void processData(){ module1.processData();}&lt;br /&gt;
        } &lt;br /&gt;
       public Module2 {&lt;br /&gt;
           public void doSomething() { superclass.processData();}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====No coupling===== &lt;br /&gt;
Modules do not communicate at all with one another.&lt;br /&gt;
&lt;br /&gt;
==Related Concepts==&lt;br /&gt;
&lt;br /&gt;
====Measuring Cohesion====&lt;br /&gt;
&lt;br /&gt;
====Measuring Coupling====&lt;br /&gt;
&lt;br /&gt;
====Demeter's Law====&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
# http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-cohesion-16069&lt;br /&gt;
# http://www.waysys.com/ws_content_bl_pgssd_ch06.html&lt;br /&gt;
# http://www.site.uottawa.ca:4321/oose/index.html#cohesion&lt;br /&gt;
# http://javaboutique.internet.com/tutorials/coupcoh/index-2.html&lt;br /&gt;
# http://bmrc.berkeley.edu/courseware/cs169/spring01/lectures/objects/sld001.htm&lt;br /&gt;
# http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-coupling-data-and-otherwise-16061&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13652</id>
		<title>CSC/ECE 517 Summer 2008/wiki2 6 cc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13652"/>
		<updated>2008-06-25T02:21:08Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;''Cohesion and coupling. Cohesion and coupling are concepts that are reasonably easy to understand, but nonetheless, it is worthwhile to gather readable illustrations of where they apply. Browse the hundreds of Web pages that attempt to explain these concepts, picking your favorite examples. Categorize these examples, so that the reader will see the big picture, rather than just a set of redundant illustrations. Many of these pages mention related concepts; list some of them and explain how they relate to cohesion and coupling.''&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
Cohesion is a measure of how strongly-related and focused the various responsibilities of a software module are. It is usually expressed as “high” or “low” cohesion when being discussed. High cohesion is desired because it is robust, reliable, reusable and more understandable whereas low cohesion has the opposite of those traits – difficult to maintain, test,reuse and understand. With high cohesion comes low coupling. Coupling is the degree of dependence of   internal implementation between different modules – low coupling is where the module doesn't depend on what other module's internal  implementation does thus a change in them won't affect the module whereas high coupling is where a change in one module might “break” other modules because they are highly dependent on eachother's internal implementations. This page will show you different types of cohesion and coupling and examples showing the “big picture” of them. &lt;br /&gt;
&lt;br /&gt;
== Cohesion ==&lt;br /&gt;
&lt;br /&gt;
Cohesion is categorized in “high” and “low” but  it is “measured” by how strongly-related or focused the responsibilities are for the class. In a highly-cohesive system, code readability and reusability is increased while complexity is kept manageable. A class of high cohesiveness could decrease its “cohesiveness” by carrying out more varied activities that have little in common and increasing complexity.&lt;br /&gt;
&lt;br /&gt;
=== Types of Cohesion ===&lt;br /&gt;
The types below are in order from &amp;quot;Highest&amp;quot; to &amp;quot;Lowest&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Functional Cohesion=====&lt;br /&gt;
Functional cohesion describes a module that is designed to perform one and only one task.  A functionally cohesive module may contain multiple methods, but all of these methods are designed to help the user achieve a single task.  The following example illustrates functional cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Stack &lt;br /&gt;
  {&lt;br /&gt;
    public Stack()   &lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void push(Object obj)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public Object pop()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public int getSize()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
   &lt;br /&gt;
=====Sequential Cohesion=====&lt;br /&gt;
Sequential cohesion describes modules whose operations are intended to executed in sequence with the output of each operation providing input to the subsequently executed operation.  The following example illustrates sequential cohesion [1].&lt;br /&gt;
&lt;br /&gt;
  public class PayCheckCalculator()&lt;br /&gt;
  { &lt;br /&gt;
    public float CalculateBenefitsDeducations(float payAmount)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float CalculateFedDeducations(float payAmount)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float CalculateStateDeductions(float payAmount)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float CalculateRetirementDeductions(float payAmount)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
    class Cube {&lt;br /&gt;
       public ArrayList getInfo(){ &lt;br /&gt;
              ArrayList tempList = new ArrayList();&lt;br /&gt;
              tempList.add(getArea());&lt;br /&gt;
              tempList.add(getVolume());&lt;br /&gt;
              return tempList;&lt;br /&gt;
       }&lt;br /&gt;
       public double getArea(){return 6*side*side;} &lt;br /&gt;
       public double getVolume(){return side*side*side;}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
===== Information cohesion =====&lt;br /&gt;
Information cohesion can do several things with the same data -  a class with various methods using same data.&lt;br /&gt;
&lt;br /&gt;
     class Circle {&lt;br /&gt;
          double radius;	      &lt;br /&gt;
          public double getArea(){return 3.14*radius*radius;}&lt;br /&gt;
          public double getDiameter(){return 2 * radius;}&lt;br /&gt;
          public double getCircumference(){return 3.14*2*radius;}&lt;br /&gt;
     }&lt;br /&gt;
=====Communicational Cohesion=====&lt;br /&gt;
Communicational cohesion describes modules that perform multiple operations on the same input or output data [1].  The following example illustrates communication cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class CustomerInformation&lt;br /&gt;
  {&lt;br /&gt;
    public CustomerInformation(int accountNum)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public String getName()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float getBalance()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Procedural Cohesion=====&lt;br /&gt;
Procedural cohesion is similar to sequential cohesion in that the operations exposed are typically grouped because they are executed within a sequence.  Unlike sequential cohesion however, the operations within a procedurally cohesive module can be somewhat unrelated and output from one operation is not necessarily use as input to a following operation.  The following example illustrates procedural cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Student&lt;br /&gt;
  {&lt;br /&gt;
    public Student(int studentId)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void LoadStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateGrades(int[] grades)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateAttendance(Date[] dates)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void SaveStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Temporal Cohesion=====&lt;br /&gt;
Temporal cohesion describes a module that has several operations grouped by the fact that the operations are executed within temporal proximity.  The following example illustrates temporal cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Startup&lt;br /&gt;
  {&lt;br /&gt;
    public void InitializeLogging()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeUI()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeDb()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Logical Cohesion=====&lt;br /&gt;
Logical cohesion describes a module that groups operations because categorically they are related but the operations themselves are quite different.  Typically, these modules accept a control flag which indicates which operation to execute.  The following example illustrates logical cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class DataStore&lt;br /&gt;
  {&lt;br /&gt;
    public void SaveData(int destination, byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      switch (destination)&lt;br /&gt;
      {&lt;br /&gt;
        default:&lt;br /&gt;
        case 0:&lt;br /&gt;
          SaveToDb(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 1:&lt;br /&gt;
          SaveToFile(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 2:&lt;br /&gt;
          SaveToWebService(data)&lt;br /&gt;
          break;&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToDb(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToFile(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToWebService(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Coincidental Cohesion=====&lt;br /&gt;
Coincidental cohesion describes a module whose operations are unrelated to one another and the module itself can be used to achieve several different types of tasks.  typically used to accomplish several unrelated tasks.  The following example illustrates coincidental cohesion [1].&lt;br /&gt;
&lt;br /&gt;
  public static class Math&lt;br /&gt;
  {&lt;br /&gt;
    public static int Add(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public static int Subtract(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
==Coupling==&lt;br /&gt;
&lt;br /&gt;
Coupling is categorized low (loose and weak) or high(tight and strong). Low coupling is a relationship where one module interacts with another module through a stable interface and does not need to be concerned with other module's implementation. With low coupling, a change in one module will not require changes in the implementation of another module (since they are not dependent of each other). High coupling introduces problems like one module change into multiple module changes, difficulty of understanding the relationships and difficulty of testing and reusing individual modules because of high dependence. Low coupling facilitates high cohesion and vice versa. Low coupling may also reduce performance, and a highly-coupled system is sometimes desirable to achieve maximum efficiency.&lt;br /&gt;
&lt;br /&gt;
===Types of coupling===&lt;br /&gt;
The types below are ordered from highest to lowest coupling.&lt;br /&gt;
&lt;br /&gt;
=====Content coupling===== &lt;br /&gt;
Content coupling is when one module modifies or relies on the internal workings of another module. Therefore changing the way the second module produces data will lead to changing the dependent module. &lt;br /&gt;
&lt;br /&gt;
    class Circle {&lt;br /&gt;
        public double getAreaDifference() { return getArea()-  square.getArea();}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    class Square {&lt;br /&gt;
        public String getArea() {  //was double getArea()&lt;br /&gt;
             return area;   &lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
Notice how the Square's getArea() was double but now changed to String. Now class Circle will get error because of incompatible types. &lt;br /&gt;
&lt;br /&gt;
=====Common coupling===== &lt;br /&gt;
Common coupling is when two modules share the same global variable.Changing the shared resource implies changing all the modules using it. &lt;br /&gt;
&lt;br /&gt;
     class Circle{&lt;br /&gt;
         String radius;//was double radius;&lt;br /&gt;
         public double getArea() {return 3.14*radius*radius;}&lt;br /&gt;
         public double getCircumference() {return 2*3.14*radius;}&lt;br /&gt;
     }&lt;br /&gt;
Notice how the radius was double but now String. Now the getArea() and getCircumference() methods will break because the global variables they both use has been changed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====Control coupling===== &lt;br /&gt;
Control coupling is one module controlling the logic of another, by passing it information on what to do.&lt;br /&gt;
&lt;br /&gt;
    class FileController {&lt;br /&gt;
        public void checkFile(File file)  {&lt;br /&gt;
             if (file.size() &amp;gt;5000000)//5 megabytes  &lt;br /&gt;
                 processFile(true); &lt;br /&gt;
             else processFile(false); 	&lt;br /&gt;
         }&lt;br /&gt;
&lt;br /&gt;
        public void processFile(boolean delete) {&lt;br /&gt;
             if (delete)&lt;br /&gt;
                 deleteFile();      	&lt;br /&gt;
             else&lt;br /&gt;
                 closeFile();&lt;br /&gt;
        }&lt;br /&gt;
      }&lt;br /&gt;
This Class basically checks the file size and if it is over 5 megs it will tell processFile(boolean) to delete it, else it will close the file. So checkFile(File) is controlling processFile(boolean).&lt;br /&gt;
&lt;br /&gt;
=====Stamp coupling=====&lt;br /&gt;
Stamp coupling is when modules share a composite data structure and use only a part of it, possibly a different part. This may lead to changing the way a module reads a record because a field, which the module doesn't need, has been modified. &lt;br /&gt;
&lt;br /&gt;
     class CarInfo {  &lt;br /&gt;
          String carType;  &lt;br /&gt;
          int numberOfWheels;&lt;br /&gt;
          double weight;&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
     class WeightStation {&lt;br /&gt;
       public checkWeight(CarInfo carInfo) {&lt;br /&gt;
          if (carInfo.getWeight &amp;gt;4000) &lt;br /&gt;
                System.out.println(&amp;quot;car over weight limit&amp;quot;);&lt;br /&gt;
          else&lt;br /&gt;
             System.out.println(&amp;quot;car ok&amp;quot;);&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
WeightStation only needs carweight but if CarInfo ever changes its data and WeightStation happens to want to use something else errors could occur.&lt;br /&gt;
&lt;br /&gt;
=====Data coupling===== &lt;br /&gt;
Data coupling is when modules share data through, for example, parameters. Each datum is an elementary piece, and these are the only data which are shared.&lt;br /&gt;
&lt;br /&gt;
       Public double calculateRoot(int value) {&lt;br /&gt;
           return value^(1/2);&lt;br /&gt;
       }&lt;br /&gt;
 &lt;br /&gt;
=====Message coupling=====&lt;br /&gt;
This is the loosest type of coupling. Modules are not dependent on each other, instead they use a public interface to exchange parameter-less messages.&lt;br /&gt;
&lt;br /&gt;
       class superclass {&lt;br /&gt;
           public void processData(){ module1.processData();}&lt;br /&gt;
        } &lt;br /&gt;
       public Module2 {&lt;br /&gt;
           public void doSomething() { superclass.processData();}}&lt;br /&gt;
&lt;br /&gt;
=====No coupling===== &lt;br /&gt;
Modules do not communicate at all with one another.&lt;br /&gt;
     &lt;br /&gt;
== References ==&lt;br /&gt;
# http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-cohesion-16069&lt;br /&gt;
# http://www.waysys.com/ws_content_bl_pgssd_ch06.html&lt;br /&gt;
# http://www.site.uottawa.ca:4321/oose/index.html#cohesion&lt;br /&gt;
# http://javaboutique.internet.com/tutorials/coupcoh/index-2.html&lt;br /&gt;
# http://bmrc.berkeley.edu/courseware/cs169/spring01/lectures/objects/sld001.htm&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13595</id>
		<title>CSC/ECE 517 Summer 2008/wiki2 6 cc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13595"/>
		<updated>2008-06-25T01:21:47Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Cohesion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;''Cohesion and coupling. Cohesion and coupling are concepts that are reasonably easy to understand, but nonetheless, it is worthwhile to gather readable illustrations of where they apply. Browse the hundreds of Web pages that attempt to explain these concepts, picking your favorite examples. Categorize these examples, so that the reader will see the big picture, rather than just a set of redundant illustrations. Many of these pages mention related concepts; list some of them and explain how they relate to cohesion and coupling.''&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
Cohesion is a measure of how strongly-related and focused the various responsibilities of a software module are. It is usually expressed as “high” or “low” cohesion when being discussed. High cohesion is desired because it is robust, reliable, reusable and more understandable whereas low cohesion has the opposite of those traits – difficult to maintain, test,reuse and understand. With high cohesion comes low coupling. Coupling is the degree of dependence of internal implementation between different modules – low coupling is where the module doesn't depend on what other module's internal implementation does thus a change in them won't affect the module whereas high coupling is where a change in one module might “break” other modules because they are highly dependent on eachother's internal implementations. This page will show you different types of cohesion and coupling and examples showing the “big picture” of them. &lt;br /&gt;
&lt;br /&gt;
== Cohesion ==&lt;br /&gt;
&lt;br /&gt;
Cohesion is categorized in “high” and “low” but  it is “measured” by how strongly-related or focused the responsibilities are for the class. In a highly-cohesive system, code readability and reusability is increased while complexity is kept manageable. A class of high cohesiveness could decrease its “cohesiveness” by carrying out more varied activities that have little in common and increasing complexity.&lt;br /&gt;
&lt;br /&gt;
=== Types of Cohesion ===&lt;br /&gt;
The types below are in order from &amp;quot;Highest&amp;quot; to &amp;quot;Lowest&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Functional Cohesion=====&lt;br /&gt;
Functional cohesion describes a module that is designed to perform one and only one task.  A functionally cohesive module may contain multiple methods, but all of these methods are designed to help the user achieve a single task.  The following example illustrates functional cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Stack &lt;br /&gt;
  {&lt;br /&gt;
    public Stack()   &lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void push(Object obj)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public Object pop()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public int getSize()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
   &lt;br /&gt;
=====Sequential Cohesion=====&lt;br /&gt;
Sequential cohesion describes modules whose operations are intended to executed in sequence with the output of each operation providing input to the subsequently executed operation.  The following example illustrates sequential cohesion [1].&lt;br /&gt;
&lt;br /&gt;
  public class PayCheckCalculator()&lt;br /&gt;
  { &lt;br /&gt;
    public float CalculateBenefitsDeducations(float payAmount)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float CalculateFedDeducations(float payAmount)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float CalculateStateDeductions(float payAmount)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float CalculateRetirementDeductions(float payAmount)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
    class Cube {&lt;br /&gt;
       public ArrayList getInfo(){ &lt;br /&gt;
              ArrayList tempList = new ArrayList();&lt;br /&gt;
              tempList.add(getArea());&lt;br /&gt;
              tempList.add(getVolume());&lt;br /&gt;
              return tempList;&lt;br /&gt;
       }&lt;br /&gt;
       public double getArea(){return 6*side*side;} &lt;br /&gt;
       public double getVolume(){return side*side*side;}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
===== Information cohesion =====&lt;br /&gt;
Information cohesion can do several things with the same data -  a class with various methods using same data.&lt;br /&gt;
&lt;br /&gt;
     class Circle {&lt;br /&gt;
          double radius;	      &lt;br /&gt;
          public double getArea(){return 3.14*radius*radius;}&lt;br /&gt;
          public double getDiameter(){return 2 * radius;}&lt;br /&gt;
          public double getCircumference(){return 3.14*2*radius;}&lt;br /&gt;
     }&lt;br /&gt;
=====Communicational Cohesion=====&lt;br /&gt;
Communicational cohesion describes modules that perform multiple operations on the same input or output data [1].  The following example illustrates communication cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class CustomerInformation&lt;br /&gt;
  {&lt;br /&gt;
    public CustomerInformation(int accountNum)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public String getName()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float getBalance()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Procedural Cohesion=====&lt;br /&gt;
Procedural cohesion is similar to sequential cohesion in that the operations exposed are typically grouped because they are executed within a sequence.  Unlike sequential cohesion however, the operations within a procedurally cohesive module can be somewhat unrelated and output from one operation is not necessarily use as input to a following operation.  The following example illustrates procedural cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Student&lt;br /&gt;
  {&lt;br /&gt;
    public Student(int studentId)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void LoadStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateGrades(int[] grades)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateAttendance(Date[] dates)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void SaveStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Temporal Cohesion=====&lt;br /&gt;
Temporal cohesion describes a module that has several operations grouped by the fact that the operations are executed within temporal proximity.  The following example illustrates temporal cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Startup&lt;br /&gt;
  {&lt;br /&gt;
    public void InitializeLogging()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeUI()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeDb()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Logical Cohesion=====&lt;br /&gt;
Logical cohesion describes a module that groups operations because categorically they are related but the operations themselves are quite different.  Typically, these modules accept a control flag which indicates which operation to execute.  The following example illustrates logical cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class DataStore&lt;br /&gt;
  {&lt;br /&gt;
    public void SaveData(int destination, byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      switch (destination)&lt;br /&gt;
      {&lt;br /&gt;
        default:&lt;br /&gt;
        case 0:&lt;br /&gt;
          SaveToDb(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 1:&lt;br /&gt;
          SaveToFile(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 2:&lt;br /&gt;
          SaveToWebService(data)&lt;br /&gt;
          break;&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToDb(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToFile(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToWebService(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Coincidental Cohesion=====&lt;br /&gt;
Coincidental cohesion describes a module whose operations are unrelated to one another and the module itself can be used to achieve several different types of tasks.  typically used to accomplish several unrelated tasks.  The following example illustrates coincidental cohesion [1].&lt;br /&gt;
&lt;br /&gt;
  public static class Math&lt;br /&gt;
  {&lt;br /&gt;
    public static int Add(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public static int Subtract(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
# http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-cohesion-16069&lt;br /&gt;
# http://www.waysys.com/ws_content_bl_pgssd_ch06.html&lt;br /&gt;
# http://www.site.uottawa.ca:4321/oose/index.html#cohesion&lt;br /&gt;
# http://javaboutique.internet.com/tutorials/coupcoh/index-2.html&lt;br /&gt;
# http://bmrc.berkeley.edu/courseware/cs169/spring01/lectures/objects/sld001.htm&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13594</id>
		<title>CSC/ECE 517 Summer 2008/wiki2 6 cc</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki2_6_cc&amp;diff=13594"/>
		<updated>2008-06-25T01:21:34Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Types of Cohesion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;''Cohesion and coupling. Cohesion and coupling are concepts that are reasonably easy to understand, but nonetheless, it is worthwhile to gather readable illustrations of where they apply. Browse the hundreds of Web pages that attempt to explain these concepts, picking your favorite examples. Categorize these examples, so that the reader will see the big picture, rather than just a set of redundant illustrations. Many of these pages mention related concepts; list some of them and explain how they relate to cohesion and coupling.''&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
Cohesion is a measure of how strongly-related and focused the various responsibilities of a software module are. It is usually expressed as “high” or “low” cohesion when being discussed. High cohesion is desired because it is robust, reliable, reusable and more understandable whereas low cohesion has the opposite of those traits – difficult to maintain, test,reuse and understand. With high cohesion comes low coupling. Coupling is the degree of dependence of internal implementation between different modules – low coupling is where the module doesn't depend on what other module's internal implementation does thus a change in them won't affect the module whereas high coupling is where a change in one module might “break” other modules because they are highly dependent on eachother's internal implementations. This page will show you different types of cohesion and coupling and examples showing the “big picture” of them. &lt;br /&gt;
&lt;br /&gt;
== Cohesion ==&lt;br /&gt;
&lt;br /&gt;
    Cohesion is categorized in “high” and “low” but  it is “measured” by how strongly-related or focused the responsibilities are for the class. In a highly-cohesive system, code readability and reusability is increased while complexity is kept manageable. A class of high cohesiveness could decrease its “cohesiveness” by carrying out more varied activities that have little in common and increasing complexity.&lt;br /&gt;
&lt;br /&gt;
=== Types of Cohesion ===&lt;br /&gt;
The types below are in order from &amp;quot;Highest&amp;quot; to &amp;quot;Lowest&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Functional Cohesion=====&lt;br /&gt;
Functional cohesion describes a module that is designed to perform one and only one task.  A functionally cohesive module may contain multiple methods, but all of these methods are designed to help the user achieve a single task.  The following example illustrates functional cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Stack &lt;br /&gt;
  {&lt;br /&gt;
    public Stack()   &lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void push(Object obj)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public Object pop()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public int getSize()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
   &lt;br /&gt;
=====Sequential Cohesion=====&lt;br /&gt;
Sequential cohesion describes modules whose operations are intended to executed in sequence with the output of each operation providing input to the subsequently executed operation.  The following example illustrates sequential cohesion [1].&lt;br /&gt;
&lt;br /&gt;
  public class PayCheckCalculator()&lt;br /&gt;
  { &lt;br /&gt;
    public float CalculateBenefitsDeducations(float payAmount)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float CalculateFedDeducations(float payAmount)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float CalculateStateDeductions(float payAmount)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float CalculateRetirementDeductions(float payAmount)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
    class Cube {&lt;br /&gt;
       public ArrayList getInfo(){ &lt;br /&gt;
              ArrayList tempList = new ArrayList();&lt;br /&gt;
              tempList.add(getArea());&lt;br /&gt;
              tempList.add(getVolume());&lt;br /&gt;
              return tempList;&lt;br /&gt;
       }&lt;br /&gt;
       public double getArea(){return 6*side*side;} &lt;br /&gt;
       public double getVolume(){return side*side*side;}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
===== Information cohesion =====&lt;br /&gt;
Information cohesion can do several things with the same data -  a class with various methods using same data.&lt;br /&gt;
&lt;br /&gt;
     class Circle {&lt;br /&gt;
          double radius;	      &lt;br /&gt;
          public double getArea(){return 3.14*radius*radius;}&lt;br /&gt;
          public double getDiameter(){return 2 * radius;}&lt;br /&gt;
          public double getCircumference(){return 3.14*2*radius;}&lt;br /&gt;
     }&lt;br /&gt;
=====Communicational Cohesion=====&lt;br /&gt;
Communicational cohesion describes modules that perform multiple operations on the same input or output data [1].  The following example illustrates communication cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class CustomerInformation&lt;br /&gt;
  {&lt;br /&gt;
    public CustomerInformation(int accountNum)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public String getName()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public float getBalance()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Procedural Cohesion=====&lt;br /&gt;
Procedural cohesion is similar to sequential cohesion in that the operations exposed are typically grouped because they are executed within a sequence.  Unlike sequential cohesion however, the operations within a procedurally cohesive module can be somewhat unrelated and output from one operation is not necessarily use as input to a following operation.  The following example illustrates procedural cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Student&lt;br /&gt;
  {&lt;br /&gt;
    public Student(int studentId)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void LoadStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateGrades(int[] grades)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void UpdateAttendance(Date[] dates)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void SaveStudent()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Temporal Cohesion=====&lt;br /&gt;
Temporal cohesion describes a module that has several operations grouped by the fact that the operations are executed within temporal proximity.  The following example illustrates temporal cohesion.&lt;br /&gt;
&lt;br /&gt;
  public class Startup&lt;br /&gt;
  {&lt;br /&gt;
    public void InitializeLogging()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeUI()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public void InitializeDb()&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Logical Cohesion=====&lt;br /&gt;
Logical cohesion describes a module that groups operations because categorically they are related but the operations themselves are quite different.  Typically, these modules accept a control flag which indicates which operation to execute.  The following example illustrates logical cohesion [2].&lt;br /&gt;
&lt;br /&gt;
  public class DataStore&lt;br /&gt;
  {&lt;br /&gt;
    public void SaveData(int destination, byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      switch (destination)&lt;br /&gt;
      {&lt;br /&gt;
        default:&lt;br /&gt;
        case 0:&lt;br /&gt;
          SaveToDb(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 1:&lt;br /&gt;
          SaveToFile(data)&lt;br /&gt;
          break;&lt;br /&gt;
        &lt;br /&gt;
        case 2:&lt;br /&gt;
          SaveToWebService(data)&lt;br /&gt;
          break;&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToDb(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToFile(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    protected void SaveToWebService(byte[] data)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
=====Coincidental Cohesion=====&lt;br /&gt;
Coincidental cohesion describes a module whose operations are unrelated to one another and the module itself can be used to achieve several different types of tasks.  typically used to accomplish several unrelated tasks.  The following example illustrates coincidental cohesion [1].&lt;br /&gt;
&lt;br /&gt;
  public static class Math&lt;br /&gt;
  {&lt;br /&gt;
    public static int Add(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    public static int Subtract(int a, int b)&lt;br /&gt;
    {&lt;br /&gt;
      // implementation details&lt;br /&gt;
    }&lt;br /&gt;
    &lt;br /&gt;
    // ...&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
# http://blogs.ittoolbox.com/eai/implementation/archives/design-principles-cohesion-16069&lt;br /&gt;
# http://www.waysys.com/ws_content_bl_pgssd_ch06.html&lt;br /&gt;
# http://www.site.uottawa.ca:4321/oose/index.html#cohesion&lt;br /&gt;
# http://javaboutique.internet.com/tutorials/coupcoh/index-2.html&lt;br /&gt;
# http://bmrc.berkeley.edu/courseware/cs169/spring01/lectures/objects/sld001.htm&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12877</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12877"/>
		<updated>2008-06-09T17:16:28Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
A thread is a basic unit of CPU utilization.  A traditional process has a single thread of control.  Many modern operating systems provide features enabling a process to contain multiple threads of control.  If the process has multiple threads of control, it can do more than one task at a time, such as, displaying graphics and reading keystrokes.  Threads are used mainly to run asynchronous tasks and pass the application’s tasks to an executor.  They are useful because they reduce the overall time of execution of programs. All threads belonging to the same process share its code section, data section and other operating system resources, such as open files and signals.  Thus multithreading is more efficient than having parallel processes running for the same program, which require a huge overhead.&lt;br /&gt;
&lt;br /&gt;
=Multi-threaded Programming= &lt;br /&gt;
Multithreading support for single processors works by giving each of the threads a “time slice” of the CPU, similar to the parallel execution of processes.  On multi-core machines, different threads can run on the different processors and the threads truly run simultaneously.   Support for threads may be provided at either the user level, for user or green threads, or by the kernel, for kernel or native threads.  User threads are supported above the kernel and are managed without kernel support, whereas kernel threads are supported and managed directly by the operating system.&lt;br /&gt;
&lt;br /&gt;
==Multi-threading Models==&lt;br /&gt;
There are three common multithreading models&lt;br /&gt;
&lt;br /&gt;
===One-to-One===&lt;br /&gt;
This model maps each user-thread to a kernel thread.  It provides more concurrency than the many-to-one model by allowing another thread to run when a thread makes a blocking system call.  It also allows multiple threads to run in parallel on multiprocessors.  The main disadvantage of this model is the overhead of creating each kernel thread for each user thread.  This burdens the performance of an application and limits the number of threads supported by the system.&lt;br /&gt;
&lt;br /&gt;
===Many-to-One===&lt;br /&gt;
This model maps many user-level threads to one kernel thread.  It is the model used by green threads.  Green threads are scheduled by a Virtual Machine instead of natively by the OS. They emulate multithreaded environments without relying on any native OS capabilities. These user-level threads are lightweight and very efficient.  They are an easy way to achieve parallelism in a program.   An application can have as many user-level threads as it needs, but true concurrency is not achieved because the kernel can schedule only one thread at a time. The developers can create as many user threads as necessary.  However, there are two main disadvantages:&lt;br /&gt;
1)	If a thread makes a blocking system call, the entire process will block.&lt;br /&gt;
2)	If you are running on a multi-core machine, the multiple threads are unable to run in parallel.&lt;br /&gt;
&lt;br /&gt;
===Many-to-Many===&lt;br /&gt;
This model multiplexes many user-level threads to a smaller or equal number of kernel threads.  This model has the best of both worlds.  Developers can create as many user threads as they need.  When a user thread performs a blocking system call, the kernel can schedule another thread for execution and the kernel threads can run in parallel on multi-core systems.&lt;br /&gt;
&lt;br /&gt;
==Benefits of Multi-threading==&lt;br /&gt;
===Resource sharing===&lt;br /&gt;
Memory, code and process resource sharing - allocating memory and resources for process creation is costly and time consuming.  It is more economical to create threads than new processes.  Applications can benefit by having several different threads of activity within the same address space.&lt;br /&gt;
&lt;br /&gt;
===Responsiveness===&lt;br /&gt;
Multithreading an interactive application may allow a program to continue running, even if part of it is blocked doing IO or performing a lengthy operation, thereby increasing responsiveness to the user.  A web browser might have one thread display images or text while another thread retrieves data from the network.  A busy web server may have many clients concurrently accessing it.  If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time.&lt;br /&gt;
&lt;br /&gt;
==Potential Problems of Multi-threading==&lt;br /&gt;
Many threaded programs have shared resources that must be accessed by more than one thread.  These programs must implement a form of mutual exclusion to ensure that only one of the threads can access the resource at a time.  These shared resources must execute in code called critical sections.  These critical sections must be protected by either hardware or software means.&lt;br /&gt;
&lt;br /&gt;
=Java Threads=&lt;br /&gt;
The Java programming language has a thread library for creating and managing threads at the user-level.  The Java virtual machine (JVM) manages the mapping of the user threads to the operating system kernel threads.  The particular mapping model that is used depends on the operating system on which the Java program is running.  Java’s Thread Scheduler monitors all the threads running in Java programs.  It decides which threads to run at any given time and when to switch between threads to run based on the thread’s priority with higher running threads running before lower priority threads.  The Java scheduler uses either preemptive or non-preemptive scheduling based on the operating system on which it is running.  With preemptive scheduling, each thread is given a constant period of time to run, after which time the thread will be suspended() to allow the next thread to resume() running.  With non-preemptive scheduling, the running thread is allowed to run until the thread completes or until it issues a yield() to allow other threads to run while it waits for some other processing to occur.  &lt;br /&gt;
A Java thread can be created either by having your Java class extend the Java Thread class or by having your Java class implement the Runnable interface and coding a run() method.  The two options are shown in Figures 1 and 2.   The preferred method for creating a thread is by implementing the Runnable interface.  It is more flexible and useful in complex applications.   Java does not support multiple inheritance, but a class may implement multiple interfaces.  By using the interface method, the Client class is open to inherit another class, if the need arose in the future.&lt;br /&gt;
  &lt;br /&gt;
'''Figure 1: Client Extends Thread Class'''&lt;br /&gt;
        &lt;br /&gt;
    public class Client extends Thread {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Server {&lt;br /&gt;
        public static void main(String args[]){&lt;br /&gt;
            Thread runner = new Client();&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 2: Client Implements Runnable Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
   &lt;br /&gt;
    public class Server {&lt;br /&gt;
    &lt;br /&gt;
        public static void main(String args[]) {&lt;br /&gt;
            Thread runner = new Thread(new Client());&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
If the main Java thread wants to wait for any threads it creates to finish their run() method, the thread method join() can be executed.  The join() method is useful in situations where the creating thread can continue only after a worker thread has completed.  Java threads can be asynchronously terminated using the stop() method.  However, this method has been deprecated and its used is discouraged.  The preferred cancellation technique is to have the target thread periodically check whether it should terminate by using the interrupt() method.&lt;br /&gt;
&lt;br /&gt;
==States of Java Threads==&lt;br /&gt;
===New===&lt;br /&gt;
A thread is in this state when the thread object is first created with the new() method.&lt;br /&gt;
===Runnable===&lt;br /&gt;
Calling the start() method allocates memory for the new thread in the JVM and calls the run() method for the thread object.&lt;br /&gt;
===Blocked===&lt;br /&gt;
A thread becomes blocked if it performs a blocking statement, such as doing I/O or if it invokes a sleep() method.&lt;br /&gt;
===Dead===&lt;br /&gt;
A thread moves to the dead state when its run() method terminates.&lt;br /&gt;
&lt;br /&gt;
==Mutual Exclusion==&lt;br /&gt;
The Java language implements mutual exclusion in a couple of ways.  There exists a MutualExclusion interface.  The Client class can implement this interface and code the methods, enteringCriticalSection() and leavingCriticalSection(), as shown in Figure 3.  The yield() method tells the Thread Scheduler to allow another thread to run.  &lt;br /&gt;
&lt;br /&gt;
'''Figure 3: Client Implements MutualExclusion Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements MutualExclusion{&lt;br /&gt;
    &lt;br /&gt;
        public Client(){&lt;br /&gt;
            flag0 = false; flag1 = false; turn = TURN_0;&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void enteringCriticalSection(int t) {&lt;br /&gt;
            int other = 1 - t;&lt;br /&gt;
            &lt;br /&gt;
            if (t == 0) {&lt;br /&gt;
                flag0 = true; turn = other;&lt;br /&gt;
                while ((flag1 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             } else {&lt;br /&gt;
                flag1 = true; turn = other;&lt;br /&gt;
     	        while ((flag0 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void leavingCriticalSection(int t) {&lt;br /&gt;
            if(t == 0) flag0 = false;&lt;br /&gt;
            else   flag1 = false;&lt;br /&gt;
        }&lt;br /&gt;
        private volatile int turn, boolean flag0, flag1;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
An alternative method of handling mutual exclusion is to code a synchronization tool called a semaphore.  A semaphore is variable that is accessed only through two standard operations: acquire() and release().  The semaphore is acquired, then the critical section of an object is entered and after the critical code completes, the semaphore is released.  An example of this code is in Figure 4.&lt;br /&gt;
&lt;br /&gt;
'''Figure 4: Client Has Semaphore'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
    &lt;br /&gt;
        public Client (Semaphore sem) {&lt;br /&gt;
            this.sem = sem;&lt;br /&gt;
        }&lt;br /&gt;
       &lt;br /&gt;
        public void run() {&lt;br /&gt;
            sem.acquire();&lt;br /&gt;
            System.out.println(&amp;quot;Entering critical section&amp;quot;);&lt;br /&gt;
            SleepUtilities.nap(3);&lt;br /&gt;
            System.out.println(&amp;quot;Leaving critical section&amp;quot;);&lt;br /&gt;
            sem.release();&lt;br /&gt;
        }&lt;br /&gt;
        private Semaphore sem;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Ruby Threads=&lt;br /&gt;
At the present time the Ruby programming language just supports green threads.  These are totally implemented within the Ruby interpreter.  The threads, as well as the thread scheduler run on the same single operating system thread.  Ruby can support thread methods, such as stop() and kill(), that are not advised for kernel threads.  However, Ruby threads suffer from the drawbacks of non-native threads.  They can only run on one processor in a multiprocessor environment.  It is possible for a single thread to cause the whole process to deadlock, if poorly designed.  The worse problem with Ruby threads is with I/O, especially network access, since it has the potential to block a process for a long time.  This problem is solvable by using non-blocking I/O.  However, one problem that is not solvable using non-blocking I/O, is the DNS lookup system call.  Ruby solves this problem with their resolv library, which was written specifically to address the threading issue with the standard OS DNA lookup mechanism.  See Figure 5 for an example of the code that handles this issue.  Despite some of the green thread concerns, for most situations, the benefits of efficiency can far outweigh the disadvantages.&lt;br /&gt;
&lt;br /&gt;
'''Figure 5: Ruby DNS Lookup Implementation'''&lt;br /&gt;
    &lt;br /&gt;
    require ‘socket’&lt;br /&gt;
    require ‘resolv-replace’&lt;br /&gt;
    count = 0&lt;br /&gt;
    Thread.critical = true&lt;br /&gt;
    thread = Thread.new { Thread.pass; loop { count += 1; } } IPSocket.getaddress(www.ruby-lang.org) &lt;br /&gt;
    count&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A Ruby thread is created using Thread.new() {block}.  The arguments given in the new() method are passed to the block code that the thread executes.  See Figure 6 for an example of creating a Ruby thread.  The Ruby pass() method is analogous to the Java yield() method.  It tells the thread scheduler to pass execution to another thread.  Ruby has a join() method that performs the same functionality as the Java join().  There are run() and wakeup() methods that wake up a sleeping threads, either giving it control or indicating that it is ready to be scheduled. &lt;br /&gt;
&lt;br /&gt;
'''Figure 6: Creating Ruby Threads'''&lt;br /&gt;
&lt;br /&gt;
    threads = []&lt;br /&gt;
    4.times do |number|&lt;br /&gt;
        threads &amp;lt;&amp;lt; Thread.new(number) do |i|&lt;br /&gt;
            print “#{i}\n”    &lt;br /&gt;
        end &lt;br /&gt;
    end&lt;br /&gt;
    threads.each { |t| t.join }  &lt;br /&gt;
&lt;br /&gt;
==States of Ruby Threads==&lt;br /&gt;
===Run===&lt;br /&gt;
The thread is executing.&lt;br /&gt;
===Sleep===&lt;br /&gt;
The thread is sleeping or waiting on I/O.&lt;br /&gt;
===Aborting===&lt;br /&gt;
The thread is aborting (has been killed).&lt;br /&gt;
===False===&lt;br /&gt;
The thread has terminated normally.&lt;br /&gt;
===Nil===&lt;br /&gt;
The thread has terminated with an exception.&lt;br /&gt;
&lt;br /&gt;
==Mutual Exclusion==&lt;br /&gt;
The best way to handle mutual exclusion in Ruby is with the Monitor class.  A monitor has a synchronization() method that prevent access to a resource by another thread while one is execution in that method.  Figure 7 shows an example of how this can be used.   &lt;br /&gt;
&lt;br /&gt;
'''Figure 7: Ruby Monitor'''&lt;br /&gt;
&lt;br /&gt;
    require 'monitor'&lt;br /&gt;
        class Counter &amp;lt; Monitor&lt;br /&gt;
            attr_reader :count&lt;br /&gt;
        &lt;br /&gt;
            def initialize&lt;br /&gt;
                @count = 0&lt;br /&gt;
                super&lt;br /&gt;
            end&lt;br /&gt;
 &lt;br /&gt;
            def tick&lt;br /&gt;
                synchronize do&lt;br /&gt;
                @count += 1&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    c = Counter.new&lt;br /&gt;
    t1 = Thread.new { 10000.times {  c.tick } } &lt;br /&gt;
    t2 = Thread.new { 10000.times {  c.tick } }&lt;br /&gt;
    t1.join; t2.join&lt;br /&gt;
    c.count&lt;br /&gt;
&lt;br /&gt;
=Java vs Ruby Threads=&lt;br /&gt;
Java thread initialization is more involved than Ruby thread initialization. Ruby threads also have the advantage of a “quick and dirty” thread creation, since it only takes couple of lines of code.  A Ruby thread shares all global, instance and local variables that are in existence at the time the thread starts. A Java thread can share these variables, as well, depending on how the thread was created.  If the client thread class uses inheritance, any variables needed are passed along when creating the thread. If the thread is created through the interface, the variables can be shared as long as the class has been initialized and the variables in use. &lt;br /&gt;
	&lt;br /&gt;
Ruby’s green threads are completely portable, as they don’t rely on the OS. But, on a multi-core processor, native thread implementations can assign work to multiple processors while green threads cannot. In this environment native threads have a huge advantage as more work is done by the native threads.&lt;br /&gt;
&lt;br /&gt;
==Java and Ruby Methods Comparison==&lt;br /&gt;
&lt;br /&gt;
'''Table 1 lists thread actions and Java and Ruby’s equivalent methods of achieving them.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table1.jpg]]&lt;br /&gt;
&lt;br /&gt;
'''Table 2 lists thread actions available in Java, but Ruby doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table2.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Table 3 lists thread actions available in Ruby, but Java doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table3.jpg]]&lt;br /&gt;
&lt;br /&gt;
There are many similarities between the Java and Ruby Thread classes, as shown with the equivalent methods in Table 1.  But, as you can see, there are also many methods in Java that Ruby doesn't support and vice versa. Some methods like activeCount(), where it returns the number of active threads, are trivial, but there is a group of methods existing in both Java and Ruby that the other doesn't support. For Java, it is exception handling with getting/setting exceptions, while in Ruby, it is more thread control. Ruby has exception methods, but they are geared more toward events prior to the exception, like making sure all threads abort when exception starts and firing an exception to destroy threads. Java is more about setting the exceptions and getting them to change accordingly. So the Java Thread class has a little bit more exception handling than Ruby.&lt;br /&gt;
	&lt;br /&gt;
Ruby has more thread control for the programmer such as pausing, terminating, aborting and resuming threads. Java did have these functions, but they all have been deprecated because, although they give the user more control, they also can cause deadlock problems. So it is a tradeoff between more thread control and less chance for deadlocks to happen. Java does use interrupt to &amp;quot;pause&amp;quot; the thread as opposed to actually pausing the thread as in Ruby. Also, Java threads &amp;quot;sleep&amp;quot; differently than Ruby threads.  Java sleeps are timed, while Ruby's sleep just stops the thread indefinitely, until it gets woken up by &amp;quot;thr.wakeup&amp;quot;. As you can see Ruby's thread methods are more flexible, but potentially dangerous than Java’s.&lt;br /&gt;
&lt;br /&gt;
Basically, Java and Ruby both have similar thread functionalities.  In some respects, Java is simpler by reducing user error, while Ruby gives the programmer more power and perhaps more headaches. If user wants more control, then Ruby threading is great, but for simplicity Java is better.  The main distinction between Ruby threads and Java threads are that currently Ruby just supports green threads (as did Java 1.1) and Java has support for kernel threads.  Currently, there is no clear “winner” between native and green threads in a uni-processor system, but Java threads definitely have the edge over Ruby in a multi-processor environment.&lt;br /&gt;
Ruby is moving from green threads to kernel threads in Ruby 1.9 or 2.0, which are still development releases.  YARV has been integrated as the new Ruby VM.  YARV will give Ruby kernel thread support.  Detailed discussions of this change are at the following links:&lt;br /&gt;
http://www.infoq.com/news/2007/05/ruby-threading-futures&lt;br /&gt;
http://expressica.com/2008/04/26/new-in-ruby-19-threads/&lt;br /&gt;
&lt;br /&gt;
==Java vs. Ruby Thread Efficiency==&lt;br /&gt;
In order to test the efficiency of Java and Ruby threads two programs were written in each language.  The first one reads in the contents of five text files, one for each of five threads, searches for a given word in each and counts each occurrence of the word.  This count is added to a total count for all five files.  Each file is passed to its own thread to run.  The main thread has the total count, which is updated using mutual exclusion techniques in each language.  The second program was modified from the first.  Instead of searching for words in files, a string was passed to each thread. The times it took each to run each program depended on the size of the files, to a small extent and on the programming language to a larger extent.  The results are recorded in Table 4.  The file versions of these programs are given in Figures 8 and 9.  With the small file, the Ruby code ran about as fast as the Java code.  With the large file, the Java code ran five times faster than Ruby.  This is evidence that when doing file I/O, Java's native threads are much more efficient.  The string versions of these programs are not included in this Wiki.  Both the Java code and the Ruby code processed the strings in approximately the same about of time.  I had expected the Ruby code to outperform Java with this version.  &lt;br /&gt;
&lt;br /&gt;
{| border=&amp;quot;1&amp;quot;&lt;br /&gt;
|+ Table 4: WordCounts Running Times&lt;br /&gt;
|- &lt;br /&gt;
! File Sizes&lt;br /&gt;
! Ruby Times&lt;br /&gt;
! Java Times&lt;br /&gt;
|-&lt;br /&gt;
| 10KB&lt;br /&gt;
| 16 millisecs&lt;br /&gt;
| 15 millisecs&lt;br /&gt;
|-&lt;br /&gt;
| 80KB&lt;br /&gt;
| 119 millisecs&lt;br /&gt;
| 20 millisecs&lt;br /&gt;
|-&lt;br /&gt;
! String Sizes&lt;br /&gt;
! Ruby Times&lt;br /&gt;
! Java Times&lt;br /&gt;
|-&lt;br /&gt;
| 10KB&lt;br /&gt;
| 15 millisecs&lt;br /&gt;
| 16 millisecs&lt;br /&gt;
|-&lt;br /&gt;
| 60KB&lt;br /&gt;
| 20 millisecs&lt;br /&gt;
| 22 millisecs&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
'''Figure 8: Java Word Counts Code'''&lt;br /&gt;
    public class WordCounts {&lt;br /&gt;
        protected static int wordCount;&lt;br /&gt;
        &lt;br /&gt;
        private class Semaphore {&lt;br /&gt;
            private int mutex;  &lt;br /&gt;
      &lt;br /&gt;
            public Semaphore () {&lt;br /&gt;
                mutex = 1;&lt;br /&gt;
            }&lt;br /&gt;
       &lt;br /&gt;
            public synchronized void acquire() throws InterruptedException {&lt;br /&gt;
                while (mutex == 0) {&lt;br /&gt;
                   wait();&lt;br /&gt;
                }&lt;br /&gt;
                mutex--;&lt;br /&gt;
            }&lt;br /&gt;
            public synchronized void release() {&lt;br /&gt;
                mutex++;    &lt;br /&gt;
                notifyAll();&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
    &lt;br /&gt;
        private class WordCountsThread implements Runnable {&lt;br /&gt;
            private String word;&lt;br /&gt;
            private String file;        &lt;br /&gt;
            private int count;&lt;br /&gt;
            private Semaphore total; &lt;br /&gt;
                   &lt;br /&gt;
            public WordCountsThread (String word, String file, Semaphore total) {&lt;br /&gt;
                this.word  = word; &lt;br /&gt;
                this.file  = file;&lt;br /&gt;
                this.total = total;&lt;br /&gt;
                count      = 0;&lt;br /&gt;
            }    &lt;br /&gt;
     &lt;br /&gt;
            public void run(){&lt;br /&gt;
                readWordFile();&lt;br /&gt;
        &lt;br /&gt;
                try {&lt;br /&gt;
                    total.acquire();&lt;br /&gt;
                    wordCount = wordCount + count;&lt;br /&gt;
                    total.release();&lt;br /&gt;
                } catch (InterruptedException e) {&lt;br /&gt;
                    System.out.println (e);&lt;br /&gt;
                }&lt;br /&gt;
            }&lt;br /&gt;
     &lt;br /&gt;
            private void readWordFile (){&lt;br /&gt;
            }   // end method&lt;br /&gt;
        } //end inner class: WordCountThread&lt;br /&gt;
     &lt;br /&gt;
    &lt;br /&gt;
        public WordCounts (String searchWord, String [] files) {&lt;br /&gt;
            int numFiles = files.length;&lt;br /&gt;
            Semaphore total = new Semaphore();&lt;br /&gt;
            Thread [] threads = new Thread [numFiles];&lt;br /&gt;
          &lt;br /&gt;
            for (int i = 0; i &amp;lt; numFiles; i++ ) {&lt;br /&gt;
                threads[i] = new Thread (new WordCountsThread (searchWord,files[i], total));&lt;br /&gt;
            }&lt;br /&gt;
        &lt;br /&gt;
            for (int j = 0; j &amp;lt; numFiles; j++ ) {&lt;br /&gt;
                threads[j].start();&lt;br /&gt;
            }&lt;br /&gt;
        &lt;br /&gt;
            try {&lt;br /&gt;
                for (int i = 0; i &amp;lt; numFiles; i++ ) {&lt;br /&gt;
                    threads[i].join();&lt;br /&gt;
                } &lt;br /&gt;
            } catch (InterruptedException e) {&lt;br /&gt;
                System.out.println (e);&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void displayTotal (String searchWord) {&lt;br /&gt;
            System.out.println (&amp;quot;There are &amp;quot; + wordCount + &lt;br /&gt;
                            &amp;quot; total occurrences of &amp;quot; + searchWord);&lt;br /&gt;
        }&lt;br /&gt;
    &lt;br /&gt;
        public static void main (String [] args) {&lt;br /&gt;
            String [] files;              &lt;br /&gt;
            files = new String [5];   &lt;br /&gt;
            files [0] = &amp;quot;Player.java&amp;quot;;&lt;br /&gt;
            files [1] = &amp;quot;KingMove.java&amp;quot;;&lt;br /&gt;
            files [2] = &amp;quot;NodeDeque.java&amp;quot;;&lt;br /&gt;
            files [3] = &amp;quot;Position.java&amp;quot;;&lt;br /&gt;
            files [4] = &amp;quot;DoubleDigest.java&amp;quot;;&lt;br /&gt;
            String searchWord = &amp;quot;public&amp;quot;;&lt;br /&gt;
            long time = System.currentTimeMillis (), time_prev = time;&lt;br /&gt;
            WordCounts wc = new WordCounts (searchWord, files);&lt;br /&gt;
            wc.displayTotal (searchWord);&lt;br /&gt;
            time = System.currentTimeMillis ();&lt;br /&gt;
            System.out.println (&amp;quot;Diff &amp;quot; + (time - time_prev) + &amp;quot; msecs&amp;quot;);&lt;br /&gt;
            System.exit(0);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 9: Ruby Word Counts Code'''&lt;br /&gt;
&lt;br /&gt;
    class WordCounts &amp;lt; Monitor&lt;br /&gt;
        attr_reader :wordCount, :numFiles, :searchWord&lt;br /&gt;
      &lt;br /&gt;
        def initialize&lt;br /&gt;
            super&lt;br /&gt;
        end # initialize def&lt;br /&gt;
        &lt;br /&gt;
        def initVars(files, searchWord)&lt;br /&gt;
            @wordCount  = 0&lt;br /&gt;
            @files      = files&lt;br /&gt;
            @searchWord = searchWord&lt;br /&gt;
        end # initVars        &lt;br /&gt;
       &lt;br /&gt;
        def countWordsInFiles&lt;br /&gt;
             threads = []&lt;br /&gt;
   &lt;br /&gt;
            for fileToFetch in @files&lt;br /&gt;
                threads &amp;lt;&amp;lt; Thread.new(fileToFetch) do |file|&lt;br /&gt;
                count = readWordFile(file)&lt;br /&gt;
                updateTotal(count)&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
        threads.each {|t| t.join}&lt;br /&gt;
    end # countWordsInFiles &lt;br /&gt;
      &lt;br /&gt;
    def readWordFile(file)&lt;br /&gt;
        ...&lt;br /&gt;
        puts (&amp;quot;There are &amp;quot; + count.to_s + &amp;quot; occurrences of '&amp;quot; + @searchWord[0] + &amp;quot;' in &amp;quot; + file + &amp;quot;\n&amp;quot;)&lt;br /&gt;
        return count&lt;br /&gt;
    end # readWordFile def  &lt;br /&gt;
    &lt;br /&gt;
    def displayTotal&lt;br /&gt;
        puts (&amp;quot;\nThere are &amp;quot; + @wordCount.to_s + &amp;quot; total occurrences of '&amp;quot; + @searchWord[0] + &amp;quot;'&amp;quot;)&lt;br /&gt;
    end # displayTotal def &lt;br /&gt;
  &lt;br /&gt;
    def updateTotal (count)&lt;br /&gt;
        synchronize do&lt;br /&gt;
            @wordCount += count&lt;br /&gt;
        end&lt;br /&gt;
    end # updateTotal def&lt;br /&gt;
    end # WordCounts class def&lt;br /&gt;
    &lt;br /&gt;
    files = %w( Player.java KingMove.java NodeDeque.java Position.java DoubleDigest.java)&lt;br /&gt;
    searchWord = %w( public )&lt;br /&gt;
    wc = WordCounts.new&lt;br /&gt;
    wc.initVars(files, searchWord)&lt;br /&gt;
    ustart = Time.now.usec&lt;br /&gt;
    wc.countWordsInFiles&lt;br /&gt;
    wc.displayTotal&lt;br /&gt;
    t = Time.now&lt;br /&gt;
    uend = Time.now.usec&lt;br /&gt;
    puts (&amp;quot;Start: &amp;quot; + ustart.to_s + &amp;quot; usecs&amp;quot;)&lt;br /&gt;
    puts (&amp;quot;End: &amp;quot; + uend.to_s + &amp;quot; usecs&amp;quot;)&lt;br /&gt;
    puts (&amp;quot;diff: &amp;quot; + ((uend - ustart)/1000.0).to_s + &amp;quot; msecs&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_threads.html&lt;br /&gt;
&lt;br /&gt;
http://www.ruby-doc.org/core/classes/Thread.html&lt;br /&gt;
&lt;br /&gt;
http://phrogz.net/ProgrammingRuby/ref_c_thread.html&lt;br /&gt;
&lt;br /&gt;
http://www.javaworld.com/javaworld/jw-04-1996/jw-04-threads.html&lt;br /&gt;
&lt;br /&gt;
http://java.sun.com/javase/6/docs/api/java/lang/Thread.html&lt;br /&gt;
&lt;br /&gt;
http://en.wikipedia.org/wiki/Green_threads&lt;br /&gt;
&lt;br /&gt;
http://corelib.rubyonrails.com/classes/Thread.html&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12876</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12876"/>
		<updated>2008-06-09T17:15:43Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
A thread is a basic unit of CPU utilization.  A traditional process has a single thread of control.  Many modern operating systems provide features enabling a process to contain multiple threads of control.  If the process has multiple threads of control, it can do more than one task at a time, such as, displaying graphics and reading keystrokes.  Threads are used mainly to run asynchronous tasks and pass the application’s tasks to an executor.  They are useful because they reduce the overall time of execution of programs. All threads belonging to the same process share its code section, data section and other operating system resources, such as open files and signals.  Thus multithreading is more efficient than having parallel processes running for the same program, which require a huge overhead.&lt;br /&gt;
&lt;br /&gt;
=Multi-threaded Programming= &lt;br /&gt;
Multithreading support for single processors works by giving each of the threads a “time slice” of the CPU, similar to the parallel execution of processes.  On multi-core machines, different threads can run on the different processors and the threads truly run simultaneously.   Support for threads may be provided at either the user level, for user or green threads, or by the kernel, for kernel or native threads.  User threads are supported above the kernel and are managed without kernel support, whereas kernel threads are supported and managed directly by the operating system.&lt;br /&gt;
&lt;br /&gt;
==Multi-threading Models==&lt;br /&gt;
There are three common multithreading models&lt;br /&gt;
&lt;br /&gt;
===One-to-One===&lt;br /&gt;
This model maps each user-thread to a kernel thread.  It provides more concurrency than the many-to-one model by allowing another thread to run when a thread makes a blocking system call.  It also allows multiple threads to run in parallel on multiprocessors.  The main disadvantage of this model is the overhead of creating each kernel thread for each user thread.  This burdens the performance of an application and limits the number of threads supported by the system.&lt;br /&gt;
&lt;br /&gt;
===Many-to-One===&lt;br /&gt;
This model maps many user-level threads to one kernel thread.  It is the model used by green threads.  Green threads are scheduled by a Virtual Machine instead of natively by the OS. They emulate multithreaded environments without relying on any native OS capabilities. These user-level threads are lightweight and very efficient.  They are an easy way to achieve parallelism in a program.   An application can have as many user-level threads as it needs, but true concurrency is not achieved because the kernel can schedule only one thread at a time. The developers can create as many user threads as necessary.  However, there are two main disadvantages:&lt;br /&gt;
1)	If a thread makes a blocking system call, the entire process will block.&lt;br /&gt;
2)	If you are running on a multi-core machine, the multiple threads are unable to run in parallel.&lt;br /&gt;
&lt;br /&gt;
===Many-to-Many===&lt;br /&gt;
This model multiplexes many user-level threads to a smaller or equal number of kernel threads.  This model has the best of both worlds.  Developers can create as many user threads as they need.  When a user thread performs a blocking system call, the kernel can schedule another thread for execution and the kernel threads can run in parallel on multi-core systems.&lt;br /&gt;
&lt;br /&gt;
==Benefits of Multi-threading==&lt;br /&gt;
===Resource sharing===&lt;br /&gt;
Memory, code and process resource sharing - allocating memory and resources for process creation is costly and time consuming.  It is more economical to create threads than new processes.  Applications can benefit by having several different threads of activity within the same address space.&lt;br /&gt;
&lt;br /&gt;
===Responsiveness===&lt;br /&gt;
Multithreading an interactive application may allow a program to continue running, even if part of it is blocked doing IO or performing a lengthy operation, thereby increasing responsiveness to the user.  A web browser might have one thread display images or text while another thread retrieves data from the network.  A busy web server may have many clients concurrently accessing it.  If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time.&lt;br /&gt;
&lt;br /&gt;
==Potential Problems of Multi-threading==&lt;br /&gt;
Many threaded programs have shared resources that must be accessed by more than one thread.  These programs must implement a form of mutual exclusion to ensure that only one of the threads can access the resource at a time.  These shared resources must execute in code called critical sections.  These critical sections must be protected by either hardware or software means.&lt;br /&gt;
&lt;br /&gt;
=Java Threads=&lt;br /&gt;
The Java programming language has a thread library for creating and managing threads at the user-level.  The Java virtual machine (JVM) manages the mapping of the user threads to the operating system kernel threads.  The particular mapping model that is used depends on the operating system on which the Java program is running.  Java’s Thread Scheduler monitors all the threads running in Java programs.  It decides which threads to run at any given time and when to switch between threads to run based on the thread’s priority with higher running threads running before lower priority threads.  The Java scheduler uses either preemptive or non-preemptive scheduling based on the operating system on which it is running.  With preemptive scheduling, each thread is given a constant period of time to run, after which time the thread will be suspended() to allow the next thread to resume() running.  With non-preemptive scheduling, the running thread is allowed to run until the thread completes or until it issues a yield() to allow other threads to run while it waits for some other processing to occur.  &lt;br /&gt;
A Java thread can be created either by having your Java class extend the Java Thread class or by having your Java class implement the Runnable interface and coding a run() method.  The two options are shown in Figures 1 and 2.   The preferred method for creating a thread is by implementing the Runnable interface.  It is more flexible and useful in complex applications.   Java does not support multiple inheritance, but a class may implement multiple interfaces.  By using the interface method, the Client class is open to inherit another class, if the need arose in the future.&lt;br /&gt;
  &lt;br /&gt;
'''Figure 1: Client Extends Thread Class'''&lt;br /&gt;
        &lt;br /&gt;
    public class Client extends Thread {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Server {&lt;br /&gt;
        public static void main(String args[]){&lt;br /&gt;
            Thread runner = new Client();&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 2: Client Implements Runnable Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
   &lt;br /&gt;
    public class Server {&lt;br /&gt;
    &lt;br /&gt;
        public static void main(String args[]) {&lt;br /&gt;
            Thread runner = new Thread(new Client());&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
If the main Java thread wants to wait for any threads it creates to finish their run() method, the thread method join() can be executed.  The join() method is useful in situations where the creating thread can continue only after a worker thread has completed.  Java threads can be asynchronously terminated using the stop() method.  However, this method has been deprecated and its used is discouraged.  The preferred cancellation technique is to have the target thread periodically check whether it should terminate by using the interrupt() method.&lt;br /&gt;
&lt;br /&gt;
==States of Java Threads==&lt;br /&gt;
===New===&lt;br /&gt;
A thread is in this state when the thread object is first created with the new() method.&lt;br /&gt;
===Runnable===&lt;br /&gt;
Calling the start() method allocates memory for the new thread in the JVM and calls the run() method for the thread object.&lt;br /&gt;
===Blocked===&lt;br /&gt;
A thread becomes blocked if it performs a blocking statement, such as doing I/O or if it invokes a sleep() method.&lt;br /&gt;
===Dead===&lt;br /&gt;
A thread moves to the dead state when its run() method terminates.&lt;br /&gt;
&lt;br /&gt;
==Mutual Exclusion==&lt;br /&gt;
The Java language implements mutual exclusion in a couple of ways.  There exists a MutualExclusion interface.  The Client class can implement this interface and code the methods, enteringCriticalSection() and leavingCriticalSection(), as shown in Figure 3.  The yield() method tells the Thread Scheduler to allow another thread to run.  &lt;br /&gt;
&lt;br /&gt;
'''Figure 3: Client Implements MutualExclusion Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements MutualExclusion{&lt;br /&gt;
    &lt;br /&gt;
        public Client(){&lt;br /&gt;
            flag0 = false; flag1 = false; turn = TURN_0;&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void enteringCriticalSection(int t) {&lt;br /&gt;
            int other = 1 - t;&lt;br /&gt;
            &lt;br /&gt;
            if (t == 0) {&lt;br /&gt;
                flag0 = true; turn = other;&lt;br /&gt;
                while ((flag1 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             } else {&lt;br /&gt;
                flag1 = true; turn = other;&lt;br /&gt;
     	        while ((flag0 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void leavingCriticalSection(int t) {&lt;br /&gt;
            if(t == 0) flag0 = false;&lt;br /&gt;
            else   flag1 = false;&lt;br /&gt;
        }&lt;br /&gt;
        private volatile int turn, boolean flag0, flag1;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
An alternative method of handling mutual exclusion is to code a synchronization tool called a semaphore.  A semaphore is variable that is accessed only through two standard operations: acquire() and release().  The semaphore is acquired, then the critical section of an object is entered and after the critical code completes, the semaphore is released.  An example of this code is in Figure 4.&lt;br /&gt;
&lt;br /&gt;
'''Figure 4: Client Has Semaphore'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
    &lt;br /&gt;
        public Client (Semaphore sem) {&lt;br /&gt;
            this.sem = sem;&lt;br /&gt;
        }&lt;br /&gt;
       &lt;br /&gt;
        public void run() {&lt;br /&gt;
            sem.acquire();&lt;br /&gt;
            System.out.println(&amp;quot;Entering critical section&amp;quot;);&lt;br /&gt;
            SleepUtilities.nap(3);&lt;br /&gt;
            System.out.println(&amp;quot;Leaving critical section&amp;quot;);&lt;br /&gt;
            sem.release();&lt;br /&gt;
        }&lt;br /&gt;
        private Semaphore sem;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Ruby Threads=&lt;br /&gt;
At the present time the Ruby programming language just supports green threads.  These are totally implemented within the Ruby interpreter.  The threads, as well as the thread scheduler run on the same single operating system thread.  Ruby can support thread methods, such as stop() and kill(), that are not advised for kernel threads.  However, Ruby threads suffer from the drawbacks of non-native threads.  They can only run on one processor in a multiprocessor environment.  It is possible for a single thread to cause the whole process to deadlock, if poorly designed.  The worse problem with Ruby threads is with I/O, especially network access, since it has the potential to block a process for a long time.  This problem is solvable by using non-blocking I/O.  However, one problem that is not solvable using non-blocking I/O, is the DNS lookup system call.  Ruby solves this problem with their resolv library, which was written specifically to address the threading issue with the standard OS DNA lookup mechanism.  See Figure 5 for an example of the code that handles this issue.  Despite some of the green thread concerns, for most situations, the benefits of efficiency can far outweigh the disadvantages.&lt;br /&gt;
&lt;br /&gt;
'''Figure 5: Ruby DNS Lookup Implementation'''&lt;br /&gt;
    &lt;br /&gt;
    require ‘socket’&lt;br /&gt;
    require ‘resolv-replace’&lt;br /&gt;
    count = 0&lt;br /&gt;
    Thread.critical = true&lt;br /&gt;
    thread = Thread.new { Thread.pass; loop { count += 1; } } IPSocket.getaddress(www.ruby-lang.org) &lt;br /&gt;
    count&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A Ruby thread is created using Thread.new() {block}.  The arguments given in the new() method are passed to the block code that the thread executes.  See Figure 6 for an example of creating a Ruby thread.  The Ruby pass() method is analogous to the Java yield() method.  It tells the thread scheduler to pass execution to another thread.  Ruby has a join() method that performs the same functionality as the Java join().  There are run() and wakeup() methods that wake up a sleeping threads, either giving it control or indicating that it is ready to be scheduled. &lt;br /&gt;
&lt;br /&gt;
'''Figure 6: Creating Ruby Threads'''&lt;br /&gt;
&lt;br /&gt;
    threads = []&lt;br /&gt;
    4.times do |number|&lt;br /&gt;
        threads &amp;lt;&amp;lt; Thread.new(number) do |i|&lt;br /&gt;
            print “#{i}\n”    &lt;br /&gt;
        end &lt;br /&gt;
    end&lt;br /&gt;
    threads.each { |t| t.join }  &lt;br /&gt;
&lt;br /&gt;
==States of Ruby Threads==&lt;br /&gt;
===Run===&lt;br /&gt;
The thread is executing.&lt;br /&gt;
===Sleep===&lt;br /&gt;
The thread is sleeping or waiting on I/O.&lt;br /&gt;
===Aborting===&lt;br /&gt;
The thread is aborting (has been killed).&lt;br /&gt;
===False===&lt;br /&gt;
The thread has terminated normally.&lt;br /&gt;
===Nil===&lt;br /&gt;
The thread has terminated with an exception.&lt;br /&gt;
&lt;br /&gt;
==Mutual Exclusion==&lt;br /&gt;
The best way to handle mutual exclusion in Ruby is with the Monitor class.  A monitor has a synchronization() method that prevent access to a resource by another thread while one is execution in that method.  Figure 7 shows an example of how this can be used.   &lt;br /&gt;
&lt;br /&gt;
'''Figure 7: Ruby Monitor'''&lt;br /&gt;
&lt;br /&gt;
    require 'monitor'&lt;br /&gt;
        class Counter &amp;lt; Monitor&lt;br /&gt;
            attr_reader :count&lt;br /&gt;
        &lt;br /&gt;
            def initialize&lt;br /&gt;
                @count = 0&lt;br /&gt;
                super&lt;br /&gt;
            end&lt;br /&gt;
 &lt;br /&gt;
            def tick&lt;br /&gt;
                synchronize do&lt;br /&gt;
                @count += 1&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    c = Counter.new&lt;br /&gt;
    t1 = Thread.new { 10000.times {  c.tick } } &lt;br /&gt;
    t2 = Thread.new { 10000.times {  c.tick } }&lt;br /&gt;
    t1.join; t2.join&lt;br /&gt;
    c.count&lt;br /&gt;
&lt;br /&gt;
=Java vs Ruby Threads=&lt;br /&gt;
Java thread initialization is more involved than Ruby thread initialization. Ruby threads also have the advantage of a “quick and dirty” thread creation, since it only takes couple of lines of code.  A Ruby thread shares all global, instance and local variables that are in existence at the time the thread starts. A Java thread can share these variables, as well, depending on how the thread was created.  If the client thread class uses inheritance, any variables needed are passed along when creating the thread. If the thread is created through the interface, the variables can be shared as long as the class has been initialized and the variables in use. &lt;br /&gt;
	&lt;br /&gt;
Ruby’s green threads are completely portable, as they don’t rely on the OS. But, on a multi-core processor, native thread implementations can assign work to multiple processors while green threads cannot. In this environment native threads have a huge advantage as more work is done by the native threads.&lt;br /&gt;
&lt;br /&gt;
==Java and Ruby Methods Comparison==&lt;br /&gt;
&lt;br /&gt;
'''Table 1 lists thread actions and Java and Ruby’s equivalent methods of achieving them.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table1.jpg]]&lt;br /&gt;
&lt;br /&gt;
'''Table 2 lists thread actions available in Java, but Ruby doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table2.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Table 3 lists thread actions available in Ruby, but Java doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table3.jpg]]&lt;br /&gt;
&lt;br /&gt;
There are many similarities between the Java and Ruby Thread classes, as shown with the equivalent methods in Table 1.  But, as you can see, there are also many methods in Java that Ruby doesn't support and vice versa. Some methods like activeCount(), where it returns the number of active threads, are trivial, but there is a group of methods existing in both Java and Ruby that the other doesn't support. For Java, it is exception handling with getting/setting exceptions, while in Ruby, it is more thread control. Ruby has exception methods, but they are geared more toward events prior to the exception, like making sure all threads abort when exception starts and firing an exception to destroy threads. Java is more about setting the exceptions and getting them to change accordingly. So the Java Thread class has a little bit more exception handling than Ruby.&lt;br /&gt;
	&lt;br /&gt;
Ruby has more thread control for the programmer such as pausing, terminating, aborting and resuming threads. Java did have these functions, but they all have been deprecated because, although they give the user more control, they also can cause deadlock problems. So it is a tradeoff between more thread control and less chance for deadlocks to happen. Java does use interrupt to &amp;quot;pause&amp;quot; the thread as opposed to actually pausing the thread as in Ruby. Also, Java threads &amp;quot;sleep&amp;quot; differently than Ruby threads.  Java sleeps are timed, while Ruby's sleep just stops the thread indefinitely, until it gets woken up by &amp;quot;thr.wakeup&amp;quot;. As you can see Ruby's thread methods are more flexible, but potentially dangerous than Java’s.&lt;br /&gt;
&lt;br /&gt;
Basically, Java and Ruby both have similar thread functionalities.  In some respects, Java is simpler by reducing user error, while Ruby gives the programmer more power and perhaps more headaches. If user wants more control, then Ruby threading is great, but for simplicity Java is better.  The main distinction between Ruby threads and Java threads are that currently Ruby just supports green threads (as did Java 1.1) and Java has support for kernel threads.  Currently, there is no clear “winner” between native and green threads in a uni-processor system, but Java threads definitely have the edge over Ruby in a multi-processor environment.&lt;br /&gt;
Ruby is moving from green threads to kernel threads in Ruby 1.9 or 2.0, which are still development releases.  YARV has been integrated as the new Ruby VM.  YARV will give Ruby kernel thread support.  Detailed discussions of this change are at the following links:&lt;br /&gt;
http://www.infoq.com/news/2007/05/ruby-threading-futures&lt;br /&gt;
http://expressica.com/2008/04/26/new-in-ruby-19-threads/&lt;br /&gt;
&lt;br /&gt;
==Java vs. Ruby Thread Efficiency==&lt;br /&gt;
In order to test the efficiency of Java and Ruby threads two programs were written in each language.  The first one reads in the contents of five text files, one for each of five threads, searches for a given word in each and counts each occurrence of the word.  This count is added to a total count for all five files.  Each file is passed to its own thread to run.  The main thread has the total count, which is updated using mutual exclusion techniques in each language.  The second program was modified from the first.  Instead of searching for words in files, a string was passed to each thread. The times it took each to run each program depended on the size of the files, to a small extent and on the programming language to a larger extent.  The results are recorded in Table 4.  The file versions of these programs are given in Figures 8 and 9.  With the small file, the Ruby code ran about as fast as the Java code.  With the large file, the Java code ran five times faster than Ruby.  This is evidence that when doing file I/O, Java's native threads are much more efficient.  The string versions of these programs are not included in this Wiki.  Both the Java code and the Ruby code processed the strings in approximately the same about of time.  I had expected the Ruby code to outperform Java with this version.  &lt;br /&gt;
&lt;br /&gt;
{| border=&amp;quot;1&amp;quot;&lt;br /&gt;
|+ Table 4: WordCounts Running Times&lt;br /&gt;
|- &lt;br /&gt;
! File Sizes&lt;br /&gt;
! Ruby Times&lt;br /&gt;
! Java Times&lt;br /&gt;
|-&lt;br /&gt;
| 10KB&lt;br /&gt;
| 16 millisecs&lt;br /&gt;
| 15 millisecs&lt;br /&gt;
|-&lt;br /&gt;
| 80KB&lt;br /&gt;
| 119 millisecs&lt;br /&gt;
| 20 millisecs&lt;br /&gt;
|-&lt;br /&gt;
! String Sizes&lt;br /&gt;
! Ruby Times&lt;br /&gt;
! Java Times&lt;br /&gt;
|-&lt;br /&gt;
| 10KB&lt;br /&gt;
| 15 millisecs&lt;br /&gt;
| 16 millisecs&lt;br /&gt;
|-&lt;br /&gt;
| 60KB&lt;br /&gt;
| 20 millisecs&lt;br /&gt;
| 22 millisecs&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
'''Figure 8: Java Word Counts Code'''&lt;br /&gt;
    public class WordCounts {&lt;br /&gt;
        protected static int wordCount;&lt;br /&gt;
        &lt;br /&gt;
        private class Semaphore {&lt;br /&gt;
            private int mutex;  &lt;br /&gt;
      &lt;br /&gt;
            public Semaphore () {&lt;br /&gt;
                mutex = 1;&lt;br /&gt;
            }&lt;br /&gt;
       &lt;br /&gt;
            public synchronized void acquire() throws InterruptedException {&lt;br /&gt;
                while (mutex == 0) {&lt;br /&gt;
                   wait();&lt;br /&gt;
                }&lt;br /&gt;
                mutex--;&lt;br /&gt;
            }&lt;br /&gt;
            public synchronized void release() {&lt;br /&gt;
                mutex++;    &lt;br /&gt;
                notifyAll();&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
    &lt;br /&gt;
        private class WordCountsThread implements Runnable {&lt;br /&gt;
            private String word;&lt;br /&gt;
            private String file;        &lt;br /&gt;
            private int count;&lt;br /&gt;
            private Semaphore total; &lt;br /&gt;
                   &lt;br /&gt;
            public WordCountsThread (String word, String file, Semaphore total) {&lt;br /&gt;
                this.word  = word; &lt;br /&gt;
                this.file  = file;&lt;br /&gt;
                this.total = total;&lt;br /&gt;
                count      = 0;&lt;br /&gt;
            }    &lt;br /&gt;
     &lt;br /&gt;
            public void run(){&lt;br /&gt;
                readWordFile();&lt;br /&gt;
        &lt;br /&gt;
                try {&lt;br /&gt;
                    total.acquire();&lt;br /&gt;
                    wordCount = wordCount + count;&lt;br /&gt;
                    total.release();&lt;br /&gt;
                } catch (InterruptedException e) {&lt;br /&gt;
                    System.out.println (e);&lt;br /&gt;
                }&lt;br /&gt;
            }&lt;br /&gt;
     &lt;br /&gt;
            private void readWordFile (){&lt;br /&gt;
            }   // end method&lt;br /&gt;
        } //end inner class: WordCountThread&lt;br /&gt;
     &lt;br /&gt;
    &lt;br /&gt;
        public WordCounts (String searchWord, String [] files) {&lt;br /&gt;
            int numFiles = files.length;&lt;br /&gt;
            Semaphore total = new Semaphore();&lt;br /&gt;
            Thread [] threads = new Thread [numFiles];&lt;br /&gt;
          &lt;br /&gt;
            for (int i = 0; i &amp;lt; numFiles; i++ ) {&lt;br /&gt;
                threads[i] = new Thread (new WordCountsThread (searchWord,files[i], total));&lt;br /&gt;
            }&lt;br /&gt;
        &lt;br /&gt;
            for (int j = 0; j &amp;lt; numFiles; j++ ) {&lt;br /&gt;
                threads[j].start();&lt;br /&gt;
            }&lt;br /&gt;
        &lt;br /&gt;
            try {&lt;br /&gt;
                for (int i = 0; i &amp;lt; numFiles; i++ ) {&lt;br /&gt;
                    threads[i].join();&lt;br /&gt;
                } &lt;br /&gt;
            } catch (InterruptedException e) {&lt;br /&gt;
                System.out.println (e);&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void displayTotal (String searchWord) {&lt;br /&gt;
            System.out.println (&amp;quot;There are &amp;quot; + wordCount + &lt;br /&gt;
                            &amp;quot; total occurrences of &amp;quot; + searchWord);&lt;br /&gt;
        }&lt;br /&gt;
    &lt;br /&gt;
        public static void main (String [] args) {&lt;br /&gt;
            String [] files;              &lt;br /&gt;
            files = new String [5];   &lt;br /&gt;
            files [0] = &amp;quot;Player.java&amp;quot;;&lt;br /&gt;
            files [1] = &amp;quot;KingMove.java&amp;quot;;&lt;br /&gt;
            files [2] = &amp;quot;NodeDeque.java&amp;quot;;&lt;br /&gt;
            files [3] = &amp;quot;Position.java&amp;quot;;&lt;br /&gt;
            files [4] = &amp;quot;DoubleDigest.java&amp;quot;;&lt;br /&gt;
            String searchWord = &amp;quot;public&amp;quot;;&lt;br /&gt;
            long time = System.currentTimeMillis (), time_prev = time;&lt;br /&gt;
            WordCounts wc = new WordCounts (searchWord, files);&lt;br /&gt;
            wc.displayTotal (searchWord);&lt;br /&gt;
            time = System.currentTimeMillis ();&lt;br /&gt;
            System.out.println (&amp;quot;Diff &amp;quot; + (time - time_prev) + &amp;quot; msecs&amp;quot;);&lt;br /&gt;
            System.exit(0);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 9: Ruby Word Counts Code'''&lt;br /&gt;
&lt;br /&gt;
    class WordCounts &amp;lt; Monitor&lt;br /&gt;
        attr_reader :wordCount, :numFiles, :searchWord&lt;br /&gt;
      &lt;br /&gt;
        def initialize&lt;br /&gt;
            super&lt;br /&gt;
        end # initialize def&lt;br /&gt;
        &lt;br /&gt;
        def initVars(files, searchWord)&lt;br /&gt;
            @wordCount  = 0&lt;br /&gt;
            @files      = files&lt;br /&gt;
            @searchWord = searchWord&lt;br /&gt;
        end # initVars        &lt;br /&gt;
       &lt;br /&gt;
        def countWordsInFiles&lt;br /&gt;
             threads = []&lt;br /&gt;
   &lt;br /&gt;
            for fileToFetch in @files&lt;br /&gt;
                threads &amp;lt;&amp;lt; Thread.new(fileToFetch) do |file|&lt;br /&gt;
                count = readWordFile(file)&lt;br /&gt;
                updateTotal(count)&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
        threads.each {|t| t.join}&lt;br /&gt;
    end # countWordsInFiles &lt;br /&gt;
      &lt;br /&gt;
    def readWordFile(file)&lt;br /&gt;
        ...&lt;br /&gt;
        puts (&amp;quot;There are &amp;quot; + count.to_s + &amp;quot; occurrences of '&amp;quot; + @searchWord[0] + &amp;quot;' in &amp;quot; + file + &amp;quot;\n&amp;quot;)&lt;br /&gt;
        return count&lt;br /&gt;
    end # readWordFile def  &lt;br /&gt;
    &lt;br /&gt;
    def displayTotal&lt;br /&gt;
        puts (&amp;quot;\nThere are &amp;quot; + @wordCount.to_s + &amp;quot; total occurrences of '&amp;quot; + @searchWord[0] + &amp;quot;'&amp;quot;)&lt;br /&gt;
    end # displayTotal def &lt;br /&gt;
  &lt;br /&gt;
    def updateTotal (count)&lt;br /&gt;
        synchronize do&lt;br /&gt;
            @wordCount += count&lt;br /&gt;
        end&lt;br /&gt;
    end # updateTotal def&lt;br /&gt;
    end # WordCounts class def&lt;br /&gt;
    &lt;br /&gt;
    files = %w( Player.java KingMove.java NodeDeque.java Position.java DoubleDigest.java)&lt;br /&gt;
    searchWord = %w( public )&lt;br /&gt;
    wc = WordCounts.new&lt;br /&gt;
    wc.initVars(files, searchWord)&lt;br /&gt;
    ustart = Time.now.usec&lt;br /&gt;
    wc.countWordsInFiles&lt;br /&gt;
    wc.displayTotal&lt;br /&gt;
    t = Time.now&lt;br /&gt;
    uend = Time.now.usec&lt;br /&gt;
    puts (&amp;quot;Start: &amp;quot; + ustart.to_s + &amp;quot; usecs&amp;quot;)&lt;br /&gt;
    puts (&amp;quot;End: &amp;quot; + uend.to_s + &amp;quot; usecs&amp;quot;)&lt;br /&gt;
    puts (&amp;quot;diff: &amp;quot; + ((uend - ustart)/1000.0).to_s + &amp;quot; msecs&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_threads.html&lt;br /&gt;
http://www.ruby-doc.org/core/classes/Thread.html&lt;br /&gt;
http://phrogz.net/ProgrammingRuby/ref_c_thread.html&lt;br /&gt;
http://www.javaworld.com/javaworld/jw-04-1996/jw-04-threads.html&lt;br /&gt;
http://java.sun.com/javase/6/docs/api/java/lang/Thread.html&lt;br /&gt;
http://en.wikipedia.org/wiki/Green_threads&lt;br /&gt;
http://corelib.rubyonrails.com/classes/Thread.html&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12875</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12875"/>
		<updated>2008-06-09T16:49:18Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
A thread is a basic unit of CPU utilization.  A traditional process has a single thread of control.  Many modern operating systems provide features enabling a process to contain multiple threads of control.  If the process has multiple threads of control, it can do more than one task at a time, such as, displaying graphics and reading keystrokes.  Threads are used mainly to run asynchronous tasks and pass the application’s tasks to an executor.  They are useful because they reduce the overall time of execution of programs. All threads belonging to the same process share its code section, data section and other operating system resources, such as open files and signals.  Thus multithreading is more efficient than having parallel processes running for the same program, which require a huge overhead.&lt;br /&gt;
&lt;br /&gt;
=Multi-threaded Programming= &lt;br /&gt;
Multithreading support for single processors works by giving each of the threads a “time slice” of the CPU, similar to the parallel execution of processes.  On multi-core machines, different threads can run on the different processors and the threads truly run simultaneously.   Support for threads may be provided at either the user level, for user or green threads, or by the kernel, for kernel or native threads.  User threads are supported above the kernel and are managed without kernel support, whereas kernel threads are supported and managed directly by the operating system.&lt;br /&gt;
&lt;br /&gt;
==Multi-threading Models==&lt;br /&gt;
There are three common multithreading models&lt;br /&gt;
&lt;br /&gt;
===One-to-One===&lt;br /&gt;
This model maps each user-thread to a kernel thread.  It provides more concurrency than the many-to-one model by allowing another thread to run when a thread makes a blocking system call.  It also allows multiple threads to run in parallel on multiprocessors.  The main disadvantage of this model is the overhead of creating each kernel thread for each user thread.  This burdens the performance of an application and limits the number of threads supported by the system.&lt;br /&gt;
&lt;br /&gt;
===Many-to-One===&lt;br /&gt;
This model maps many user-level threads to one kernel thread.  It is the model used by green threads.  Green threads are scheduled by a Virtual Machine instead of natively by the OS. They emulate multithreaded environments without relying on any native OS capabilities. These user-level threads are lightweight and very efficient.  They are an easy way to achieve parallelism in a program.   An application can have as many user-level threads as it needs, but true concurrency is not achieved because the kernel can schedule only one thread at a time. The developers can create as many user threads as necessary.  However, there are two main disadvantages:&lt;br /&gt;
1)	If a thread makes a blocking system call, the entire process will block.&lt;br /&gt;
2)	If you are running on a multi-core machine, the multiple threads are unable to run in parallel.&lt;br /&gt;
&lt;br /&gt;
===Many-to-Many===&lt;br /&gt;
This model multiplexes many user-level threads to a smaller or equal number of kernel threads.  This model has the best of both worlds.  Developers can create as many user threads as they need.  When a user thread performs a blocking system call, the kernel can schedule another thread for execution and the kernel threads can run in parallel on multi-core systems.&lt;br /&gt;
&lt;br /&gt;
==Benefits of Multi-threading==&lt;br /&gt;
===Resource sharing===&lt;br /&gt;
Memory, code and process resource sharing - allocating memory and resources for process creation is costly and time consuming.  It is more economical to create threads than new processes.  Applications can benefit by having several different threads of activity within the same address space.&lt;br /&gt;
&lt;br /&gt;
===Responsiveness===&lt;br /&gt;
Multithreading an interactive application may allow a program to continue running, even if part of it is blocked doing IO or performing a lengthy operation, thereby increasing responsiveness to the user.  A web browser might have one thread display images or text while another thread retrieves data from the network.  A busy web server may have many clients concurrently accessing it.  If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time.&lt;br /&gt;
&lt;br /&gt;
==Potential Problems of Multi-threading==&lt;br /&gt;
Many threaded programs have shared resources that must be accessed by more than one thread.  These programs must implement a form of mutual exclusion to ensure that only one of the threads can access the resource at a time.  These shared resources must execute in code called critical sections.  These critical sections must be protected by either hardware or software means.&lt;br /&gt;
&lt;br /&gt;
=Java Threads=&lt;br /&gt;
The Java programming language has a thread library for creating and managing threads at the user-level.  The Java virtual machine (JVM) manages the mapping of the user threads to the operating system kernel threads.  The particular mapping model that is used depends on the operating system on which the Java program is running.  Java’s Thread Scheduler monitors all the threads running in Java programs.  It decides which threads to run at any given time and when to switch between threads to run based on the thread’s priority with higher running threads running before lower priority threads.  The Java scheduler uses either preemptive or non-preemptive scheduling based on the operating system on which it is running.  With preemptive scheduling, each thread is given a constant period of time to run, after which time the thread will be suspended() to allow the next thread to resume() running.  With non-preemptive scheduling, the running thread is allowed to run until the thread completes or until it issues a yield() to allow other threads to run while it waits for some other processing to occur.  &lt;br /&gt;
A Java thread can be created either by having your Java class extend the Java Thread class or by having your Java class implement the Runnable interface and coding a run() method.  The two options are shown in Figures 1 and 2.   The preferred method for creating a thread is by implementing the Runnable interface.  It is more flexible and useful in complex applications.   Java does not support multiple inheritance, but a class may implement multiple interfaces.  By using the interface method, the Client class is open to inherit another class, if the need arose in the future.&lt;br /&gt;
  &lt;br /&gt;
'''Figure 1: Client Extends Thread Class'''&lt;br /&gt;
        &lt;br /&gt;
    public class Client extends Thread {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Server {&lt;br /&gt;
        public static void main(String args[]){&lt;br /&gt;
            Thread runner = new Client();&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 2: Client Implements Runnable Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
   &lt;br /&gt;
    public class Server {&lt;br /&gt;
    &lt;br /&gt;
        public static void main(String args[]) {&lt;br /&gt;
            Thread runner = new Thread(new Client());&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
If the main Java thread wants to wait for any threads it creates to finish their run() method, the thread method join() can be executed.  The join() method is useful in situations where the creating thread can continue only after a worker thread has completed.  Java threads can be asynchronously terminated using the stop() method.  However, this method has been deprecated and its used is discouraged.  The preferred cancellation technique is to have the target thread periodically check whether it should terminate by using the interrupt() method.&lt;br /&gt;
&lt;br /&gt;
==States of Java Threads==&lt;br /&gt;
===New===&lt;br /&gt;
A thread is in this state when the thread object is first created with the new() method.&lt;br /&gt;
===Runnable===&lt;br /&gt;
Calling the start() method allocates memory for the new thread in the JVM and calls the run() method for the thread object.&lt;br /&gt;
===Blocked===&lt;br /&gt;
A thread becomes blocked if it performs a blocking statement, such as doing I/O or if it invokes a sleep() method.&lt;br /&gt;
===Dead===&lt;br /&gt;
A thread moves to the dead state when its run() method terminates.&lt;br /&gt;
&lt;br /&gt;
==Mutual Exclusion==&lt;br /&gt;
The Java language implements mutual exclusion in a couple of ways.  There exists a MutualExclusion interface.  The Client class can implement this interface and code the methods, enteringCriticalSection() and leavingCriticalSection(), as shown in Figure 3.  The yield() method tells the Thread Scheduler to allow another thread to run.  &lt;br /&gt;
&lt;br /&gt;
'''Figure 3: Client Implements MutualExclusion Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements MutualExclusion{&lt;br /&gt;
    &lt;br /&gt;
        public Client(){&lt;br /&gt;
            flag0 = false; flag1 = false; turn = TURN_0;&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void enteringCriticalSection(int t) {&lt;br /&gt;
            int other = 1 - t;&lt;br /&gt;
            &lt;br /&gt;
            if (t == 0) {&lt;br /&gt;
                flag0 = true; turn = other;&lt;br /&gt;
                while ((flag1 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             } else {&lt;br /&gt;
                flag1 = true; turn = other;&lt;br /&gt;
     	        while ((flag0 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void leavingCriticalSection(int t) {&lt;br /&gt;
            if(t == 0) flag0 = false;&lt;br /&gt;
            else   flag1 = false;&lt;br /&gt;
        }&lt;br /&gt;
        private volatile int turn, boolean flag0, flag1;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
An alternative method of handling mutual exclusion is to code a synchronization tool called a semaphore.  A semaphore is variable that is accessed only through two standard operations: acquire() and release().  The semaphore is acquired, then the critical section of an object is entered and after the critical code completes, the semaphore is released.  An example of this code is in Figure 4.&lt;br /&gt;
&lt;br /&gt;
'''Figure 4: Client Has Semaphore'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
    &lt;br /&gt;
        public Client (Semaphore sem) {&lt;br /&gt;
            this.sem = sem;&lt;br /&gt;
        }&lt;br /&gt;
       &lt;br /&gt;
        public void run() {&lt;br /&gt;
            sem.acquire();&lt;br /&gt;
            System.out.println(&amp;quot;Entering critical section&amp;quot;);&lt;br /&gt;
            SleepUtilities.nap(3);&lt;br /&gt;
            System.out.println(&amp;quot;Leaving critical section&amp;quot;);&lt;br /&gt;
            sem.release();&lt;br /&gt;
        }&lt;br /&gt;
        private Semaphore sem;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Ruby Threads=&lt;br /&gt;
At the present time the Ruby programming language just supports green threads.  These are totally implemented within the Ruby interpreter.  The threads, as well as the thread scheduler run on the same single operating system thread.  Ruby can support thread methods, such as stop() and kill(), that are not advised for kernel threads.  However, Ruby threads suffer from the drawbacks of non-native threads.  They can only run on one processor in a multiprocessor environment.  It is possible for a single thread to cause the whole process to deadlock, if poorly designed.  The worse problem with Ruby threads is with I/O, especially network access, since it has the potential to block a process for a long time.  This problem is solvable by using non-blocking I/O.  However, one problem that is not solvable using non-blocking I/O, is the DNS lookup system call.  Ruby solves this problem with their resolv library, which was written specifically to address the threading issue with the standard OS DNA lookup mechanism.  See Figure 5 for an example of the code that handles this issue.  Despite some of the green thread concerns, for most situations, the benefits of efficiency can far outweigh the disadvantages.&lt;br /&gt;
&lt;br /&gt;
'''Figure 5: Ruby DNS Lookup Implementation'''&lt;br /&gt;
    &lt;br /&gt;
    require ‘socket’&lt;br /&gt;
    require ‘resolv-replace’&lt;br /&gt;
    count = 0&lt;br /&gt;
    Thread.critical = true&lt;br /&gt;
    thread = Thread.new { Thread.pass; loop { count += 1; } } IPSocket.getaddress(www.ruby-lang.org) &lt;br /&gt;
    count&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A Ruby thread is created using Thread.new() {block}.  The arguments given in the new() method are passed to the block code that the thread executes.  See Figure 6 for an example of creating a Ruby thread.  The Ruby pass() method is analogous to the Java yield() method.  It tells the thread scheduler to pass execution to another thread.  Ruby has a join() method that performs the same functionality as the Java join().  There are run() and wakeup() methods that wake up a sleeping threads, either giving it control or indicating that it is ready to be scheduled. &lt;br /&gt;
&lt;br /&gt;
'''Figure 6: Creating Ruby Threads'''&lt;br /&gt;
&lt;br /&gt;
    threads = []&lt;br /&gt;
    4.times do |number|&lt;br /&gt;
        threads &amp;lt;&amp;lt; Thread.new(number) do |i|&lt;br /&gt;
            print “#{i}\n”    &lt;br /&gt;
        end &lt;br /&gt;
    end&lt;br /&gt;
    threads.each { |t| t.join }  &lt;br /&gt;
&lt;br /&gt;
==States of Ruby Threads==&lt;br /&gt;
===Run===&lt;br /&gt;
The thread is executing.&lt;br /&gt;
===Sleep===&lt;br /&gt;
The thread is sleeping or waiting on I/O.&lt;br /&gt;
===Aborting===&lt;br /&gt;
The thread is aborting (has been killed).&lt;br /&gt;
===False===&lt;br /&gt;
The thread has terminated normally.&lt;br /&gt;
===Nil===&lt;br /&gt;
The thread has terminated with an exception.&lt;br /&gt;
&lt;br /&gt;
==Mutual Exclusion==&lt;br /&gt;
The best way to handle mutual exclusion in Ruby is with the Monitor class.  A monitor has a synchronization() method that prevent access to a resource by another thread while one is execution in that method.  Figure 7 shows an example of how this can be used.   &lt;br /&gt;
&lt;br /&gt;
'''Figure 7: Ruby Monitor'''&lt;br /&gt;
&lt;br /&gt;
    require 'monitor'&lt;br /&gt;
        class Counter &amp;lt; Monitor&lt;br /&gt;
            attr_reader :count&lt;br /&gt;
        &lt;br /&gt;
            def initialize&lt;br /&gt;
                @count = 0&lt;br /&gt;
                super&lt;br /&gt;
            end&lt;br /&gt;
 &lt;br /&gt;
            def tick&lt;br /&gt;
                synchronize do&lt;br /&gt;
                @count += 1&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    c = Counter.new&lt;br /&gt;
    t1 = Thread.new { 10000.times {  c.tick } } &lt;br /&gt;
    t2 = Thread.new { 10000.times {  c.tick } }&lt;br /&gt;
    t1.join; t2.join&lt;br /&gt;
    c.count&lt;br /&gt;
&lt;br /&gt;
=Java vs Ruby Threads=&lt;br /&gt;
Java thread initialization is more involved than Ruby thread initialization. Ruby threads also have the advantage of a “quick and dirty” thread creation, since it only takes couple of lines of code.  A Ruby thread shares all global, instance and local variables that are in existence at the time the thread starts. A Java thread can share these variables, as well, depending on how the thread was created.  If the client thread class uses inheritance, any variables needed are passed along when creating the thread. If the thread is created through the interface, the variables can be shared as long as the class has been initialized and the variables in use. &lt;br /&gt;
	&lt;br /&gt;
Ruby’s green threads are completely portable, as they don’t rely on the OS. But, on a multi-core processor, native thread implementations can assign work to multiple processors while green threads cannot. In this environment native threads have a huge advantage as more work is done by the native threads.&lt;br /&gt;
&lt;br /&gt;
==Java and Ruby Methods Comparison==&lt;br /&gt;
&lt;br /&gt;
'''Table 1 lists thread actions and Java and Ruby’s equivalent methods of achieving them.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table1.jpg]]&lt;br /&gt;
&lt;br /&gt;
'''Table 2 lists thread actions available in Java, but Ruby doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table2.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Table 3 lists thread actions available in Ruby, but Java doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table3.jpg]]&lt;br /&gt;
&lt;br /&gt;
There are many similarities between the Java and Ruby Thread classes, as shown with the equivalent methods in Table 1.  But, as you can see, there are also many methods in Java that Ruby doesn't support and vice versa. Some methods like activeCount(), where it returns the number of active threads, are trivial, but there is a group of methods existing in both Java and Ruby that the other doesn't support. For Java, it is exception handling with getting/setting exceptions, while in Ruby, it is more thread control. Ruby has exception methods, but they are geared more toward events prior to the exception, like making sure all threads abort when exception starts and firing an exception to destroy threads. Java is more about setting the exceptions and getting them to change accordingly. So the Java Thread class has a little bit more exception handling than Ruby.&lt;br /&gt;
	&lt;br /&gt;
Ruby has more thread control for the programmer such as pausing, terminating, aborting and resuming threads. Java did have these functions, but they all have been deprecated because, although they give the user more control, they also can cause deadlock problems. So it is a tradeoff between more thread control and less chance for deadlocks to happen. Java does use interrupt to &amp;quot;pause&amp;quot; the thread as opposed to actually pausing the thread as in Ruby. Also, Java threads &amp;quot;sleep&amp;quot; differently than Ruby threads.  Java sleeps are timed, while Ruby's sleep just stops the thread indefinitely, until it gets woken up by &amp;quot;thr.wakeup&amp;quot;. As you can see Ruby's thread methods are more flexible, but potentially dangerous than Java’s.&lt;br /&gt;
&lt;br /&gt;
Basically, Java and Ruby both have similar thread functionalities.  In some respects, Java is simpler by reducing user error, while Ruby gives the programmer more power and perhaps more headaches. If user wants more control, then Ruby threading is great, but for simplicity Java is better.  The main distinction between Ruby threads and Java threads are that currently Ruby just supports green threads (as did Java 1.1) and Java has support for kernel threads.  Currently, there is no clear “winner” between native and green threads in a uni-processor system, but Java threads definitely have the edge over Ruby in a multi-processor environment.&lt;br /&gt;
Ruby is moving from green threads to kernel threads in Ruby 1.9 or 2.0, which are still development releases.  YARV has been integrated as the new Ruby VM.  YARV will give Ruby kernel thread support.  Detailed discussions of this change are at the following links:&lt;br /&gt;
http://www.infoq.com/news/2007/05/ruby-threading-futures&lt;br /&gt;
http://expressica.com/2008/04/26/new-in-ruby-19-threads/&lt;br /&gt;
&lt;br /&gt;
==Java vs. Ruby Thread Efficiency==&lt;br /&gt;
In order to test the efficiency of Java and Ruby threads two programs were written in each language.  The first one reads in the contents of five text files, one for each of five threads, searches for a given word in each and counts each occurrence of the word.  This count is added to a total count for all five files.  Each file is passed to its own thread to run.  The main thread has the total count, which is updated using mutual exclusion techniques in each language.  The second program was modified from the first.  Instead of searching for words in files, a string was passed to each thread. The times it took each to run each program depended on the size of the files, to a small extent and on the programming language to a larger extent.  The results are recorded in Table 4.  The file versions of these programs are given in Figures 8 and 9.  With the small file, the Ruby code ran about as fast as the Java code.  With the large file, the Java code ran five times faster than Ruby.  This is evidence that when doing file I/O, Java's native threads are much more efficient.  The string versions of these programs are not included in this Wiki.  Both the Java code and the Ruby code processed the strings in approximately the same about of time.  I had expected the Ruby code to outperform Java with this version.  &lt;br /&gt;
&lt;br /&gt;
{| border=&amp;quot;1&amp;quot;&lt;br /&gt;
|+ Table 4: WordCounts Running Times&lt;br /&gt;
|- &lt;br /&gt;
! File Sizes&lt;br /&gt;
! Ruby Times&lt;br /&gt;
! Java Times&lt;br /&gt;
|-&lt;br /&gt;
| 10KB&lt;br /&gt;
| 16 millisecs&lt;br /&gt;
| 15 millisecs&lt;br /&gt;
|-&lt;br /&gt;
| 80KB&lt;br /&gt;
| 119 millisecs&lt;br /&gt;
| 20 millisecs&lt;br /&gt;
|-&lt;br /&gt;
! String Sizes&lt;br /&gt;
! Ruby Times&lt;br /&gt;
! Java Times&lt;br /&gt;
|-&lt;br /&gt;
| 10KB&lt;br /&gt;
| 15 millisecs&lt;br /&gt;
| 16 millisecs&lt;br /&gt;
|-&lt;br /&gt;
| 60KB&lt;br /&gt;
| 20 millisecs&lt;br /&gt;
| 22 millisecs&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
'''Figure 8: Java Word Counts Code'''&lt;br /&gt;
    public class WordCounts {&lt;br /&gt;
        protected static int wordCount;&lt;br /&gt;
        &lt;br /&gt;
        private class Semaphore {&lt;br /&gt;
            private int mutex;  &lt;br /&gt;
      &lt;br /&gt;
            public Semaphore () {&lt;br /&gt;
                mutex = 1;&lt;br /&gt;
            }&lt;br /&gt;
       &lt;br /&gt;
            public synchronized void acquire() throws InterruptedException {&lt;br /&gt;
                while (mutex == 0) {&lt;br /&gt;
                   wait();&lt;br /&gt;
                }&lt;br /&gt;
                mutex--;&lt;br /&gt;
            }&lt;br /&gt;
            public synchronized void release() {&lt;br /&gt;
                mutex++;    &lt;br /&gt;
                notifyAll();&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
    &lt;br /&gt;
        private class WordCountsThread implements Runnable {&lt;br /&gt;
            private String word;&lt;br /&gt;
            private String file;        &lt;br /&gt;
            private int count;&lt;br /&gt;
            private Semaphore total; &lt;br /&gt;
                   &lt;br /&gt;
            public WordCountsThread (String word, String file, Semaphore total) {&lt;br /&gt;
                this.word  = word; &lt;br /&gt;
                this.file  = file;&lt;br /&gt;
                this.total = total;&lt;br /&gt;
                count      = 0;&lt;br /&gt;
            }    &lt;br /&gt;
     &lt;br /&gt;
            public void run(){&lt;br /&gt;
                readWordFile();&lt;br /&gt;
        &lt;br /&gt;
                try {&lt;br /&gt;
                    total.acquire();&lt;br /&gt;
                    wordCount = wordCount + count;&lt;br /&gt;
                    total.release();&lt;br /&gt;
                } catch (InterruptedException e) {&lt;br /&gt;
                    System.out.println (e);&lt;br /&gt;
                }&lt;br /&gt;
            }&lt;br /&gt;
     &lt;br /&gt;
            private void readWordFile (){&lt;br /&gt;
            }   // end method&lt;br /&gt;
        } //end inner class: WordCountThread&lt;br /&gt;
     &lt;br /&gt;
    &lt;br /&gt;
        public WordCounts (String searchWord, String [] files) {&lt;br /&gt;
            int numFiles = files.length;&lt;br /&gt;
            Semaphore total = new Semaphore();&lt;br /&gt;
            Thread [] threads = new Thread [numFiles];&lt;br /&gt;
          &lt;br /&gt;
            for (int i = 0; i &amp;lt; numFiles; i++ ) {&lt;br /&gt;
                threads[i] = new Thread (new WordCountsThread (searchWord,files[i], total));&lt;br /&gt;
            }&lt;br /&gt;
        &lt;br /&gt;
            for (int j = 0; j &amp;lt; numFiles; j++ ) {&lt;br /&gt;
                threads[j].start();&lt;br /&gt;
            }&lt;br /&gt;
        &lt;br /&gt;
            try {&lt;br /&gt;
                for (int i = 0; i &amp;lt; numFiles; i++ ) {&lt;br /&gt;
                    threads[i].join();&lt;br /&gt;
                } &lt;br /&gt;
            } catch (InterruptedException e) {&lt;br /&gt;
                System.out.println (e);&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void displayTotal (String searchWord) {&lt;br /&gt;
            System.out.println (&amp;quot;There are &amp;quot; + wordCount + &lt;br /&gt;
                            &amp;quot; total occurrences of &amp;quot; + searchWord);&lt;br /&gt;
        }&lt;br /&gt;
    &lt;br /&gt;
        public static void main (String [] args) {&lt;br /&gt;
            String [] files;              &lt;br /&gt;
            files = new String [5];   &lt;br /&gt;
            files [0] = &amp;quot;Player.java&amp;quot;;&lt;br /&gt;
            files [1] = &amp;quot;KingMove.java&amp;quot;;&lt;br /&gt;
            files [2] = &amp;quot;NodeDeque.java&amp;quot;;&lt;br /&gt;
            files [3] = &amp;quot;Position.java&amp;quot;;&lt;br /&gt;
            files [4] = &amp;quot;DoubleDigest.java&amp;quot;;&lt;br /&gt;
            String searchWord = &amp;quot;public&amp;quot;;&lt;br /&gt;
            long time = System.currentTimeMillis (), time_prev = time;&lt;br /&gt;
            WordCounts wc = new WordCounts (searchWord, files);&lt;br /&gt;
            wc.displayTotal (searchWord);&lt;br /&gt;
            time = System.currentTimeMillis ();&lt;br /&gt;
            System.out.println (&amp;quot;Diff &amp;quot; + (time - time_prev) + &amp;quot; msecs&amp;quot;);&lt;br /&gt;
            System.exit(0);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 9: Ruby Word Counts Code'''&lt;br /&gt;
&lt;br /&gt;
    class WordCounts &amp;lt; Monitor&lt;br /&gt;
        attr_reader :wordCount, :numFiles, :searchWord&lt;br /&gt;
      &lt;br /&gt;
        def initialize&lt;br /&gt;
            super&lt;br /&gt;
        end # initialize def&lt;br /&gt;
        &lt;br /&gt;
        def initVars(files, searchWord)&lt;br /&gt;
            @wordCount  = 0&lt;br /&gt;
            @files      = files&lt;br /&gt;
            @searchWord = searchWord&lt;br /&gt;
        end # initVars        &lt;br /&gt;
       &lt;br /&gt;
        def countWordsInFiles&lt;br /&gt;
             threads = []&lt;br /&gt;
   &lt;br /&gt;
            for fileToFetch in @files&lt;br /&gt;
                threads &amp;lt;&amp;lt; Thread.new(fileToFetch) do |file|&lt;br /&gt;
                count = readWordFile(file)&lt;br /&gt;
                updateTotal(count)&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
        threads.each {|t| t.join}&lt;br /&gt;
    end # countWordsInFiles &lt;br /&gt;
      &lt;br /&gt;
    def readWordFile(file)&lt;br /&gt;
        ...&lt;br /&gt;
        puts (&amp;quot;There are &amp;quot; + count.to_s + &amp;quot; occurrences of '&amp;quot; + @searchWord[0] + &amp;quot;' in &amp;quot; + file + &amp;quot;\n&amp;quot;)&lt;br /&gt;
        return count&lt;br /&gt;
    end # readWordFile def  &lt;br /&gt;
    &lt;br /&gt;
    def displayTotal&lt;br /&gt;
        puts (&amp;quot;\nThere are &amp;quot; + @wordCount.to_s + &amp;quot; total occurrences of '&amp;quot; + @searchWord[0] + &amp;quot;'&amp;quot;)&lt;br /&gt;
    end # displayTotal def &lt;br /&gt;
  &lt;br /&gt;
    def updateTotal (count)&lt;br /&gt;
        synchronize do&lt;br /&gt;
            @wordCount += count&lt;br /&gt;
        end&lt;br /&gt;
    end # updateTotal def&lt;br /&gt;
    end # WordCounts class def&lt;br /&gt;
    &lt;br /&gt;
    files = %w( Player.java KingMove.java NodeDeque.java Position.java DoubleDigest.java)&lt;br /&gt;
    searchWord = %w( public )&lt;br /&gt;
    wc = WordCounts.new&lt;br /&gt;
    wc.initVars(files, searchWord)&lt;br /&gt;
    ustart = Time.now.usec&lt;br /&gt;
    wc.countWordsInFiles&lt;br /&gt;
    wc.displayTotal&lt;br /&gt;
    t = Time.now&lt;br /&gt;
    uend = Time.now.usec&lt;br /&gt;
    puts (&amp;quot;Start: &amp;quot; + ustart.to_s + &amp;quot; usecs&amp;quot;)&lt;br /&gt;
    puts (&amp;quot;End: &amp;quot; + uend.to_s + &amp;quot; usecs&amp;quot;)&lt;br /&gt;
    puts (&amp;quot;diff: &amp;quot; + ((uend - ustart)/1000.0).to_s + &amp;quot; msecs&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
=References=&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12467</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12467"/>
		<updated>2008-06-06T17:54:01Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Java vs. Ruby Thread Efficiency */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
A thread is a basic unit of CPU utilization.  A traditional process has a single thread of control.  Many modern operating systems provide features enabling a process to contain multiple threads of control.  If the process has multiple threads of control, it can do more than one task at a time, such as, displaying graphics and reading keystrokes.  Threads are used mainly to run asynchronous tasks and pass the application’s tasks to an executor.  They are useful because they reduce the overall time of execution of programs. All threads belonging to the same process share its code section, data section and other operating system resources, such as open files and signals.  Thus multithreading is more efficient than having parallel processes running for the same program, which require a huge overhead.&lt;br /&gt;
&lt;br /&gt;
=Multi-threaded Programming= &lt;br /&gt;
Multithreading support for single processors works by giving each of the threads a “time slice” of the CPU, similar to the parallel execution of processes.  On multi-core machines, different threads can run on the different processors and the threads truly run simultaneously.   Support for threads may be provided at either the user level, for user or green threads, or by the kernel, for kernel or native threads.  User threads are supported above the kernel and are managed without kernel support, whereas kernel threads are supported and managed directly by the operating system.&lt;br /&gt;
&lt;br /&gt;
==Multi-threading Models==&lt;br /&gt;
There are three common multithreading models&lt;br /&gt;
&lt;br /&gt;
===One-to-One===&lt;br /&gt;
This model maps each user-thread to a kernel thread.  It provides more concurrency than the many-to-one model by allowing another thread to run when a thread makes a blocking system call.  It also allows multiple threads to run in parallel on multiprocessors.  The main disadvantage of this model is the overhead of creating each kernel thread for each user thread.  This burdens the performance of an application and limits the number of threads supported by the system.&lt;br /&gt;
&lt;br /&gt;
===Many-to-One===&lt;br /&gt;
This model maps many user-level threads to one kernel thread.  It is the model used by green threads.  Green threads are scheduled by a Virtual Machine instead of natively by the OS. They emulate multithreaded environments without relying on any native OS capabilities. These user-level threads are lightweight and very efficient.  They are an easy way to achieve parallelism in a program.   An application can have as many user-level threads as it needs, but true concurrency is not achieved because the kernel can schedule only one thread at a time. The developers can create as many user threads as necessary.  However, there are two main disadvantages:&lt;br /&gt;
1)	If a thread makes a blocking system call, the entire process will block.&lt;br /&gt;
2)	If you are running on a multi-core machine, the multiple threads are unable to run in parallel.&lt;br /&gt;
&lt;br /&gt;
===Many-to-Many===&lt;br /&gt;
This model multiplexes many user-level threads to a smaller or equal number of kernel threads.  This model has the best of both worlds.  Developers can create as many user threads as they need.  When a user thread performs a blocking system call, the kernel can schedule another thread for execution and the kernel threads can run in parallel on multi-core systems.&lt;br /&gt;
&lt;br /&gt;
==Benefits of Multi-threading==&lt;br /&gt;
===Resource sharing===&lt;br /&gt;
Memory, code and process resource sharing - allocating memory and resources for process creation is costly and time consuming.  It is more economical to create threads than new processes.  Applications can benefit by having several different threads of activity within the same address space.&lt;br /&gt;
&lt;br /&gt;
===Responsiveness===&lt;br /&gt;
Multithreading an interactive application may allow a program to continue running, even if part of it is blocked doing IO or performing a lengthy operation, thereby increasing responsiveness to the user.  A web browser might have one thread display images or text while another thread retrieves data from the network.  A busy web server may have many clients concurrently accessing it.  If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time.&lt;br /&gt;
&lt;br /&gt;
==Potential Problems of Multi-threading==&lt;br /&gt;
Many threaded programs have shared resources that must be accessed by more than one thread.  These programs must implement a form of mutual exclusion to ensure that only one of the threads can access the resource at a time.  These shared resources must execute in code called critical sections.  These critical sections must be protected by either hardware or software means.&lt;br /&gt;
&lt;br /&gt;
=Java Threads=&lt;br /&gt;
The Java programming language has a thread library for creating and managing threads at the user-level.  The Java virtual machine (JVM) manages the mapping of the user threads to the operating system kernel threads.  The particular mapping model that is used depends on the operating system on which the Java program is running.  Java’s Thread Scheduler monitors all the threads running in Java programs.  It decides which threads to run at any given time and when to switch between threads to run based on the thread’s priority with higher running threads running before lower priority threads.  The Java scheduler uses either preemptive or non-preemptive scheduling based on the operating system on which it is running.  With preemptive scheduling, each thread is given a constant period of time to run, after which time the thread will be suspended() to allow the next thread to resume() running.  With non-preemptive scheduling, the running thread is allowed to run until the thread completes or until it issues a yield() to allow other threads to run while it waits for some other processing to occur.  &lt;br /&gt;
A Java thread can be created either by having your Java class extend the Java Thread class or by having your Java class implement the Runnable interface and coding a run() method.  The two options are shown in Figures 1 and 2.   The preferred method for creating a thread is by implementing the Runnable interface.  It is more flexible and useful in complex applications.   Java does not support multiple inheritance, but a class may implement multiple interfaces.  By using the interface method, the Client class is open to inherit another class, if the need arose in the future.&lt;br /&gt;
  &lt;br /&gt;
'''Figure 1: Client Extends Thread Class'''&lt;br /&gt;
        &lt;br /&gt;
    public class Client extends Thread {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Server {&lt;br /&gt;
        public static void main(String args[]){&lt;br /&gt;
            Thread runner = new Client();&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 2: Client Implements Runnable Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
   &lt;br /&gt;
    public class Server {&lt;br /&gt;
    &lt;br /&gt;
        public static void main(String args[]) {&lt;br /&gt;
            Thread runner = new Thread(new Client());&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
If the main Java thread wants to wait for any threads it creates to finish their run() method, the thread method join() can be executed.  The join() method is useful in situations where the creating thread can continue only after a worker thread has completed.  Java threads can be asynchronously terminated using the stop() method.  However, this method has been deprecated and its used is discouraged.  The preferred cancellation technique is to have the target thread periodically check whether it should terminate by using the interrupt() method.&lt;br /&gt;
&lt;br /&gt;
==States of Java Threads==&lt;br /&gt;
===New===&lt;br /&gt;
A thread is in this state when the thread object is first created with the new() method.&lt;br /&gt;
===Runnable===&lt;br /&gt;
Calling the start() method allocates memory for the new thread in the JVM and calls the run() method for the thread object.&lt;br /&gt;
===Blocked===&lt;br /&gt;
A thread becomes blocked if it performs a blocking statement, such as doing I/O or if it invokes a sleep() method.&lt;br /&gt;
===Dead===&lt;br /&gt;
A thread moves to the dead state when its run() method terminates.&lt;br /&gt;
&lt;br /&gt;
==Mutual Exclusion==&lt;br /&gt;
The Java language implements mutual exclusion in a couple of ways.  There exists a MutualExclusion interface.  The Client class can implement this interface and code the methods, enteringCriticalSection() and leavingCriticalSection(), as shown in Figure 3.  The yield() method tells the Thread Scheduler to allow another thread to run.  &lt;br /&gt;
&lt;br /&gt;
'''Figure 3: Client Implements MutualExclusion Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements MutualExclusion{&lt;br /&gt;
    &lt;br /&gt;
        public Client(){&lt;br /&gt;
            flag0 = false; flag1 = false; turn = TURN_0;&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void enteringCriticalSection(int t) {&lt;br /&gt;
            int other = 1 - t;&lt;br /&gt;
            &lt;br /&gt;
            if (t == 0) {&lt;br /&gt;
                flag0 = true; turn = other;&lt;br /&gt;
                while ((flag1 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             } else {&lt;br /&gt;
                flag1 = true; turn = other;&lt;br /&gt;
     	        while ((flag0 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void leavingCriticalSection(int t) {&lt;br /&gt;
            if(t == 0) flag0 = false;&lt;br /&gt;
            else   flag1 = false;&lt;br /&gt;
        }&lt;br /&gt;
        private volatile int turn, boolean flag0, flag1;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
An alternative method of handling mutual exclusion is to code a synchronization tool called a semaphore.  A semaphore is variable that is accessed only through two standard operations: acquire() and release().  The semaphore is acquired, then the critical section of an object is entered and after the critical code completes, the semaphore is released.  An example of this code is in Figure 4.&lt;br /&gt;
&lt;br /&gt;
'''Figure 4: Client Has Semaphore'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
    &lt;br /&gt;
        public Client (Semaphore sem) {&lt;br /&gt;
            this.sem = sem;&lt;br /&gt;
        }&lt;br /&gt;
       &lt;br /&gt;
        public void run() {&lt;br /&gt;
            sem.acquire();&lt;br /&gt;
            System.out.println(&amp;quot;Entering critical section&amp;quot;);&lt;br /&gt;
            SleepUtilities.nap(3);&lt;br /&gt;
            System.out.println(&amp;quot;Leaving critical section&amp;quot;);&lt;br /&gt;
            sem.release();&lt;br /&gt;
        }&lt;br /&gt;
        private Semaphore sem;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Ruby Threads=&lt;br /&gt;
At the present time the Ruby programming language just supports green threads.  These are totally implemented within the Ruby interpreter.  The threads, as well as the thread scheduler run on the same single operating system thread.  Ruby can support thread methods, such as stop() and kill(), that are not advised for kernel threads.  However, Ruby threads suffer from the drawbacks of non-native threads.  They can only run on one processor in a multiprocessor environment.  It is possible for a single thread to cause the whole process to deadlock, if poorly designed.  The worse problem with Ruby threads is with I/O, especially network access, since it has the potential to block a process for a long time.  This problem is solvable by using non-blocking I/O.  However, one problem that is not solvable using non-blocking I/O, is the DNS lookup system call.  Ruby solves this problem with their resolv library, which was written specifically to address the threading issue with the standard OS DNA lookup mechanism.  See Figure 5 for an example of the code that handles this issue.  Despite some of the green thread concerns, for most situations, the benefits of efficiency can far outweigh the disadvantages.&lt;br /&gt;
&lt;br /&gt;
'''Figure 5: Ruby DNS Lookup Implementation'''&lt;br /&gt;
    &lt;br /&gt;
    require ‘socket’&lt;br /&gt;
    require ‘resolv-replace’&lt;br /&gt;
    count = 0&lt;br /&gt;
    Thread.critical = true&lt;br /&gt;
    thread = Thread.new { Thread.pass; loop { count += 1; } } IPSocket.getaddress(www.ruby-lang.org) &lt;br /&gt;
    count&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A Ruby thread is created using Thread.new() {block}.  The arguments given in the new() method are passed to the block code that the thread executes.  See Figure 6 for an example of creating a Ruby thread.  The Ruby pass() method is analogous to the Java yield() method.  It tells the thread scheduler to pass execution to another thread.  Ruby has a join() method that performs the same functionality as the Java join().  There are run() and wakeup() methods that wake up a sleeping threads, either giving it control or indicating that it is ready to be scheduled. &lt;br /&gt;
&lt;br /&gt;
'''Figure 6: Creating Ruby Threads'''&lt;br /&gt;
&lt;br /&gt;
    threads = []&lt;br /&gt;
    4.times do |number|&lt;br /&gt;
        threads &amp;lt;&amp;lt; Thread.new(number) do |i|&lt;br /&gt;
            print “#{i}\n”    &lt;br /&gt;
        end &lt;br /&gt;
    end&lt;br /&gt;
    threads.each { |t| t.join }  &lt;br /&gt;
&lt;br /&gt;
==States of Ruby Threads==&lt;br /&gt;
===Run===&lt;br /&gt;
The thread is executing.&lt;br /&gt;
===Sleep===&lt;br /&gt;
The thread is sleeping or waiting on I/O.&lt;br /&gt;
===Aborting===&lt;br /&gt;
The thread is aborting (has been killed).&lt;br /&gt;
===False===&lt;br /&gt;
The thread has terminated normally.&lt;br /&gt;
===Nil===&lt;br /&gt;
The thread has terminated with an exception.&lt;br /&gt;
&lt;br /&gt;
==Mutual Exclusion==&lt;br /&gt;
The best way to handle mutual exclusion in Ruby is with the Monitor class.  A monitor has a synchronization() method that prevent access to a resource by another thread while one is execution in that method.  Figure 7 shows an example of how this can be used.   &lt;br /&gt;
&lt;br /&gt;
'''Figure 7: Ruby Monitor'''&lt;br /&gt;
&lt;br /&gt;
    require 'monitor'&lt;br /&gt;
        class Counter &amp;lt; Monitor&lt;br /&gt;
            attr_reader :count&lt;br /&gt;
        &lt;br /&gt;
            def initialize&lt;br /&gt;
                @count = 0&lt;br /&gt;
                super&lt;br /&gt;
            end&lt;br /&gt;
 &lt;br /&gt;
            def tick&lt;br /&gt;
                synchronize do&lt;br /&gt;
                @count += 1&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    c = Counter.new&lt;br /&gt;
    t1 = Thread.new { 10000.times {  c.tick } } &lt;br /&gt;
    t2 = Thread.new { 10000.times {  c.tick } }&lt;br /&gt;
    t1.join; t2.join&lt;br /&gt;
    c.count&lt;br /&gt;
&lt;br /&gt;
=Java vs Ruby Threads=&lt;br /&gt;
Java thread initialization is more involved than Ruby thread initialization. Ruby threads also have the advantage of a “quick and dirty” thread creation, since it only takes couple of lines of code.  A Ruby thread shares all global, instance and local variables that are in existence at the time the thread starts. A Java thread can share these variables, as well, depending on how the thread was created.  If the client thread class uses inheritance, any variables needed are passed along when creating the thread. If the thread is created through the interface, the variables can be shared as long as the class has been initialized and the variables in use. &lt;br /&gt;
	&lt;br /&gt;
Ruby’s green threads are completely portable, as they don’t rely on the OS. But, on a multi-core processor, native thread implementations can assign work to multiple processors while green threads cannot. In this environment native threads have a huge advantage as more work is done by the native threads.&lt;br /&gt;
&lt;br /&gt;
==Java and Ruby Methods Comparison==&lt;br /&gt;
&lt;br /&gt;
'''Table 1 lists thread actions and Java and Ruby’s equivalent methods of achieving them.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table1.jpg]]&lt;br /&gt;
&lt;br /&gt;
'''Table 2 lists thread actions available in Java, but Ruby doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table2.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Table 3 lists thread actions available in Ruby, but Java doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table3.jpg]]&lt;br /&gt;
&lt;br /&gt;
There are many similarities between the Java and Ruby Thread classes, as shown with the equivalent methods in Table 1.  But, as you can see, there are also many methods in Java that Ruby doesn't support and vice versa. Some methods like activeCount(), where it returns the number of active threads, are trivial, but there is a group of methods existing in both Java and Ruby that the other doesn't support. For Java, it is exception handling with getting/setting exceptions, while in Ruby, it is more thread control. Ruby has exception methods, but they are geared more toward events prior to the exception, like making sure all threads abort when exception starts and firing an exception to destroy threads. Java is more about setting the exceptions and getting them to change accordingly. So the Java Thread class has a little bit more exception handling than Ruby.&lt;br /&gt;
	&lt;br /&gt;
Ruby has more thread control for the programmer such as pausing, terminating, aborting and resuming threads. Java did have these functions, but they all have been deprecated because, although they give the user more control, they also can cause deadlock problems. So it is a tradeoff between more thread control and less chance for deadlocks to happen. Java does use interrupt to &amp;quot;pause&amp;quot; the thread as opposed to actually pausing the thread as in Ruby. Also, Java threads &amp;quot;sleep&amp;quot; differently than Ruby threads.  Java sleeps are timed, while Ruby's sleep just stops the thread indefinitely, until it gets woken up by &amp;quot;thr.wakeup&amp;quot;. As you can see Ruby's thread methods are more flexible, but potentially dangerous than Java’s.&lt;br /&gt;
&lt;br /&gt;
Basically, Java and Ruby both have similar thread functionalities.  In some respects, Java is simpler by reducing user error, while Ruby gives the programmer more power and perhaps more headaches. If user wants more control, then Ruby threading is great, but for simplicity Java is better.  The main distinction between Ruby threads and Java threads are that currently Ruby just supports green threads (as did Java 1.1) and Java has support for kernel threads.  Currently, there is no clear “winner” between native and green threads in a uni-processor system, but Java threads definitely have the edge over Ruby in a multi-processor environment.&lt;br /&gt;
Ruby is moving from green threads to kernel threads in Ruby 1.9 or 2.0, which are still development releases.  YARV has been integrated as the new Ruby VM.  YARV will give Ruby kernel thread support.  Detailed discussions of this change are at the following links:&lt;br /&gt;
http://www.infoq.com/news/2007/05/ruby-threading-futures&lt;br /&gt;
http://expressica.com/2008/04/26/new-in-ruby-19-threads/&lt;br /&gt;
&lt;br /&gt;
==Java vs. Ruby Thread Efficiency==&lt;br /&gt;
In order to test the efficiency of Java and Ruby threads a program was written in each language that reads in the contents of five different text files and searches for a given word in each and counts each occurrence of the word.  This count is then added to a total count for all five files.  Each file is passed to its own thread to run.  The main thread has the total count, which is updated using mutual exclusion techniques in each language.  The times it took each to run depended on the size of the files.  The results are recorded in Table 4.  With very small files, the Ruby code ran twice as fast of the Java.  With the medium sized files the Java ran twice as fast as the Ruby code.  With the larger files, the Java code ran three times faster.  Certainly, the Java threads outperform the Ruby threads with I/O intensive code.  The Java code is in Figure 8 and the Ruby code is in Figure 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 8: Java Word Counts Code'''&lt;br /&gt;
    public class WordCounts {&lt;br /&gt;
        protected static int wordCount;&lt;br /&gt;
        &lt;br /&gt;
        private class Semaphore {&lt;br /&gt;
            private int mutex;  &lt;br /&gt;
      &lt;br /&gt;
            public Semaphore () {&lt;br /&gt;
                mutex = 1;&lt;br /&gt;
            }&lt;br /&gt;
       &lt;br /&gt;
            public synchronized void acquire() throws InterruptedException {&lt;br /&gt;
                while (mutex == 0) {&lt;br /&gt;
                   wait();&lt;br /&gt;
                }&lt;br /&gt;
                mutex--;&lt;br /&gt;
            }&lt;br /&gt;
            public synchronized void release() {&lt;br /&gt;
                mutex++;    &lt;br /&gt;
                notifyAll();&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
    &lt;br /&gt;
        private class WordCountsThread implements Runnable {&lt;br /&gt;
            private String word;&lt;br /&gt;
            private String file;        &lt;br /&gt;
            private int count;&lt;br /&gt;
            private Semaphore total; &lt;br /&gt;
                   &lt;br /&gt;
            public WordCountsThread (String word, String file, Semaphore total) {&lt;br /&gt;
                this.word  = word; &lt;br /&gt;
                this.file  = file;&lt;br /&gt;
                this.total = total;&lt;br /&gt;
                count      = 0;&lt;br /&gt;
            }    &lt;br /&gt;
     &lt;br /&gt;
            public void run(){&lt;br /&gt;
                readWordFile();&lt;br /&gt;
        &lt;br /&gt;
                try {&lt;br /&gt;
                    total.acquire();&lt;br /&gt;
                    wordCount = wordCount + count;&lt;br /&gt;
                    total.release();&lt;br /&gt;
                } catch (InterruptedException e) {&lt;br /&gt;
                    System.out.println (e);&lt;br /&gt;
                }&lt;br /&gt;
            }&lt;br /&gt;
     &lt;br /&gt;
            private void readWordFile (){&lt;br /&gt;
            }   // end method&lt;br /&gt;
        } //end inner class: WordCountThread&lt;br /&gt;
     &lt;br /&gt;
    &lt;br /&gt;
        public WordCounts (String searchWord, String [] files) {&lt;br /&gt;
            int numFiles = files.length;&lt;br /&gt;
            Semaphore total = new Semaphore();&lt;br /&gt;
            Thread [] threads = new Thread [numFiles];&lt;br /&gt;
          &lt;br /&gt;
            for (int i = 0; i &amp;lt; numFiles; i++ ) {&lt;br /&gt;
                threads[i] = new Thread (new WordCountsThread (searchWord,files[i], total));&lt;br /&gt;
            }&lt;br /&gt;
        &lt;br /&gt;
            for (int j = 0; j &amp;lt; numFiles; j++ ) {&lt;br /&gt;
                threads[j].start();&lt;br /&gt;
            }&lt;br /&gt;
        &lt;br /&gt;
            try {&lt;br /&gt;
                for (int i = 0; i &amp;lt; numFiles; i++ ) {&lt;br /&gt;
                    threads[i].join();&lt;br /&gt;
                } &lt;br /&gt;
            } catch (InterruptedException e) {&lt;br /&gt;
                System.out.println (e);&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void displayTotal (String searchWord) {&lt;br /&gt;
            System.out.println (&amp;quot;There are &amp;quot; + wordCount + &lt;br /&gt;
                            &amp;quot; total occurrences of &amp;quot; + searchWord);&lt;br /&gt;
        }&lt;br /&gt;
    &lt;br /&gt;
        public static void main (String [] args) {&lt;br /&gt;
            String [] files;              &lt;br /&gt;
            files = new String [5];   &lt;br /&gt;
            files [0] = &amp;quot;Player.java&amp;quot;;&lt;br /&gt;
            files [1] = &amp;quot;KingMove.java&amp;quot;;&lt;br /&gt;
            files [2] = &amp;quot;NodeDeque.java&amp;quot;;&lt;br /&gt;
            files [3] = &amp;quot;Position.java&amp;quot;;&lt;br /&gt;
            files [4] = &amp;quot;DoubleDigest.java&amp;quot;;&lt;br /&gt;
            String searchWord = &amp;quot;public&amp;quot;;&lt;br /&gt;
            long time = System.currentTimeMillis (), time_prev = time;&lt;br /&gt;
            WordCounts wc = new WordCounts (searchWord, files);&lt;br /&gt;
            wc.displayTotal (searchWord);&lt;br /&gt;
            time = System.currentTimeMillis ();&lt;br /&gt;
            System.out.println (&amp;quot;Diff &amp;quot; + (time - time_prev) + &amp;quot; msecs&amp;quot;);&lt;br /&gt;
            System.exit(0);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 9: Ruby Word Counts Code'''&lt;br /&gt;
&lt;br /&gt;
    class WordCounts &amp;lt; Monitor&lt;br /&gt;
        attr_reader :wordCount, :numFiles, :searchWord&lt;br /&gt;
      &lt;br /&gt;
        def initialize&lt;br /&gt;
            super&lt;br /&gt;
        end # initialize def&lt;br /&gt;
        &lt;br /&gt;
        def initVars(files, searchWord)&lt;br /&gt;
            @wordCount  = 0&lt;br /&gt;
            @files      = files&lt;br /&gt;
            @searchWord = searchWord&lt;br /&gt;
        end # initVars        &lt;br /&gt;
       &lt;br /&gt;
        def countWordsInFiles&lt;br /&gt;
             threads = []&lt;br /&gt;
   &lt;br /&gt;
            for fileToFetch in @files&lt;br /&gt;
                threads &amp;lt;&amp;lt; Thread.new(fileToFetch) do |file|&lt;br /&gt;
                count = readWordFile(file)&lt;br /&gt;
                updateTotal(count)&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
        threads.each {|t| t.join}&lt;br /&gt;
    end # countWordsInFiles &lt;br /&gt;
      &lt;br /&gt;
    def readWordFile(file)&lt;br /&gt;
        ...&lt;br /&gt;
        puts (&amp;quot;There are &amp;quot; + count.to_s + &amp;quot; occurrences of '&amp;quot; + @searchWord[0] + &amp;quot;' in &amp;quot; + file + &amp;quot;\n&amp;quot;)&lt;br /&gt;
        return count&lt;br /&gt;
    end # readWordFile def  &lt;br /&gt;
    &lt;br /&gt;
    def displayTotal&lt;br /&gt;
        puts (&amp;quot;\nThere are &amp;quot; + @wordCount.to_s + &amp;quot; total occurrences of '&amp;quot; + @searchWord[0] + &amp;quot;'&amp;quot;)&lt;br /&gt;
    end # displayTotal def &lt;br /&gt;
  &lt;br /&gt;
    def updateTotal (count)&lt;br /&gt;
        synchronize do&lt;br /&gt;
            @wordCount += count&lt;br /&gt;
        end&lt;br /&gt;
    end # updateTotal def&lt;br /&gt;
    end # WordCounts class def&lt;br /&gt;
    &lt;br /&gt;
    files = %w( Player.java KingMove.java NodeDeque.java Position.java DoubleDigest.java)&lt;br /&gt;
    searchWord = %w( public )&lt;br /&gt;
    wc = WordCounts.new&lt;br /&gt;
    wc.initVars(files, searchWord)&lt;br /&gt;
    ustart = Time.now.usec&lt;br /&gt;
    wc.countWordsInFiles&lt;br /&gt;
    wc.displayTotal&lt;br /&gt;
    t = Time.now&lt;br /&gt;
    uend = Time.now.usec&lt;br /&gt;
    puts (&amp;quot;Start: &amp;quot; + ustart.to_s + &amp;quot; usecs&amp;quot;)&lt;br /&gt;
    puts (&amp;quot;End: &amp;quot; + uend.to_s + &amp;quot; usecs&amp;quot;)&lt;br /&gt;
    puts (&amp;quot;diff: &amp;quot; + ((uend - ustart)/1000.0).to_s + &amp;quot; msecs&amp;quot;)&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12466</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12466"/>
		<updated>2008-06-06T17:50:36Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Java vs. Ruby Thread Efficiency */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
A thread is a basic unit of CPU utilization.  A traditional process has a single thread of control.  Many modern operating systems provide features enabling a process to contain multiple threads of control.  If the process has multiple threads of control, it can do more than one task at a time, such as, displaying graphics and reading keystrokes.  Threads are used mainly to run asynchronous tasks and pass the application’s tasks to an executor.  They are useful because they reduce the overall time of execution of programs. All threads belonging to the same process share its code section, data section and other operating system resources, such as open files and signals.  Thus multithreading is more efficient than having parallel processes running for the same program, which require a huge overhead.&lt;br /&gt;
&lt;br /&gt;
=Multi-threaded Programming= &lt;br /&gt;
Multithreading support for single processors works by giving each of the threads a “time slice” of the CPU, similar to the parallel execution of processes.  On multi-core machines, different threads can run on the different processors and the threads truly run simultaneously.   Support for threads may be provided at either the user level, for user or green threads, or by the kernel, for kernel or native threads.  User threads are supported above the kernel and are managed without kernel support, whereas kernel threads are supported and managed directly by the operating system.&lt;br /&gt;
&lt;br /&gt;
==Multi-threading Models==&lt;br /&gt;
There are three common multithreading models&lt;br /&gt;
&lt;br /&gt;
===One-to-One===&lt;br /&gt;
This model maps each user-thread to a kernel thread.  It provides more concurrency than the many-to-one model by allowing another thread to run when a thread makes a blocking system call.  It also allows multiple threads to run in parallel on multiprocessors.  The main disadvantage of this model is the overhead of creating each kernel thread for each user thread.  This burdens the performance of an application and limits the number of threads supported by the system.&lt;br /&gt;
&lt;br /&gt;
===Many-to-One===&lt;br /&gt;
This model maps many user-level threads to one kernel thread.  It is the model used by green threads.  Green threads are scheduled by a Virtual Machine instead of natively by the OS. They emulate multithreaded environments without relying on any native OS capabilities. These user-level threads are lightweight and very efficient.  They are an easy way to achieve parallelism in a program.   An application can have as many user-level threads as it needs, but true concurrency is not achieved because the kernel can schedule only one thread at a time. The developers can create as many user threads as necessary.  However, there are two main disadvantages:&lt;br /&gt;
1)	If a thread makes a blocking system call, the entire process will block.&lt;br /&gt;
2)	If you are running on a multi-core machine, the multiple threads are unable to run in parallel.&lt;br /&gt;
&lt;br /&gt;
===Many-to-Many===&lt;br /&gt;
This model multiplexes many user-level threads to a smaller or equal number of kernel threads.  This model has the best of both worlds.  Developers can create as many user threads as they need.  When a user thread performs a blocking system call, the kernel can schedule another thread for execution and the kernel threads can run in parallel on multi-core systems.&lt;br /&gt;
&lt;br /&gt;
==Benefits of Multi-threading==&lt;br /&gt;
===Resource sharing===&lt;br /&gt;
Memory, code and process resource sharing - allocating memory and resources for process creation is costly and time consuming.  It is more economical to create threads than new processes.  Applications can benefit by having several different threads of activity within the same address space.&lt;br /&gt;
&lt;br /&gt;
===Responsiveness===&lt;br /&gt;
Multithreading an interactive application may allow a program to continue running, even if part of it is blocked doing IO or performing a lengthy operation, thereby increasing responsiveness to the user.  A web browser might have one thread display images or text while another thread retrieves data from the network.  A busy web server may have many clients concurrently accessing it.  If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time.&lt;br /&gt;
&lt;br /&gt;
==Potential Problems of Multi-threading==&lt;br /&gt;
Many threaded programs have shared resources that must be accessed by more than one thread.  These programs must implement a form of mutual exclusion to ensure that only one of the threads can access the resource at a time.  These shared resources must execute in code called critical sections.  These critical sections must be protected by either hardware or software means.&lt;br /&gt;
&lt;br /&gt;
=Java Threads=&lt;br /&gt;
The Java programming language has a thread library for creating and managing threads at the user-level.  The Java virtual machine (JVM) manages the mapping of the user threads to the operating system kernel threads.  The particular mapping model that is used depends on the operating system on which the Java program is running.  Java’s Thread Scheduler monitors all the threads running in Java programs.  It decides which threads to run at any given time and when to switch between threads to run based on the thread’s priority with higher running threads running before lower priority threads.  The Java scheduler uses either preemptive or non-preemptive scheduling based on the operating system on which it is running.  With preemptive scheduling, each thread is given a constant period of time to run, after which time the thread will be suspended() to allow the next thread to resume() running.  With non-preemptive scheduling, the running thread is allowed to run until the thread completes or until it issues a yield() to allow other threads to run while it waits for some other processing to occur.  &lt;br /&gt;
A Java thread can be created either by having your Java class extend the Java Thread class or by having your Java class implement the Runnable interface and coding a run() method.  The two options are shown in Figures 1 and 2.   The preferred method for creating a thread is by implementing the Runnable interface.  It is more flexible and useful in complex applications.   Java does not support multiple inheritance, but a class may implement multiple interfaces.  By using the interface method, the Client class is open to inherit another class, if the need arose in the future.&lt;br /&gt;
  &lt;br /&gt;
'''Figure 1: Client Extends Thread Class'''&lt;br /&gt;
        &lt;br /&gt;
    public class Client extends Thread {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Server {&lt;br /&gt;
        public static void main(String args[]){&lt;br /&gt;
            Thread runner = new Client();&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 2: Client Implements Runnable Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
   &lt;br /&gt;
    public class Server {&lt;br /&gt;
    &lt;br /&gt;
        public static void main(String args[]) {&lt;br /&gt;
            Thread runner = new Thread(new Client());&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
If the main Java thread wants to wait for any threads it creates to finish their run() method, the thread method join() can be executed.  The join() method is useful in situations where the creating thread can continue only after a worker thread has completed.  Java threads can be asynchronously terminated using the stop() method.  However, this method has been deprecated and its used is discouraged.  The preferred cancellation technique is to have the target thread periodically check whether it should terminate by using the interrupt() method.&lt;br /&gt;
&lt;br /&gt;
==States of Java Threads==&lt;br /&gt;
===New===&lt;br /&gt;
A thread is in this state when the thread object is first created with the new() method.&lt;br /&gt;
===Runnable===&lt;br /&gt;
Calling the start() method allocates memory for the new thread in the JVM and calls the run() method for the thread object.&lt;br /&gt;
===Blocked===&lt;br /&gt;
A thread becomes blocked if it performs a blocking statement, such as doing I/O or if it invokes a sleep() method.&lt;br /&gt;
===Dead===&lt;br /&gt;
A thread moves to the dead state when its run() method terminates.&lt;br /&gt;
&lt;br /&gt;
==Mutual Exclusion==&lt;br /&gt;
The Java language implements mutual exclusion in a couple of ways.  There exists a MutualExclusion interface.  The Client class can implement this interface and code the methods, enteringCriticalSection() and leavingCriticalSection(), as shown in Figure 3.  The yield() method tells the Thread Scheduler to allow another thread to run.  &lt;br /&gt;
&lt;br /&gt;
'''Figure 3: Client Implements MutualExclusion Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements MutualExclusion{&lt;br /&gt;
    &lt;br /&gt;
        public Client(){&lt;br /&gt;
            flag0 = false; flag1 = false; turn = TURN_0;&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void enteringCriticalSection(int t) {&lt;br /&gt;
            int other = 1 - t;&lt;br /&gt;
            &lt;br /&gt;
            if (t == 0) {&lt;br /&gt;
                flag0 = true; turn = other;&lt;br /&gt;
                while ((flag1 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             } else {&lt;br /&gt;
                flag1 = true; turn = other;&lt;br /&gt;
     	        while ((flag0 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void leavingCriticalSection(int t) {&lt;br /&gt;
            if(t == 0) flag0 = false;&lt;br /&gt;
            else   flag1 = false;&lt;br /&gt;
        }&lt;br /&gt;
        private volatile int turn, boolean flag0, flag1;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
An alternative method of handling mutual exclusion is to code a synchronization tool called a semaphore.  A semaphore is variable that is accessed only through two standard operations: acquire() and release().  The semaphore is acquired, then the critical section of an object is entered and after the critical code completes, the semaphore is released.  An example of this code is in Figure 4.&lt;br /&gt;
&lt;br /&gt;
'''Figure 4: Client Has Semaphore'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
    &lt;br /&gt;
        public Client (Semaphore sem) {&lt;br /&gt;
            this.sem = sem;&lt;br /&gt;
        }&lt;br /&gt;
       &lt;br /&gt;
        public void run() {&lt;br /&gt;
            sem.acquire();&lt;br /&gt;
            System.out.println(&amp;quot;Entering critical section&amp;quot;);&lt;br /&gt;
            SleepUtilities.nap(3);&lt;br /&gt;
            System.out.println(&amp;quot;Leaving critical section&amp;quot;);&lt;br /&gt;
            sem.release();&lt;br /&gt;
        }&lt;br /&gt;
        private Semaphore sem;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Ruby Threads=&lt;br /&gt;
At the present time the Ruby programming language just supports green threads.  These are totally implemented within the Ruby interpreter.  The threads, as well as the thread scheduler run on the same single operating system thread.  Ruby can support thread methods, such as stop() and kill(), that are not advised for kernel threads.  However, Ruby threads suffer from the drawbacks of non-native threads.  They can only run on one processor in a multiprocessor environment.  It is possible for a single thread to cause the whole process to deadlock, if poorly designed.  The worse problem with Ruby threads is with I/O, especially network access, since it has the potential to block a process for a long time.  This problem is solvable by using non-blocking I/O.  However, one problem that is not solvable using non-blocking I/O, is the DNS lookup system call.  Ruby solves this problem with their resolv library, which was written specifically to address the threading issue with the standard OS DNA lookup mechanism.  See Figure 5 for an example of the code that handles this issue.  Despite some of the green thread concerns, for most situations, the benefits of efficiency can far outweigh the disadvantages.&lt;br /&gt;
&lt;br /&gt;
'''Figure 5: Ruby DNS Lookup Implementation'''&lt;br /&gt;
    &lt;br /&gt;
    require ‘socket’&lt;br /&gt;
    require ‘resolv-replace’&lt;br /&gt;
    count = 0&lt;br /&gt;
    Thread.critical = true&lt;br /&gt;
    thread = Thread.new { Thread.pass; loop { count += 1; } } IPSocket.getaddress(www.ruby-lang.org) &lt;br /&gt;
    count&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A Ruby thread is created using Thread.new() {block}.  The arguments given in the new() method are passed to the block code that the thread executes.  See Figure 6 for an example of creating a Ruby thread.  The Ruby pass() method is analogous to the Java yield() method.  It tells the thread scheduler to pass execution to another thread.  Ruby has a join() method that performs the same functionality as the Java join().  There are run() and wakeup() methods that wake up a sleeping threads, either giving it control or indicating that it is ready to be scheduled. &lt;br /&gt;
&lt;br /&gt;
'''Figure 6: Creating Ruby Threads'''&lt;br /&gt;
&lt;br /&gt;
    threads = []&lt;br /&gt;
    4.times do |number|&lt;br /&gt;
        threads &amp;lt;&amp;lt; Thread.new(number) do |i|&lt;br /&gt;
            print “#{i}\n”    &lt;br /&gt;
        end &lt;br /&gt;
    end&lt;br /&gt;
    threads.each { |t| t.join }  &lt;br /&gt;
&lt;br /&gt;
==States of Ruby Threads==&lt;br /&gt;
===Run===&lt;br /&gt;
The thread is executing.&lt;br /&gt;
===Sleep===&lt;br /&gt;
The thread is sleeping or waiting on I/O.&lt;br /&gt;
===Aborting===&lt;br /&gt;
The thread is aborting (has been killed).&lt;br /&gt;
===False===&lt;br /&gt;
The thread has terminated normally.&lt;br /&gt;
===Nil===&lt;br /&gt;
The thread has terminated with an exception.&lt;br /&gt;
&lt;br /&gt;
==Mutual Exclusion==&lt;br /&gt;
The best way to handle mutual exclusion in Ruby is with the Monitor class.  A monitor has a synchronization() method that prevent access to a resource by another thread while one is execution in that method.  Figure 7 shows an example of how this can be used.   &lt;br /&gt;
&lt;br /&gt;
'''Figure 7: Ruby Monitor'''&lt;br /&gt;
&lt;br /&gt;
    require 'monitor'&lt;br /&gt;
        class Counter &amp;lt; Monitor&lt;br /&gt;
            attr_reader :count&lt;br /&gt;
        &lt;br /&gt;
            def initialize&lt;br /&gt;
                @count = 0&lt;br /&gt;
                super&lt;br /&gt;
            end&lt;br /&gt;
 &lt;br /&gt;
            def tick&lt;br /&gt;
                synchronize do&lt;br /&gt;
                @count += 1&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    c = Counter.new&lt;br /&gt;
    t1 = Thread.new { 10000.times {  c.tick } } &lt;br /&gt;
    t2 = Thread.new { 10000.times {  c.tick } }&lt;br /&gt;
    t1.join; t2.join&lt;br /&gt;
    c.count&lt;br /&gt;
&lt;br /&gt;
=Java vs Ruby Threads=&lt;br /&gt;
Java thread initialization is more involved than Ruby thread initialization. Ruby threads also have the advantage of a “quick and dirty” thread creation, since it only takes couple of lines of code.  A Ruby thread shares all global, instance and local variables that are in existence at the time the thread starts. A Java thread can share these variables, as well, depending on how the thread was created.  If the client thread class uses inheritance, any variables needed are passed along when creating the thread. If the thread is created through the interface, the variables can be shared as long as the class has been initialized and the variables in use. &lt;br /&gt;
	&lt;br /&gt;
Ruby’s green threads are completely portable, as they don’t rely on the OS. But, on a multi-core processor, native thread implementations can assign work to multiple processors while green threads cannot. In this environment native threads have a huge advantage as more work is done by the native threads.&lt;br /&gt;
&lt;br /&gt;
==Java and Ruby Methods Comparison==&lt;br /&gt;
&lt;br /&gt;
'''Table 1 lists thread actions and Java and Ruby’s equivalent methods of achieving them.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table1.jpg]]&lt;br /&gt;
&lt;br /&gt;
'''Table 2 lists thread actions available in Java, but Ruby doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table2.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Table 3 lists thread actions available in Ruby, but Java doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table3.jpg]]&lt;br /&gt;
&lt;br /&gt;
There are many similarities between the Java and Ruby Thread classes, as shown with the equivalent methods in Table 1.  But, as you can see, there are also many methods in Java that Ruby doesn't support and vice versa. Some methods like activeCount(), where it returns the number of active threads, are trivial, but there is a group of methods existing in both Java and Ruby that the other doesn't support. For Java, it is exception handling with getting/setting exceptions, while in Ruby, it is more thread control. Ruby has exception methods, but they are geared more toward events prior to the exception, like making sure all threads abort when exception starts and firing an exception to destroy threads. Java is more about setting the exceptions and getting them to change accordingly. So the Java Thread class has a little bit more exception handling than Ruby.&lt;br /&gt;
	&lt;br /&gt;
Ruby has more thread control for the programmer such as pausing, terminating, aborting and resuming threads. Java did have these functions, but they all have been deprecated because, although they give the user more control, they also can cause deadlock problems. So it is a tradeoff between more thread control and less chance for deadlocks to happen. Java does use interrupt to &amp;quot;pause&amp;quot; the thread as opposed to actually pausing the thread as in Ruby. Also, Java threads &amp;quot;sleep&amp;quot; differently than Ruby threads.  Java sleeps are timed, while Ruby's sleep just stops the thread indefinitely, until it gets woken up by &amp;quot;thr.wakeup&amp;quot;. As you can see Ruby's thread methods are more flexible, but potentially dangerous than Java’s.&lt;br /&gt;
&lt;br /&gt;
Basically, Java and Ruby both have similar thread functionalities.  In some respects, Java is simpler by reducing user error, while Ruby gives the programmer more power and perhaps more headaches. If user wants more control, then Ruby threading is great, but for simplicity Java is better.  The main distinction between Ruby threads and Java threads are that currently Ruby just supports green threads (as did Java 1.1) and Java has support for kernel threads.  Currently, there is no clear “winner” between native and green threads in a uni-processor system, but Java threads definitely have the edge over Ruby in a multi-processor environment.&lt;br /&gt;
Ruby is moving from green threads to kernel threads in Ruby 1.9 or 2.0, which are still development releases.  YARV has been integrated as the new Ruby VM.  YARV will give Ruby kernel thread support.  Detailed discussions of this change are at the following links:&lt;br /&gt;
http://www.infoq.com/news/2007/05/ruby-threading-futures&lt;br /&gt;
http://expressica.com/2008/04/26/new-in-ruby-19-threads/&lt;br /&gt;
&lt;br /&gt;
==Java vs. Ruby Thread Efficiency==&lt;br /&gt;
In order to test the efficiency of Java and Ruby threads a program was written in each language that reads in the contents of five different text files and searches for a given word in each and counts each occurrence of the word.  This count is then added to a total count for all five files.  Each file is passed to its own thread to run.  The main thread has the total count, which is updated using mutual exclusion techniques in each language.  The times it took each to run depended on the size of the files.  The results are recorded in Table 4.  With very small files, the Ruby code ran twice as fast of the Java.  With the medium sized files the Java ran twice as fast as the Ruby code.  With the larger files, the Java code ran three times faster.  Certainly, the Java threads outperform the Ruby threads with I/O intensive code.  The Java code is in Figure 8 and the Ruby code is in Figure 9.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 8: Java Word Counts Code'''&lt;br /&gt;
    public class WordCounts {&lt;br /&gt;
        protected static int wordCount;&lt;br /&gt;
        &lt;br /&gt;
        private class Semaphore {&lt;br /&gt;
            private int mutex;  &lt;br /&gt;
      &lt;br /&gt;
            public Semaphore () {&lt;br /&gt;
                mutex = 1;&lt;br /&gt;
            }&lt;br /&gt;
       &lt;br /&gt;
            public synchronized void acquire() throws InterruptedException {&lt;br /&gt;
                while (mutex == 0) {&lt;br /&gt;
                   wait();&lt;br /&gt;
                }&lt;br /&gt;
                mutex--;&lt;br /&gt;
            }&lt;br /&gt;
            public synchronized void release() {&lt;br /&gt;
                mutex++;    &lt;br /&gt;
                notifyAll();&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
    &lt;br /&gt;
        private class WordCountsThread implements Runnable {&lt;br /&gt;
            private String word;&lt;br /&gt;
            private String file;        &lt;br /&gt;
            private int count;&lt;br /&gt;
            private Semaphore total; &lt;br /&gt;
                   &lt;br /&gt;
            public WordCountsThread (String word, String file, Semaphore total) {&lt;br /&gt;
                this.word  = word; &lt;br /&gt;
                this.file  = file;&lt;br /&gt;
                this.total = total;&lt;br /&gt;
                count      = 0;&lt;br /&gt;
            }    &lt;br /&gt;
     &lt;br /&gt;
            public void run(){&lt;br /&gt;
                readWordFile();&lt;br /&gt;
        &lt;br /&gt;
                try {&lt;br /&gt;
                    total.acquire();&lt;br /&gt;
                    wordCount = wordCount + count;&lt;br /&gt;
                    total.release();&lt;br /&gt;
                } catch (InterruptedException e) {&lt;br /&gt;
                    System.out.println (e);&lt;br /&gt;
                }&lt;br /&gt;
            }&lt;br /&gt;
     &lt;br /&gt;
            private void readWordFile (){&lt;br /&gt;
            }   // end method&lt;br /&gt;
        } //end inner class: WordCountThread&lt;br /&gt;
     &lt;br /&gt;
    &lt;br /&gt;
        public WordCounts (String searchWord, String [] files) {&lt;br /&gt;
            int numFiles = files.length;&lt;br /&gt;
            Semaphore total = new Semaphore();&lt;br /&gt;
            Thread [] threads = new Thread [numFiles];&lt;br /&gt;
          &lt;br /&gt;
            for (int i = 0; i &amp;lt; numFiles; i++ ) {&lt;br /&gt;
                threads[i] = new Thread (new WordCountsThread (searchWord,files[i], total));&lt;br /&gt;
            }&lt;br /&gt;
        &lt;br /&gt;
            for (int j = 0; j &amp;lt; numFiles; j++ ) {&lt;br /&gt;
                threads[j].start();&lt;br /&gt;
            }&lt;br /&gt;
        &lt;br /&gt;
            try {&lt;br /&gt;
                for (int i = 0; i &amp;lt; numFiles; i++ ) {&lt;br /&gt;
                    threads[i].join();&lt;br /&gt;
                } &lt;br /&gt;
            } catch (InterruptedException e) {&lt;br /&gt;
                System.out.println (e);&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void displayTotal (String searchWord) {&lt;br /&gt;
            System.out.println (&amp;quot;There are &amp;quot; + wordCount + &lt;br /&gt;
                            &amp;quot; total occurrences of &amp;quot; + searchWord);&lt;br /&gt;
        }&lt;br /&gt;
    &lt;br /&gt;
        public static void main (String [] args) {&lt;br /&gt;
            String [] files;              &lt;br /&gt;
            files = new String [5];   &lt;br /&gt;
            files [0] = &amp;quot;Player.java&amp;quot;;&lt;br /&gt;
            files [1] = &amp;quot;KingMove.java&amp;quot;;&lt;br /&gt;
            files [2] = &amp;quot;NodeDeque.java&amp;quot;;&lt;br /&gt;
            files [3] = &amp;quot;Position.java&amp;quot;;&lt;br /&gt;
            files [4] = &amp;quot;DoubleDigest.java&amp;quot;;&lt;br /&gt;
            String searchWord = &amp;quot;public&amp;quot;;&lt;br /&gt;
            long time = System.currentTimeMillis (), time_prev = time;&lt;br /&gt;
            WordCounts wc = new WordCounts (searchWord, files);&lt;br /&gt;
            wc.displayTotal (searchWord);&lt;br /&gt;
            time = System.currentTimeMillis ();&lt;br /&gt;
            System.out.println (&amp;quot;Diff &amp;quot; + (time - time_prev) + &amp;quot; msecs&amp;quot;);&lt;br /&gt;
            System.exit(0);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12458</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12458"/>
		<updated>2008-06-06T17:40:40Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
A thread is a basic unit of CPU utilization.  A traditional process has a single thread of control.  Many modern operating systems provide features enabling a process to contain multiple threads of control.  If the process has multiple threads of control, it can do more than one task at a time, such as, displaying graphics and reading keystrokes.  Threads are used mainly to run asynchronous tasks and pass the application’s tasks to an executor.  They are useful because they reduce the overall time of execution of programs. All threads belonging to the same process share its code section, data section and other operating system resources, such as open files and signals.  Thus multithreading is more efficient than having parallel processes running for the same program, which require a huge overhead.&lt;br /&gt;
&lt;br /&gt;
=Multi-threaded Programming= &lt;br /&gt;
Multithreading support for single processors works by giving each of the threads a “time slice” of the CPU, similar to the parallel execution of processes.  On multi-core machines, different threads can run on the different processors and the threads truly run simultaneously.   Support for threads may be provided at either the user level, for user or green threads, or by the kernel, for kernel or native threads.  User threads are supported above the kernel and are managed without kernel support, whereas kernel threads are supported and managed directly by the operating system.&lt;br /&gt;
&lt;br /&gt;
==Multi-threading Models==&lt;br /&gt;
There are three common multithreading models&lt;br /&gt;
&lt;br /&gt;
===One-to-One===&lt;br /&gt;
This model maps each user-thread to a kernel thread.  It provides more concurrency than the many-to-one model by allowing another thread to run when a thread makes a blocking system call.  It also allows multiple threads to run in parallel on multiprocessors.  The main disadvantage of this model is the overhead of creating each kernel thread for each user thread.  This burdens the performance of an application and limits the number of threads supported by the system.&lt;br /&gt;
&lt;br /&gt;
===Many-to-One===&lt;br /&gt;
This model maps many user-level threads to one kernel thread.  It is the model used by green threads.  Green threads are scheduled by a Virtual Machine instead of natively by the OS. They emulate multithreaded environments without relying on any native OS capabilities. These user-level threads are lightweight and very efficient.  They are an easy way to achieve parallelism in a program.   An application can have as many user-level threads as it needs, but true concurrency is not achieved because the kernel can schedule only one thread at a time. The developers can create as many user threads as necessary.  However, there are two main disadvantages:&lt;br /&gt;
1)	If a thread makes a blocking system call, the entire process will block.&lt;br /&gt;
2)	If you are running on a multi-core machine, the multiple threads are unable to run in parallel.&lt;br /&gt;
&lt;br /&gt;
===Many-to-Many===&lt;br /&gt;
This model multiplexes many user-level threads to a smaller or equal number of kernel threads.  This model has the best of both worlds.  Developers can create as many user threads as they need.  When a user thread performs a blocking system call, the kernel can schedule another thread for execution and the kernel threads can run in parallel on multi-core systems.&lt;br /&gt;
&lt;br /&gt;
==Benefits of Multi-threading==&lt;br /&gt;
===Resource sharing===&lt;br /&gt;
Memory, code and process resource sharing - allocating memory and resources for process creation is costly and time consuming.  It is more economical to create threads than new processes.  Applications can benefit by having several different threads of activity within the same address space.&lt;br /&gt;
&lt;br /&gt;
===Responsiveness===&lt;br /&gt;
Multithreading an interactive application may allow a program to continue running, even if part of it is blocked doing IO or performing a lengthy operation, thereby increasing responsiveness to the user.  A web browser might have one thread display images or text while another thread retrieves data from the network.  A busy web server may have many clients concurrently accessing it.  If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time.&lt;br /&gt;
&lt;br /&gt;
==Potential Problems of Multi-threading==&lt;br /&gt;
Many threaded programs have shared resources that must be accessed by more than one thread.  These programs must implement a form of mutual exclusion to ensure that only one of the threads can access the resource at a time.  These shared resources must execute in code called critical sections.  These critical sections must be protected by either hardware or software means.&lt;br /&gt;
&lt;br /&gt;
=Java Threads=&lt;br /&gt;
The Java programming language has a thread library for creating and managing threads at the user-level.  The Java virtual machine (JVM) manages the mapping of the user threads to the operating system kernel threads.  The particular mapping model that is used depends on the operating system on which the Java program is running.  Java’s Thread Scheduler monitors all the threads running in Java programs.  It decides which threads to run at any given time and when to switch between threads to run based on the thread’s priority with higher running threads running before lower priority threads.  The Java scheduler uses either preemptive or non-preemptive scheduling based on the operating system on which it is running.  With preemptive scheduling, each thread is given a constant period of time to run, after which time the thread will be suspended() to allow the next thread to resume() running.  With non-preemptive scheduling, the running thread is allowed to run until the thread completes or until it issues a yield() to allow other threads to run while it waits for some other processing to occur.  &lt;br /&gt;
A Java thread can be created either by having your Java class extend the Java Thread class or by having your Java class implement the Runnable interface and coding a run() method.  The two options are shown in Figures 1 and 2.   The preferred method for creating a thread is by implementing the Runnable interface.  It is more flexible and useful in complex applications.   Java does not support multiple inheritance, but a class may implement multiple interfaces.  By using the interface method, the Client class is open to inherit another class, if the need arose in the future.&lt;br /&gt;
  &lt;br /&gt;
'''Figure 1: Client Extends Thread Class'''&lt;br /&gt;
        &lt;br /&gt;
    public class Client extends Thread {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Server {&lt;br /&gt;
        public static void main(String args[]){&lt;br /&gt;
            Thread runner = new Client();&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 2: Client Implements Runnable Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
   &lt;br /&gt;
    public class Server {&lt;br /&gt;
    &lt;br /&gt;
        public static void main(String args[]) {&lt;br /&gt;
            Thread runner = new Thread(new Client());&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
If the main Java thread wants to wait for any threads it creates to finish their run() method, the thread method join() can be executed.  The join() method is useful in situations where the creating thread can continue only after a worker thread has completed.  Java threads can be asynchronously terminated using the stop() method.  However, this method has been deprecated and its used is discouraged.  The preferred cancellation technique is to have the target thread periodically check whether it should terminate by using the interrupt() method.&lt;br /&gt;
&lt;br /&gt;
==States of Java Threads==&lt;br /&gt;
===New===&lt;br /&gt;
A thread is in this state when the thread object is first created with the new() method.&lt;br /&gt;
===Runnable===&lt;br /&gt;
Calling the start() method allocates memory for the new thread in the JVM and calls the run() method for the thread object.&lt;br /&gt;
===Blocked===&lt;br /&gt;
A thread becomes blocked if it performs a blocking statement, such as doing I/O or if it invokes a sleep() method.&lt;br /&gt;
===Dead===&lt;br /&gt;
A thread moves to the dead state when its run() method terminates.&lt;br /&gt;
&lt;br /&gt;
==Mutual Exclusion==&lt;br /&gt;
The Java language implements mutual exclusion in a couple of ways.  There exists a MutualExclusion interface.  The Client class can implement this interface and code the methods, enteringCriticalSection() and leavingCriticalSection(), as shown in Figure 3.  The yield() method tells the Thread Scheduler to allow another thread to run.  &lt;br /&gt;
&lt;br /&gt;
'''Figure 3: Client Implements MutualExclusion Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements MutualExclusion{&lt;br /&gt;
    &lt;br /&gt;
        public Client(){&lt;br /&gt;
            flag0 = false; flag1 = false; turn = TURN_0;&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void enteringCriticalSection(int t) {&lt;br /&gt;
            int other = 1 - t;&lt;br /&gt;
            &lt;br /&gt;
            if (t == 0) {&lt;br /&gt;
                flag0 = true; turn = other;&lt;br /&gt;
                while ((flag1 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             } else {&lt;br /&gt;
                flag1 = true; turn = other;&lt;br /&gt;
     	        while ((flag0 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void leavingCriticalSection(int t) {&lt;br /&gt;
            if(t == 0) flag0 = false;&lt;br /&gt;
            else   flag1 = false;&lt;br /&gt;
        }&lt;br /&gt;
        private volatile int turn, boolean flag0, flag1;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
An alternative method of handling mutual exclusion is to code a synchronization tool called a semaphore.  A semaphore is variable that is accessed only through two standard operations: acquire() and release().  The semaphore is acquired, then the critical section of an object is entered and after the critical code completes, the semaphore is released.  An example of this code is in Figure 4.&lt;br /&gt;
&lt;br /&gt;
'''Figure 4: Client Has Semaphore'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
    &lt;br /&gt;
        public Client (Semaphore sem) {&lt;br /&gt;
            this.sem = sem;&lt;br /&gt;
        }&lt;br /&gt;
       &lt;br /&gt;
        public void run() {&lt;br /&gt;
            sem.acquire();&lt;br /&gt;
            System.out.println(&amp;quot;Entering critical section&amp;quot;);&lt;br /&gt;
            SleepUtilities.nap(3);&lt;br /&gt;
            System.out.println(&amp;quot;Leaving critical section&amp;quot;);&lt;br /&gt;
            sem.release();&lt;br /&gt;
        }&lt;br /&gt;
        private Semaphore sem;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Ruby Threads=&lt;br /&gt;
At the present time the Ruby programming language just supports green threads.  These are totally implemented within the Ruby interpreter.  The threads, as well as the thread scheduler run on the same single operating system thread.  Ruby can support thread methods, such as stop() and kill(), that are not advised for kernel threads.  However, Ruby threads suffer from the drawbacks of non-native threads.  They can only run on one processor in a multiprocessor environment.  It is possible for a single thread to cause the whole process to deadlock, if poorly designed.  The worse problem with Ruby threads is with I/O, especially network access, since it has the potential to block a process for a long time.  This problem is solvable by using non-blocking I/O.  However, one problem that is not solvable using non-blocking I/O, is the DNS lookup system call.  Ruby solves this problem with their resolv library, which was written specifically to address the threading issue with the standard OS DNA lookup mechanism.  See Figure 5 for an example of the code that handles this issue.  Despite some of the green thread concerns, for most situations, the benefits of efficiency can far outweigh the disadvantages.&lt;br /&gt;
&lt;br /&gt;
'''Figure 5: Ruby DNS Lookup Implementation'''&lt;br /&gt;
    &lt;br /&gt;
    require ‘socket’&lt;br /&gt;
    require ‘resolv-replace’&lt;br /&gt;
    count = 0&lt;br /&gt;
    Thread.critical = true&lt;br /&gt;
    thread = Thread.new { Thread.pass; loop { count += 1; } } IPSocket.getaddress(www.ruby-lang.org) &lt;br /&gt;
    count&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A Ruby thread is created using Thread.new() {block}.  The arguments given in the new() method are passed to the block code that the thread executes.  See Figure 6 for an example of creating a Ruby thread.  The Ruby pass() method is analogous to the Java yield() method.  It tells the thread scheduler to pass execution to another thread.  Ruby has a join() method that performs the same functionality as the Java join().  There are run() and wakeup() methods that wake up a sleeping threads, either giving it control or indicating that it is ready to be scheduled. &lt;br /&gt;
&lt;br /&gt;
'''Figure 6: Creating Ruby Threads'''&lt;br /&gt;
&lt;br /&gt;
    threads = []&lt;br /&gt;
    4.times do |number|&lt;br /&gt;
        threads &amp;lt;&amp;lt; Thread.new(number) do |i|&lt;br /&gt;
            print “#{i}\n”    &lt;br /&gt;
        end &lt;br /&gt;
    end&lt;br /&gt;
    threads.each { |t| t.join }  &lt;br /&gt;
&lt;br /&gt;
==States of Ruby Threads==&lt;br /&gt;
===Run===&lt;br /&gt;
The thread is executing.&lt;br /&gt;
===Sleep===&lt;br /&gt;
The thread is sleeping or waiting on I/O.&lt;br /&gt;
===Aborting===&lt;br /&gt;
The thread is aborting (has been killed).&lt;br /&gt;
===False===&lt;br /&gt;
The thread has terminated normally.&lt;br /&gt;
===Nil===&lt;br /&gt;
The thread has terminated with an exception.&lt;br /&gt;
&lt;br /&gt;
==Mutual Exclusion==&lt;br /&gt;
The best way to handle mutual exclusion in Ruby is with the Monitor class.  A monitor has a synchronization() method that prevent access to a resource by another thread while one is execution in that method.  Figure 7 shows an example of how this can be used.   &lt;br /&gt;
&lt;br /&gt;
'''Figure 7: Ruby Monitor'''&lt;br /&gt;
&lt;br /&gt;
    require 'monitor'&lt;br /&gt;
        class Counter &amp;lt; Monitor&lt;br /&gt;
            attr_reader :count&lt;br /&gt;
        &lt;br /&gt;
            def initialize&lt;br /&gt;
                @count = 0&lt;br /&gt;
                super&lt;br /&gt;
            end&lt;br /&gt;
 &lt;br /&gt;
            def tick&lt;br /&gt;
                synchronize do&lt;br /&gt;
                @count += 1&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    c = Counter.new&lt;br /&gt;
    t1 = Thread.new { 10000.times {  c.tick } } &lt;br /&gt;
    t2 = Thread.new { 10000.times {  c.tick } }&lt;br /&gt;
    t1.join; t2.join&lt;br /&gt;
    c.count&lt;br /&gt;
&lt;br /&gt;
=Java vs Ruby Threads=&lt;br /&gt;
Java thread initialization is more involved than Ruby thread initialization. Ruby threads also have the advantage of a “quick and dirty” thread creation, since it only takes couple of lines of code.  A Ruby thread shares all global, instance and local variables that are in existence at the time the thread starts. A Java thread can share these variables, as well, depending on how the thread was created.  If the client thread class uses inheritance, any variables needed are passed along when creating the thread. If the thread is created through the interface, the variables can be shared as long as the class has been initialized and the variables in use. &lt;br /&gt;
	&lt;br /&gt;
Ruby’s green threads are completely portable, as they don’t rely on the OS. But, on a multi-core processor, native thread implementations can assign work to multiple processors while green threads cannot. In this environment native threads have a huge advantage as more work is done by the native threads.&lt;br /&gt;
&lt;br /&gt;
==Java and Ruby Methods Comparison==&lt;br /&gt;
&lt;br /&gt;
'''Table 1 lists thread actions and Java and Ruby’s equivalent methods of achieving them.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table1.jpg]]&lt;br /&gt;
&lt;br /&gt;
'''Table 2 lists thread actions available in Java, but Ruby doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table2.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Table 3 lists thread actions available in Ruby, but Java doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table3.jpg]]&lt;br /&gt;
&lt;br /&gt;
There are many similarities between the Java and Ruby Thread classes, as shown with the equivalent methods in Table 1.  But, as you can see, there are also many methods in Java that Ruby doesn't support and vice versa. Some methods like activeCount(), where it returns the number of active threads, are trivial, but there is a group of methods existing in both Java and Ruby that the other doesn't support. For Java, it is exception handling with getting/setting exceptions, while in Ruby, it is more thread control. Ruby has exception methods, but they are geared more toward events prior to the exception, like making sure all threads abort when exception starts and firing an exception to destroy threads. Java is more about setting the exceptions and getting them to change accordingly. So the Java Thread class has a little bit more exception handling than Ruby.&lt;br /&gt;
	&lt;br /&gt;
Ruby has more thread control for the programmer such as pausing, terminating, aborting and resuming threads. Java did have these functions, but they all have been deprecated because, although they give the user more control, they also can cause deadlock problems. So it is a tradeoff between more thread control and less chance for deadlocks to happen. Java does use interrupt to &amp;quot;pause&amp;quot; the thread as opposed to actually pausing the thread as in Ruby. Also, Java threads &amp;quot;sleep&amp;quot; differently than Ruby threads.  Java sleeps are timed, while Ruby's sleep just stops the thread indefinitely, until it gets woken up by &amp;quot;thr.wakeup&amp;quot;. As you can see Ruby's thread methods are more flexible, but potentially dangerous than Java’s.&lt;br /&gt;
&lt;br /&gt;
Basically, Java and Ruby both have similar thread functionalities.  In some respects, Java is simpler by reducing user error, while Ruby gives the programmer more power and perhaps more headaches. If user wants more control, then Ruby threading is great, but for simplicity Java is better.  The main distinction between Ruby threads and Java threads are that currently Ruby just supports green threads (as did Java 1.1) and Java has support for kernel threads.  Currently, there is no clear “winner” between native and green threads in a uni-processor system, but Java threads definitely have the edge over Ruby in a multi-processor environment.&lt;br /&gt;
Ruby is moving from green threads to kernel threads in Ruby 1.9 or 2.0, which are still development releases.  YARV has been integrated as the new Ruby VM.  YARV will give Ruby kernel thread support.  Detailed discussions of this change are at the following links:&lt;br /&gt;
http://www.infoq.com/news/2007/05/ruby-threading-futures&lt;br /&gt;
http://expressica.com/2008/04/26/new-in-ruby-19-threads/&lt;br /&gt;
&lt;br /&gt;
==Java vs. Ruby Thread Efficiency==&lt;br /&gt;
In order to test the efficiency of Java and Ruby threads a program was written in each language that reads in the contents of five different text files and searches for a given word in each and counts each occurrence of the word.  This count is then added to a total count for all five files.  Each file is passed to its own thread to run.  The main thread has the total count, which is updated using mutual exclusion techniques in each language.  The times it took each to run depended on the size of the files.  The results are recorded in Table 4.  With very small files, the Ruby code ran twice as fast of the Java.  With the medium sized files the Java ran twice as fast as the Ruby code.  With the larger files, the Java code ran three times faster.  Certainly, the Java threads outperform the Ruby threads with I/O intensive code.  The Java code is in Figure 8 and the Ruby code is in Figure 9.&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12457</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12457"/>
		<updated>2008-06-06T17:39:19Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
A thread is a basic unit of CPU utilization.  A traditional process has a single thread of control.  Many modern operating systems provide features enabling a process to contain multiple threads of control.  If the process has multiple threads of control, it can do more than one task at a time, such as, displaying graphics and reading keystrokes.  Threads are used mainly to run asynchronous tasks and pass the application’s tasks to an executor.  They are useful because they reduce the overall time of execution of programs. All threads belonging to the same process share its code section, data section and other operating system resources, such as open files and signals.  Thus multithreading is more efficient than having parallel processes running for the same program, which require a huge overhead.&lt;br /&gt;
&lt;br /&gt;
=Multi-threaded programming= &lt;br /&gt;
Multithreading support for single processors works by giving each of the threads a “time slice” of the CPU, similar to the parallel execution of processes.  On multi-core machines, different threads can run on the different processors and the threads truly run simultaneously.   Support for threads may be provided at either the user level, for user or green threads, or by the kernel, for kernel or native threads.  User threads are supported above the kernel and are managed without kernel support, whereas kernel threads are supported and managed directly by the operating system.&lt;br /&gt;
&lt;br /&gt;
==Multi-threading models==&lt;br /&gt;
There are three common multithreading models&lt;br /&gt;
&lt;br /&gt;
===One-to-one===&lt;br /&gt;
This model maps each user-thread to a kernel thread.  It provides more concurrency than the many-to-one model by allowing another thread to run when a thread makes a blocking system call.  It also allows multiple threads to run in parallel on multiprocessors.  The main disadvantage of this model is the overhead of creating each kernel thread for each user thread.  This burdens the performance of an application and limits the number of threads supported by the system.&lt;br /&gt;
&lt;br /&gt;
===Many-to-one===&lt;br /&gt;
This model maps many user-level threads to one kernel thread.  It is the model used by green threads.  Green threads are scheduled by a Virtual Machine instead of natively by the OS. They emulate multithreaded environments without relying on any native OS capabilities. These user-level threads are lightweight and very efficient.  They are an easy way to achieve parallelism in a program.   An application can have as many user-level threads as it needs, but true concurrency is not achieved because the kernel can schedule only one thread at a time. The developers can create as many user threads as necessary.  However, there are two main disadvantages:&lt;br /&gt;
1)	If a thread makes a blocking system call, the entire process will block.&lt;br /&gt;
2)	If you are running on a multi-core machine, the multiple threads are unable to run in parallel.&lt;br /&gt;
&lt;br /&gt;
===Many-to-Many===&lt;br /&gt;
This model multiplexes many user-level threads to a smaller or equal number of kernel threads.  This model has the best of both worlds.  Developers can create as many user threads as they need.  When a user thread performs a blocking system call, the kernel can schedule another thread for execution and the kernel threads can run in parallel on multi-core systems.&lt;br /&gt;
&lt;br /&gt;
==Benefits of multi-threading==&lt;br /&gt;
===Resource sharing===&lt;br /&gt;
Memory, code and process resource sharing - allocating memory and resources for process creation is costly and time consuming.  It is more economical to create threads than new processes.  Applications can benefit by having several different threads of activity within the same address space.&lt;br /&gt;
&lt;br /&gt;
===Responsiveness===&lt;br /&gt;
Multithreading an interactive application may allow a program to continue running, even if part of it is blocked doing IO or performing a lengthy operation, thereby increasing responsiveness to the user.  A web browser might have one thread display images or text while another thread retrieves data from the network.  A busy web server may have many clients concurrently accessing it.  If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time.&lt;br /&gt;
&lt;br /&gt;
==Potential problems of multi-threading==&lt;br /&gt;
Many threaded programs have shared resources that must be accessed by more than one thread.  These programs must implement a form of mutual exclusion to ensure that only one of the threads can access the resource at a time.  These shared resources must execute in code called critical sections.  These critical sections must be protected by either hardware or software means.&lt;br /&gt;
&lt;br /&gt;
=Java threads=&lt;br /&gt;
The Java programming language has a thread library for creating and managing threads at the user-level.  The Java virtual machine (JVM) manages the mapping of the user threads to the operating system kernel threads.  The particular mapping model that is used depends on the operating system on which the Java program is running.  Java’s Thread Scheduler monitors all the threads running in Java programs.  It decides which threads to run at any given time and when to switch between threads to run based on the thread’s priority with higher running threads running before lower priority threads.  The Java scheduler uses either preemptive or non-preemptive scheduling based on the operating system on which it is running.  With preemptive scheduling, each thread is given a constant period of time to run, after which time the thread will be suspended() to allow the next thread to resume() running.  With non-preemptive scheduling, the running thread is allowed to run until the thread completes or until it issues a yield() to allow other threads to run while it waits for some other processing to occur.  &lt;br /&gt;
A Java thread can be created either by having your Java class extend the Java Thread class or by having your Java class implement the Runnable interface and coding a run() method.  The two options are shown in Figures 1 and 2.   The preferred method for creating a thread is by implementing the Runnable interface.  It is more flexible and useful in complex applications.   Java does not support multiple inheritance, but a class may implement multiple interfaces.  By using the interface method, the Client class is open to inherit another class, if the need arose in the future.&lt;br /&gt;
  &lt;br /&gt;
'''Figure 1: Client Extends Thread Class'''&lt;br /&gt;
        &lt;br /&gt;
    public class Client extends Thread {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Server {&lt;br /&gt;
        public static void main(String args[]){&lt;br /&gt;
            Thread runner = new Client();&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 2: Client Implements Runnable Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
   &lt;br /&gt;
    public class Server {&lt;br /&gt;
    &lt;br /&gt;
        public static void main(String args[]) {&lt;br /&gt;
            Thread runner = new Thread(new Client());&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
If the main Java thread wants to wait for any threads it creates to finish their run() method, the thread method join() can be executed.  The join() method is useful in situations where the creating thread can continue only after a worker thread has completed.  Java threads can be asynchronously terminated using the stop() method.  However, this method has been deprecated and its used is discouraged.  The preferred cancellation technique is to have the target thread periodically check whether it should terminate by using the interrupt() method.&lt;br /&gt;
&lt;br /&gt;
==States of Java threads==&lt;br /&gt;
===New===&lt;br /&gt;
A thread is in this state when the thread object is first created with the new() method.&lt;br /&gt;
===Runnable===&lt;br /&gt;
Calling the start() method allocates memory for the new thread in the JVM and calls the run() method for the thread object.&lt;br /&gt;
===Blocked===&lt;br /&gt;
A thread becomes blocked if it performs a blocking statement, such as doing I/O or if it invokes a sleep() method.&lt;br /&gt;
===Dead===&lt;br /&gt;
A thread moves to the dead state when its run() method terminates.&lt;br /&gt;
&lt;br /&gt;
==Mutual exclusion==&lt;br /&gt;
The Java language implements mutual exclusion in a couple of ways.  There exists a MutualExclusion interface.  The Client class can implement this interface and code the methods, enteringCriticalSection() and leavingCriticalSection(), as shown in Figure 3.  The yield() method tells the Thread Scheduler to allow another thread to run.  &lt;br /&gt;
&lt;br /&gt;
'''Figure 3: Client Implements MutualExclusion Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements MutualExclusion{&lt;br /&gt;
    &lt;br /&gt;
        public Client(){&lt;br /&gt;
            flag0 = false; flag1 = false; turn = TURN_0;&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void enteringCriticalSection(int t) {&lt;br /&gt;
            int other = 1 - t;&lt;br /&gt;
            &lt;br /&gt;
            if (t == 0) {&lt;br /&gt;
                flag0 = true; turn = other;&lt;br /&gt;
                while ((flag1 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             } else {&lt;br /&gt;
                flag1 = true; turn = other;&lt;br /&gt;
     	        while ((flag0 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void leavingCriticalSection(int t) {&lt;br /&gt;
            if(t == 0) flag0 = false;&lt;br /&gt;
            else   flag1 = false;&lt;br /&gt;
        }&lt;br /&gt;
        private volatile int turn, boolean flag0, flag1;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
An alternative method of handling mutual exclusion is to code a synchronization tool called a semaphore.  A semaphore is variable that is accessed only through two standard operations: acquire() and release().  The semaphore is acquired, then the critical section of an object is entered and after the critical code completes, the semaphore is released.  An example of this code is in Figure 4.&lt;br /&gt;
&lt;br /&gt;
'''Figure 4: Client Has Semaphore'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
    &lt;br /&gt;
        public Client (Semaphore sem) {&lt;br /&gt;
            this.sem = sem;&lt;br /&gt;
        }&lt;br /&gt;
       &lt;br /&gt;
        public void run() {&lt;br /&gt;
            sem.acquire();&lt;br /&gt;
            System.out.println(&amp;quot;Entering critical section&amp;quot;);&lt;br /&gt;
            SleepUtilities.nap(3);&lt;br /&gt;
            System.out.println(&amp;quot;Leaving critical section&amp;quot;);&lt;br /&gt;
            sem.release();&lt;br /&gt;
        }&lt;br /&gt;
        private Semaphore sem;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Ruby threads=&lt;br /&gt;
At the present time the Ruby programming language just supports green threads.  These are totally implemented within the Ruby interpreter.  The threads, as well as the thread scheduler run on the same single operating system thread.  Ruby can support thread methods, such as stop() and kill(), that are not advised for kernel threads.  However, Ruby threads suffer from the drawbacks of non-native threads.  They can only run on one processor in a multiprocessor environment.  It is possible for a single thread to cause the whole process to deadlock, if poorly designed.  The worse problem with Ruby threads is with I/O, especially network access, since it has the potential to block a process for a long time.  This problem is solvable by using non-blocking I/O.  However, one problem that is not solvable using non-blocking I/O, is the DNS lookup system call.  Ruby solves this problem with their resolv library, which was written specifically to address the threading issue with the standard OS DNA lookup mechanism.  See Figure 5 for an example of the code that handles this issue.  Despite some of the green thread concerns, for most situations, the benefits of efficiency can far outweigh the disadvantages.&lt;br /&gt;
&lt;br /&gt;
'''Figure 5: Ruby DNS Lookup Implementation'''&lt;br /&gt;
    &lt;br /&gt;
    require ‘socket’&lt;br /&gt;
    require ‘resolv-replace’&lt;br /&gt;
    count = 0&lt;br /&gt;
    Thread.critical = true&lt;br /&gt;
    thread = Thread.new { Thread.pass; loop { count += 1; } } IPSocket.getaddress(www.ruby-lang.org) &lt;br /&gt;
    count&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A Ruby thread is created using Thread.new() {block}.  The arguments given in the new() method are passed to the block code that the thread executes.  See Figure 6 for an example of creating a Ruby thread.  The Ruby pass() method is analogous to the Java yield() method.  It tells the thread scheduler to pass execution to another thread.  Ruby has a join() method that performs the same functionality as the Java join().  There are run() and wakeup() methods that wake up a sleeping threads, either giving it control or indicating that it is ready to be scheduled. &lt;br /&gt;
&lt;br /&gt;
'''Figure 6: Creating Ruby Threads'''&lt;br /&gt;
&lt;br /&gt;
    threads = []&lt;br /&gt;
    4.times do |number|&lt;br /&gt;
        threads &amp;lt;&amp;lt; Thread.new(number) do |i|&lt;br /&gt;
            print “#{i}\n”    &lt;br /&gt;
        end &lt;br /&gt;
    end&lt;br /&gt;
    threads.each { |t| t.join }  &lt;br /&gt;
&lt;br /&gt;
==States of Ruby threads==&lt;br /&gt;
===Run===&lt;br /&gt;
The thread is executing.&lt;br /&gt;
===Sleep===&lt;br /&gt;
The thread is sleeping or waiting on I/O.&lt;br /&gt;
===Aborting===&lt;br /&gt;
The thread is aborting (has been killed).&lt;br /&gt;
===False===&lt;br /&gt;
The thread has terminated normally.&lt;br /&gt;
===Nil===&lt;br /&gt;
The thread has terminated with an exception.&lt;br /&gt;
&lt;br /&gt;
==Mutual Exclusion==&lt;br /&gt;
The best way to handle mutual exclusion in Ruby is with the Monitor class.  A monitor has a synchronization() method that prevent access to a resource by another thread while one is execution in that method.  Figure 7 shows an example of how this can be used.   &lt;br /&gt;
&lt;br /&gt;
'''Figure 7: Ruby Monitor'''&lt;br /&gt;
&lt;br /&gt;
    require 'monitor'&lt;br /&gt;
        class Counter &amp;lt; Monitor&lt;br /&gt;
            attr_reader :count&lt;br /&gt;
        &lt;br /&gt;
            def initialize&lt;br /&gt;
                @count = 0&lt;br /&gt;
                super&lt;br /&gt;
            end&lt;br /&gt;
 &lt;br /&gt;
            def tick&lt;br /&gt;
                synchronize do&lt;br /&gt;
                @count += 1&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    c = Counter.new&lt;br /&gt;
    t1 = Thread.new { 10000.times {  c.tick } } &lt;br /&gt;
    t2 = Thread.new { 10000.times {  c.tick } }&lt;br /&gt;
    t1.join; t2.join&lt;br /&gt;
    c.count&lt;br /&gt;
&lt;br /&gt;
=Java vs Ruby threads=&lt;br /&gt;
Java thread initialization is more involved than Ruby thread initialization. Ruby threads also have the advantage of a “quick and dirty” thread creation, since it only takes couple of lines of code.  A Ruby thread shares all global, instance and local variables that are in existence at the time the thread starts. A Java thread can share these variables, as well, depending on how the thread was created.  If the client thread class uses inheritance, any variables needed are passed along when creating the thread. If the thread is created through the interface, the variables can be shared as long as the class has been initialized and the variables in use. &lt;br /&gt;
	&lt;br /&gt;
Ruby’s green threads are completely portable, as they don’t rely on the OS. But, on a multi-core processor, native thread implementations can assign work to multiple processors while green threads cannot. In this environment native threads have a huge advantage as more work is done by the native threads.&lt;br /&gt;
&lt;br /&gt;
==Java and Ruby methods comparison==&lt;br /&gt;
&lt;br /&gt;
'''Table 1 lists thread actions and Java and Ruby’s equivalent methods of achieving them.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table1.jpg]]&lt;br /&gt;
&lt;br /&gt;
'''Table 2 lists thread actions available in Java, but Ruby doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table2.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Table 3 lists thread actions available in Ruby, but Java doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table3.jpg]]&lt;br /&gt;
&lt;br /&gt;
There are many similarities between the Java and Ruby Thread classes, as shown with the equivalent methods in Table 1.  But, as you can see, there are also many methods in Java that Ruby doesn't support and vice versa. Some methods like activeCount(), where it returns the number of active threads, are trivial, but there is a group of methods existing in both Java and Ruby that the other doesn't support. For Java, it is exception handling with getting/setting exceptions, while in Ruby, it is more thread control. Ruby has exception methods, but they are geared more toward events prior to the exception, like making sure all threads abort when exception starts and firing an exception to destroy threads. Java is more about setting the exceptions and getting them to change accordingly. So the Java Thread class has a little bit more exception handling than Ruby.&lt;br /&gt;
	&lt;br /&gt;
Ruby has more thread control for the programmer such as pausing, terminating, aborting and resuming threads. Java did have these functions, but they all have been deprecated because, although they give the user more control, they also can cause deadlock problems. So it is a tradeoff between more thread control and less chance for deadlocks to happen. Java does use interrupt to &amp;quot;pause&amp;quot; the thread as opposed to actually pausing the thread as in Ruby. Also, Java threads &amp;quot;sleep&amp;quot; differently than Ruby threads.  Java sleeps are timed, while Ruby's sleep just stops the thread indefinitely, until it gets woken up by &amp;quot;thr.wakeup&amp;quot;. As you can see Ruby's thread methods are more flexible, but potentially dangerous than Java’s.&lt;br /&gt;
&lt;br /&gt;
Basically, Java and Ruby both have similar thread functionalities.  In some respects, Java is simpler by reducing user error, while Ruby gives the programmer more power and perhaps more headaches. If user wants more control, then Ruby threading is great, but for simplicity Java is better.  The main distinction between Ruby threads and Java threads are that currently Ruby just supports green threads (as did Java 1.1) and Java has support for kernel threads.  Currently, there is no clear “winner” between native and green threads in a uni-processor system, but Java threads definitely have the edge over Ruby in a multi-processor environment.&lt;br /&gt;
Ruby is moving from green threads to kernel threads in Ruby 1.9 or 2.0, which are still development releases.  YARV has been integrated as the new Ruby VM.  YARV will give Ruby kernel thread support.  Detailed discussions of this change are at the following links:&lt;br /&gt;
http://www.infoq.com/news/2007/05/ruby-threading-futures&lt;br /&gt;
http://expressica.com/2008/04/26/new-in-ruby-19-threads/&lt;br /&gt;
&lt;br /&gt;
==Java vs. Ruby Thread Efficiency==&lt;br /&gt;
In order to test the efficiency of Java and Ruby threads a program was written in each language that reads in the contents of five different text files and searches for a given word in each and counts each occurrence of the word.  This count is then added to a total count for all five files.  Each file is passed to its own thread to run.  The main thread has the total count, which is updated using mutual exclusion techniques in each language.  The times it took each to run depended on the size of the files.  The results are recorded in Table 4.  With very small files, the Ruby code ran twice as fast of the Java.  With the medium sized files the Java ran twice as fast as the Ruby code.  With the larger files, the Java code ran three times faster.  Certainly, the Java threads outperform the Ruby threads with I/O intensive code.  The Java code is in Figure 8 and the Ruby code is in Figure 9.&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12456</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12456"/>
		<updated>2008-06-06T17:38:23Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Java and Ruby methods comparison */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
A thread is a basic unit of CPU utilization.  A traditional process has a single thread of control.  Many modern operating systems provide features enabling a process to contain multiple threads of control.  If the process has multiple threads of control, it can do more than one task at a time, such as, displaying graphics and reading keystrokes.  Threads are used mainly to run asynchronous tasks and pass the application’s tasks to an executor.  They are useful because they reduce the overall time of execution of programs. All threads belonging to the same process share its code section, data section and other operating system resources, such as open files and signals.  Thus multithreading is more efficient than having parallel processes running for the same program, which require a huge overhead.&lt;br /&gt;
&lt;br /&gt;
=Multi-threaded programming= &lt;br /&gt;
Multithreading support for single processors works by giving each of the threads a “time slice” of the CPU, similar to the parallel execution of processes.  On multi-core machines, different threads can run on the different processors and the threads truly run simultaneously.   Support for threads may be provided at either the user level, for user or green threads, or by the kernel, for kernel or native threads.  User threads are supported above the kernel and are managed without kernel support, whereas kernel threads are supported and managed directly by the operating system.&lt;br /&gt;
&lt;br /&gt;
==Multi-threading models==&lt;br /&gt;
There are three common multithreading models&lt;br /&gt;
&lt;br /&gt;
===One-to-one===&lt;br /&gt;
This model maps each user-thread to a kernel thread.  It provides more concurrency than the many-to-one model by allowing another thread to run when a thread makes a blocking system call.  It also allows multiple threads to run in parallel on multiprocessors.  The main disadvantage of this model is the overhead of creating each kernel thread for each user thread.  This burdens the performance of an application and limits the number of threads supported by the system.&lt;br /&gt;
&lt;br /&gt;
===Many-to-one===&lt;br /&gt;
This model maps many user-level threads to one kernel thread.  It is the model used by green threads.  Green threads are scheduled by a Virtual Machine instead of natively by the OS. They emulate multithreaded environments without relying on any native OS capabilities. These user-level threads are lightweight and very efficient.  They are an easy way to achieve parallelism in a program.   An application can have as many user-level threads as it needs, but true concurrency is not achieved because the kernel can schedule only one thread at a time. The developers can create as many user threads as necessary.  However, there are two main disadvantages:&lt;br /&gt;
1)	If a thread makes a blocking system call, the entire process will block.&lt;br /&gt;
2)	If you are running on a multi-core machine, the multiple threads are unable to run in parallel.&lt;br /&gt;
&lt;br /&gt;
===Many-to-Many===&lt;br /&gt;
This model multiplexes many user-level threads to a smaller or equal number of kernel threads.  This model has the best of both worlds.  Developers can create as many user threads as they need.  When a user thread performs a blocking system call, the kernel can schedule another thread for execution and the kernel threads can run in parallel on multi-core systems.&lt;br /&gt;
&lt;br /&gt;
==Benefits of multi-threading==&lt;br /&gt;
===Resource sharing===&lt;br /&gt;
Memory, code and process resource sharing - allocating memory and resources for process creation is costly and time consuming.  It is more economical to create threads than new processes.  Applications can benefit by having several different threads of activity within the same address space.&lt;br /&gt;
&lt;br /&gt;
===Responsiveness===&lt;br /&gt;
Multithreading an interactive application may allow a program to continue running, even if part of it is blocked doing IO or performing a lengthy operation, thereby increasing responsiveness to the user.  A web browser might have one thread display images or text while another thread retrieves data from the network.  A busy web server may have many clients concurrently accessing it.  If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time.&lt;br /&gt;
&lt;br /&gt;
==Potential problems of multi-threading==&lt;br /&gt;
Many threaded programs have shared resources that must be accessed by more than one thread.  These programs must implement a form of mutual exclusion to ensure that only one of the threads can access the resource at a time.  These shared resources must execute in code called critical sections.  These critical sections must be protected by either hardware or software means.&lt;br /&gt;
&lt;br /&gt;
=Java threads=&lt;br /&gt;
The Java programming language has a thread library for creating and managing threads at the user-level.  The Java virtual machine (JVM) manages the mapping of the user threads to the operating system kernel threads.  The particular mapping model that is used depends on the operating system on which the Java program is running.  Java’s Thread Scheduler monitors all the threads running in Java programs.  It decides which threads to run at any given time and when to switch between threads to run based on the thread’s priority with higher running threads running before lower priority threads.  The Java scheduler uses either preemptive or non-preemptive scheduling based on the operating system on which it is running.  With preemptive scheduling, each thread is given a constant period of time to run, after which time the thread will be suspended() to allow the next thread to resume() running.  With non-preemptive scheduling, the running thread is allowed to run until the thread completes or until it issues a yield() to allow other threads to run while it waits for some other processing to occur.  &lt;br /&gt;
A Java thread can be created either by having your Java class extend the Java Thread class or by having your Java class implement the Runnable interface and coding a run() method.  The two options are shown in Figures 1 and 2.   The preferred method for creating a thread is by implementing the Runnable interface.  It is more flexible and useful in complex applications.   Java does not support multiple inheritance, but a class may implement multiple interfaces.  By using the interface method, the Client class is open to inherit another class, if the need arose in the future.&lt;br /&gt;
  &lt;br /&gt;
'''Figure 1: Client Extends Thread Class'''&lt;br /&gt;
        &lt;br /&gt;
    public class Client extends Thread {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Server {&lt;br /&gt;
        public static void main(String args[]){&lt;br /&gt;
            Thread runner = new Client();&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 2: Client Implements Runnable Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
   &lt;br /&gt;
    public class Server {&lt;br /&gt;
    &lt;br /&gt;
        public static void main(String args[]) {&lt;br /&gt;
            Thread runner = new Thread(new Client());&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
If the main Java thread wants to wait for any threads it creates to finish their run() method, the thread method join() can be executed.  The join() method is useful in situations where the creating thread can continue only after a worker thread has completed.  Java threads can be asynchronously terminated using the stop() method.  However, this method has been deprecated and its used is discouraged.  The preferred cancellation technique is to have the target thread periodically check whether it should terminate by using the interrupt() method.&lt;br /&gt;
&lt;br /&gt;
==States of Java threads==&lt;br /&gt;
===New===&lt;br /&gt;
A thread is in this state when the thread object is first created with the new() method.&lt;br /&gt;
===Runnable===&lt;br /&gt;
Calling the start() method allocates memory for the new thread in the JVM and calls the run() method for the thread object.&lt;br /&gt;
===Blocked===&lt;br /&gt;
A thread becomes blocked if it performs a blocking statement, such as doing I/O or if it invokes a sleep() method.&lt;br /&gt;
===Dead===&lt;br /&gt;
A thread moves to the dead state when its run() method terminates.&lt;br /&gt;
&lt;br /&gt;
==Mutual exclusion==&lt;br /&gt;
The Java language implements mutual exclusion in a couple of ways.  There exists a MutualExclusion interface.  The Client class can implement this interface and code the methods, enteringCriticalSection() and leavingCriticalSection(), as shown in Figure 3.  The yield() method tells the Thread Scheduler to allow another thread to run.  &lt;br /&gt;
&lt;br /&gt;
'''Figure 3: Client Implements MutualExclusion Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements MutualExclusion{&lt;br /&gt;
    &lt;br /&gt;
        public Client(){&lt;br /&gt;
            flag0 = false; flag1 = false; turn = TURN_0;&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void enteringCriticalSection(int t) {&lt;br /&gt;
            int other = 1 - t;&lt;br /&gt;
            &lt;br /&gt;
            if (t == 0) {&lt;br /&gt;
                flag0 = true; turn = other;&lt;br /&gt;
                while ((flag1 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             } else {&lt;br /&gt;
                flag1 = true; turn = other;&lt;br /&gt;
     	        while ((flag0 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void leavingCriticalSection(int t) {&lt;br /&gt;
            if(t == 0) flag0 = false;&lt;br /&gt;
            else   flag1 = false;&lt;br /&gt;
        }&lt;br /&gt;
        private volatile int turn, boolean flag0, flag1;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
An alternative method of handling mutual exclusion is to code a synchronization tool called a semaphore.  A semaphore is variable that is accessed only through two standard operations: acquire() and release().  The semaphore is acquired, then the critical section of an object is entered and after the critical code completes, the semaphore is released.  An example of this code is in Figure 4.&lt;br /&gt;
&lt;br /&gt;
'''Figure 4: Client Has Semaphore'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
    &lt;br /&gt;
        public Client (Semaphore sem) {&lt;br /&gt;
            this.sem = sem;&lt;br /&gt;
        }&lt;br /&gt;
       &lt;br /&gt;
        public void run() {&lt;br /&gt;
            sem.acquire();&lt;br /&gt;
            System.out.println(&amp;quot;Entering critical section&amp;quot;);&lt;br /&gt;
            SleepUtilities.nap(3);&lt;br /&gt;
            System.out.println(&amp;quot;Leaving critical section&amp;quot;);&lt;br /&gt;
            sem.release();&lt;br /&gt;
        }&lt;br /&gt;
        private Semaphore sem;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Ruby threads=&lt;br /&gt;
At the present time the Ruby programming language just supports green threads.  These are totally implemented within the Ruby interpreter.  The threads, as well as the thread scheduler run on the same single operating system thread.  Ruby can support thread methods, such as stop() and kill(), that are not advised for kernel threads.  However, Ruby threads suffer from the drawbacks of non-native threads.  They can only run on one processor in a multiprocessor environment.  It is possible for a single thread to cause the whole process to deadlock, if poorly designed.  The worse problem with Ruby threads is with I/O, especially network access, since it has the potential to block a process for a long time.  This problem is solvable by using non-blocking I/O.  However, one problem that is not solvable using non-blocking I/O, is the DNS lookup system call.  Ruby solves this problem with their resolv library, which was written specifically to address the threading issue with the standard OS DNA lookup mechanism.  See Figure 5 for an example of the code that handles this issue.  Despite some of the green thread concerns, for most situations, the benefits of efficiency can far outweigh the disadvantages.&lt;br /&gt;
&lt;br /&gt;
'''Figure 5: Ruby DNS Lookup Implementation'''&lt;br /&gt;
    &lt;br /&gt;
    require ‘socket’&lt;br /&gt;
    require ‘resolv-replace’&lt;br /&gt;
    count = 0&lt;br /&gt;
    Thread.critical = true&lt;br /&gt;
    thread = Thread.new { Thread.pass; loop { count += 1; } } IPSocket.getaddress(www.ruby-lang.org) &lt;br /&gt;
    count&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A Ruby thread is created using Thread.new() {block}.  The arguments given in the new() method are passed to the block code that the thread executes.  See Figure 6 for an example of creating a Ruby thread.  The Ruby pass() method is analogous to the Java yield() method.  It tells the thread scheduler to pass execution to another thread.  Ruby has a join() method that performs the same functionality as the Java join().  There are run() and wakeup() methods that wake up a sleeping threads, either giving it control or indicating that it is ready to be scheduled. &lt;br /&gt;
&lt;br /&gt;
'''Figure 6: Creating Ruby Threads'''&lt;br /&gt;
&lt;br /&gt;
    threads = []&lt;br /&gt;
    4.times do |number|&lt;br /&gt;
        threads &amp;lt;&amp;lt; Thread.new(number) do |i|&lt;br /&gt;
            print “#{i}\n”    &lt;br /&gt;
        end &lt;br /&gt;
    end&lt;br /&gt;
    threads.each { |t| t.join }  &lt;br /&gt;
&lt;br /&gt;
==States of Ruby threads==&lt;br /&gt;
===Run===&lt;br /&gt;
The thread is executing.&lt;br /&gt;
===Sleep===&lt;br /&gt;
The thread is sleeping or waiting on I/O.&lt;br /&gt;
===Aborting===&lt;br /&gt;
The thread is aborting (has been killed).&lt;br /&gt;
===False===&lt;br /&gt;
The thread has terminated normally.&lt;br /&gt;
===Nil===&lt;br /&gt;
The thread has terminated with an exception.&lt;br /&gt;
&lt;br /&gt;
==Mutual Exclusion==&lt;br /&gt;
The best way to handle mutual exclusion in Ruby is with the Monitor class.  A monitor has a synchronization() method that prevent access to a resource by another thread while one is execution in that method.  Figure 7 shows an example of how this can be used.   &lt;br /&gt;
&lt;br /&gt;
'''Figure 7: Ruby Monitor'''&lt;br /&gt;
&lt;br /&gt;
    require 'monitor'&lt;br /&gt;
        class Counter &amp;lt; Monitor&lt;br /&gt;
            attr_reader :count&lt;br /&gt;
        &lt;br /&gt;
            def initialize&lt;br /&gt;
                @count = 0&lt;br /&gt;
                super&lt;br /&gt;
            end&lt;br /&gt;
 &lt;br /&gt;
            def tick&lt;br /&gt;
                synchronize do&lt;br /&gt;
                @count += 1&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    c = Counter.new&lt;br /&gt;
    t1 = Thread.new { 10000.times {  c.tick } } &lt;br /&gt;
    t2 = Thread.new { 10000.times {  c.tick } }&lt;br /&gt;
    t1.join; t2.join&lt;br /&gt;
    c.count&lt;br /&gt;
&lt;br /&gt;
=Java vs Ruby threads=&lt;br /&gt;
Java thread initialization is more involved than Ruby thread initialization. Ruby threads also have the advantage of a “quick and dirty” thread creation, since it only takes couple of lines of code.  A Ruby thread shares all global, instance and local variables that are in existence at the time the thread starts. A Java thread can share these variables, as well, depending on how the thread was created.  If the client thread class uses inheritance, any variables needed are passed along when creating the thread. If the thread is created through the interface, the variables can be shared as long as the class has been initialized and the variables in use. &lt;br /&gt;
	&lt;br /&gt;
Ruby’s green threads are completely portable, as they don’t rely on the OS. But, on a multi-core processor, native thread implementations can assign work to multiple processors while green threads cannot. In this environment native threads have a huge advantage as more work is done by the native threads.&lt;br /&gt;
&lt;br /&gt;
==Java and Ruby methods comparison==&lt;br /&gt;
&lt;br /&gt;
'''Table 1 lists thread actions and Java and Ruby’s equivalent methods of achieving them.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table1.jpg]]&lt;br /&gt;
&lt;br /&gt;
'''Table 2 lists thread actions available in Java, but Ruby doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table2.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Table 3 lists thread actions available in Ruby, but Java doesn’t have a method for the action.'''&lt;br /&gt;
&lt;br /&gt;
[[Image:java table3.jpg]]&lt;br /&gt;
&lt;br /&gt;
There are many similarities between the Java and Ruby Thread classes, as shown with the equivalent methods in Table 1.  But, as you can see, there are also many methods in Java that Ruby doesn't support and vice versa. Some methods like activeCount(), where it returns the number of active threads, are trivial, but there is a group of methods existing in both Java and Ruby that the other doesn't support. For Java, it is exception handling with getting/setting exceptions, while in Ruby, it is more thread control. Ruby has exception methods, but they are geared more toward events prior to the exception, like making sure all threads abort when exception starts and firing an exception to destroy threads. Java is more about setting the exceptions and getting them to change accordingly. So the Java Thread class has a little bit more exception handling than Ruby.&lt;br /&gt;
	&lt;br /&gt;
Ruby has more thread control for the programmer such as pausing, terminating, aborting and resuming threads. Java did have these functions, but they all have been deprecated because, although they give the user more control, they also can cause deadlock problems. So it is a tradeoff between more thread control and less chance for deadlocks to happen. Java does use interrupt to &amp;quot;pause&amp;quot; the thread as opposed to actually pausing the thread as in Ruby. Also, Java threads &amp;quot;sleep&amp;quot; differently than Ruby threads.  Java sleeps are timed, while Ruby's sleep just stops the thread indefinitely, until it gets woken up by &amp;quot;thr.wakeup&amp;quot;. As you can see Ruby's thread methods are more flexible, but potentially dangerous than Java’s.&lt;br /&gt;
&lt;br /&gt;
Basically, Java and Ruby both have similar thread functionalities.  In some respects, Java is simpler by reducing user error, while Ruby gives the programmer more power and perhaps more headaches. If user wants more control, then Ruby threading is great, but for simplicity Java is better.  The main distinction between Ruby threads and Java threads are that currently Ruby just supports green threads (as did Java 1.1) and Java has support for kernel threads.  Currently, there is no clear “winner” between native and green threads in a uni-processor system, but Java threads definitely have the edge over Ruby in a multi-processor environment.&lt;br /&gt;
Ruby is moving from green threads to kernel threads in Ruby 1.9 or 2.0, which are still development releases.  YARV has been integrated as the new Ruby VM.  YARV will give Ruby kernel thread support.  Detailed discussions of this change are at the following links:&lt;br /&gt;
http://www.infoq.com/news/2007/05/ruby-threading-futures&lt;br /&gt;
http://expressica.com/2008/04/26/new-in-ruby-19-threads/&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Java_table3.jpg&amp;diff=12455</id>
		<title>File:Java table3.jpg</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Java_table3.jpg&amp;diff=12455"/>
		<updated>2008-06-06T17:35:07Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Java_table2.jpg&amp;diff=12453</id>
		<title>File:Java table2.jpg</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Java_table2.jpg&amp;diff=12453"/>
		<updated>2008-06-06T17:34:41Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Java_table1.jpg&amp;diff=12451</id>
		<title>File:Java table1.jpg</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Java_table1.jpg&amp;diff=12451"/>
		<updated>2008-06-06T17:31:25Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Java_effi.JPG&amp;diff=12448</id>
		<title>File:Java effi.JPG</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Java_effi.JPG&amp;diff=12448"/>
		<updated>2008-06-06T17:28:12Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Java_table_3.JPG&amp;diff=12446</id>
		<title>File:Java table 3.JPG</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Java_table_3.JPG&amp;diff=12446"/>
		<updated>2008-06-06T17:26:48Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Java_table_2.JPG&amp;diff=12445</id>
		<title>File:Java table 2.JPG</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Java_table_2.JPG&amp;diff=12445"/>
		<updated>2008-06-06T17:26:36Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Java_table_1.JPG&amp;diff=12444</id>
		<title>File:Java table 1.JPG</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Java_table_1.JPG&amp;diff=12444"/>
		<updated>2008-06-06T17:25:49Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12442</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12442"/>
		<updated>2008-06-06T17:19:35Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
A thread is a basic unit of CPU utilization.  A traditional process has a single thread of control.  Many modern operating systems provide features enabling a process to contain multiple threads of control.  If the process has multiple threads of control, it can do more than one task at a time, such as, displaying graphics and reading keystrokes.  Threads are used mainly to run asynchronous tasks and pass the application’s tasks to an executor.  They are useful because they reduce the overall time of execution of programs. All threads belonging to the same process share its code section, data section and other operating system resources, such as open files and signals.  Thus multithreading is more efficient than having parallel processes running for the same program, which require a huge overhead.&lt;br /&gt;
&lt;br /&gt;
=Multi-threaded programming= &lt;br /&gt;
Multithreading support for single processors works by giving each of the threads a “time slice” of the CPU, similar to the parallel execution of processes.  On multi-core machines, different threads can run on the different processors and the threads truly run simultaneously.   Support for threads may be provided at either the user level, for user or green threads, or by the kernel, for kernel or native threads.  User threads are supported above the kernel and are managed without kernel support, whereas kernel threads are supported and managed directly by the operating system.&lt;br /&gt;
&lt;br /&gt;
==Multi-threading models==&lt;br /&gt;
There are three common multithreading models&lt;br /&gt;
&lt;br /&gt;
===One-to-one===&lt;br /&gt;
This model maps each user-thread to a kernel thread.  It provides more concurrency than the many-to-one model by allowing another thread to run when a thread makes a blocking system call.  It also allows multiple threads to run in parallel on multiprocessors.  The main disadvantage of this model is the overhead of creating each kernel thread for each user thread.  This burdens the performance of an application and limits the number of threads supported by the system.&lt;br /&gt;
&lt;br /&gt;
===Many-to-one===&lt;br /&gt;
This model maps many user-level threads to one kernel thread.  It is the model used by green threads.  Green threads are scheduled by a Virtual Machine instead of natively by the OS. They emulate multithreaded environments without relying on any native OS capabilities. These user-level threads are lightweight and very efficient.  They are an easy way to achieve parallelism in a program.   An application can have as many user-level threads as it needs, but true concurrency is not achieved because the kernel can schedule only one thread at a time. The developers can create as many user threads as necessary.  However, there are two main disadvantages:&lt;br /&gt;
1)	If a thread makes a blocking system call, the entire process will block.&lt;br /&gt;
2)	If you are running on a multi-core machine, the multiple threads are unable to run in parallel.&lt;br /&gt;
&lt;br /&gt;
===Many-to-Many===&lt;br /&gt;
This model multiplexes many user-level threads to a smaller or equal number of kernel threads.  This model has the best of both worlds.  Developers can create as many user threads as they need.  When a user thread performs a blocking system call, the kernel can schedule another thread for execution and the kernel threads can run in parallel on multi-core systems.&lt;br /&gt;
&lt;br /&gt;
==Benefits of multi-threading==&lt;br /&gt;
===Resource sharing===&lt;br /&gt;
Memory, code and process resource sharing - allocating memory and resources for process creation is costly and time consuming.  It is more economical to create threads than new processes.  Applications can benefit by having several different threads of activity within the same address space.&lt;br /&gt;
&lt;br /&gt;
===Responsiveness===&lt;br /&gt;
Multithreading an interactive application may allow a program to continue running, even if part of it is blocked doing IO or performing a lengthy operation, thereby increasing responsiveness to the user.  A web browser might have one thread display images or text while another thread retrieves data from the network.  A busy web server may have many clients concurrently accessing it.  If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time.&lt;br /&gt;
&lt;br /&gt;
==Potential problems of multi-threading==&lt;br /&gt;
Many threaded programs have shared resources that must be accessed by more than one thread.  These programs must implement a form of mutual exclusion to ensure that only one of the threads can access the resource at a time.  These shared resources must execute in code called critical sections.  These critical sections must be protected by either hardware or software means.&lt;br /&gt;
&lt;br /&gt;
=Java threads=&lt;br /&gt;
The Java programming language has a thread library for creating and managing threads at the user-level.  The Java virtual machine (JVM) manages the mapping of the user threads to the operating system kernel threads.  The particular mapping model that is used depends on the operating system on which the Java program is running.  Java’s Thread Scheduler monitors all the threads running in Java programs.  It decides which threads to run at any given time and when to switch between threads to run based on the thread’s priority with higher running threads running before lower priority threads.  The Java scheduler uses either preemptive or non-preemptive scheduling based on the operating system on which it is running.  With preemptive scheduling, each thread is given a constant period of time to run, after which time the thread will be suspended() to allow the next thread to resume() running.  With non-preemptive scheduling, the running thread is allowed to run until the thread completes or until it issues a yield() to allow other threads to run while it waits for some other processing to occur.  &lt;br /&gt;
A Java thread can be created either by having your Java class extend the Java Thread class or by having your Java class implement the Runnable interface and coding a run() method.  The two options are shown in Figures 1 and 2.   The preferred method for creating a thread is by implementing the Runnable interface.  It is more flexible and useful in complex applications.   Java does not support multiple inheritance, but a class may implement multiple interfaces.  By using the interface method, the Client class is open to inherit another class, if the need arose in the future.&lt;br /&gt;
  &lt;br /&gt;
'''Figure 1: Client Extends Thread Class'''&lt;br /&gt;
        &lt;br /&gt;
    public class Client extends Thread {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Server {&lt;br /&gt;
        public static void main(String args[]){&lt;br /&gt;
            Thread runner = new Client();&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 2: Client Implements Runnable Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
   &lt;br /&gt;
    public class Server {&lt;br /&gt;
    &lt;br /&gt;
        public static void main(String args[]) {&lt;br /&gt;
            Thread runner = new Thread(new Client());&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
If the main Java thread wants to wait for any threads it creates to finish their run() method, the thread method join() can be executed.  The join() method is useful in situations where the creating thread can continue only after a worker thread has completed.  Java threads can be asynchronously terminated using the stop() method.  However, this method has been deprecated and its used is discouraged.  The preferred cancellation technique is to have the target thread periodically check whether it should terminate by using the interrupt() method.&lt;br /&gt;
&lt;br /&gt;
==States of Java threads==&lt;br /&gt;
===New===&lt;br /&gt;
A thread is in this state when the thread object is first created with the new() method.&lt;br /&gt;
===Runnable===&lt;br /&gt;
Calling the start() method allocates memory for the new thread in the JVM and calls the run() method for the thread object.&lt;br /&gt;
===Blocked===&lt;br /&gt;
A thread becomes blocked if it performs a blocking statement, such as doing I/O or if it invokes a sleep() method.&lt;br /&gt;
===Dead===&lt;br /&gt;
A thread moves to the dead state when its run() method terminates.&lt;br /&gt;
&lt;br /&gt;
==Mutual exclusion==&lt;br /&gt;
The Java language implements mutual exclusion in a couple of ways.  There exists a MutualExclusion interface.  The Client class can implement this interface and code the methods, enteringCriticalSection() and leavingCriticalSection(), as shown in Figure 3.  The yield() method tells the Thread Scheduler to allow another thread to run.  &lt;br /&gt;
&lt;br /&gt;
'''Figure 3: Client Implements MutualExclusion Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements MutualExclusion{&lt;br /&gt;
    &lt;br /&gt;
        public Client(){&lt;br /&gt;
            flag0 = false; flag1 = false; turn = TURN_0;&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void enteringCriticalSection(int t) {&lt;br /&gt;
            int other = 1 - t;&lt;br /&gt;
            &lt;br /&gt;
            if (t == 0) {&lt;br /&gt;
                flag0 = true; turn = other;&lt;br /&gt;
                while ((flag1 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             } else {&lt;br /&gt;
                flag1 = true; turn = other;&lt;br /&gt;
     	        while ((flag0 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void leavingCriticalSection(int t) {&lt;br /&gt;
            if(t == 0) flag0 = false;&lt;br /&gt;
            else   flag1 = false;&lt;br /&gt;
        }&lt;br /&gt;
        private volatile int turn, boolean flag0, flag1;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
An alternative method of handling mutual exclusion is to code a synchronization tool called a semaphore.  A semaphore is variable that is accessed only through two standard operations: acquire() and release().  The semaphore is acquired, then the critical section of an object is entered and after the critical code completes, the semaphore is released.  An example of this code is in Figure 4.&lt;br /&gt;
&lt;br /&gt;
'''Figure 4: Client Has Semaphore'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
    &lt;br /&gt;
        public Client (Semaphore sem) {&lt;br /&gt;
            this.sem = sem;&lt;br /&gt;
        }&lt;br /&gt;
       &lt;br /&gt;
        public void run() {&lt;br /&gt;
            sem.acquire();&lt;br /&gt;
            System.out.println(&amp;quot;Entering critical section&amp;quot;);&lt;br /&gt;
            SleepUtilities.nap(3);&lt;br /&gt;
            System.out.println(&amp;quot;Leaving critical section&amp;quot;);&lt;br /&gt;
            sem.release();&lt;br /&gt;
        }&lt;br /&gt;
        private Semaphore sem;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Ruby threads=&lt;br /&gt;
At the present time the Ruby programming language just supports green threads.  These are totally implemented within the Ruby interpreter.  The threads, as well as the thread scheduler run on the same single operating system thread.  Ruby can support thread methods, such as stop() and kill(), that are not advised for kernel threads.  However, Ruby threads suffer from the drawbacks of non-native threads.  They can only run on one processor in a multiprocessor environment.  It is possible for a single thread to cause the whole process to deadlock, if poorly designed.  The worse problem with Ruby threads is with I/O, especially network access, since it has the potential to block a process for a long time.  This problem is solvable by using non-blocking I/O.  However, one problem that is not solvable using non-blocking I/O, is the DNS lookup system call.  Ruby solves this problem with their resolv library, which was written specifically to address the threading issue with the standard OS DNA lookup mechanism.  See Figure 5 for an example of the code that handles this issue.  Despite some of the green thread concerns, for most situations, the benefits of efficiency can far outweigh the disadvantages.&lt;br /&gt;
&lt;br /&gt;
'''Figure 5: Ruby DNS Lookup Implementation'''&lt;br /&gt;
    &lt;br /&gt;
    require ‘socket’&lt;br /&gt;
    require ‘resolv-replace’&lt;br /&gt;
    count = 0&lt;br /&gt;
    Thread.critical = true&lt;br /&gt;
    thread = Thread.new { Thread.pass; loop { count += 1; } } IPSocket.getaddress(www.ruby-lang.org) &lt;br /&gt;
    count&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A Ruby thread is created using Thread.new() {block}.  The arguments given in the new() method are passed to the block code that the thread executes.  See Figure 6 for an example of creating a Ruby thread.  The Ruby pass() method is analogous to the Java yield() method.  It tells the thread scheduler to pass execution to another thread.  Ruby has a join() method that performs the same functionality as the Java join().  There are run() and wakeup() methods that wake up a sleeping threads, either giving it control or indicating that it is ready to be scheduled. &lt;br /&gt;
&lt;br /&gt;
'''Figure 6: Creating Ruby Threads'''&lt;br /&gt;
&lt;br /&gt;
    threads = []&lt;br /&gt;
    4.times do |number|&lt;br /&gt;
        threads &amp;lt;&amp;lt; Thread.new(number) do |i|&lt;br /&gt;
            print “#{i}\n”    &lt;br /&gt;
        end &lt;br /&gt;
    end&lt;br /&gt;
    threads.each { |t| t.join }  &lt;br /&gt;
&lt;br /&gt;
==States of Ruby threads==&lt;br /&gt;
===Run===&lt;br /&gt;
The thread is executing.&lt;br /&gt;
===Sleep===&lt;br /&gt;
The thread is sleeping or waiting on I/O.&lt;br /&gt;
===Aborting===&lt;br /&gt;
The thread is aborting (has been killed).&lt;br /&gt;
===False===&lt;br /&gt;
The thread has terminated normally.&lt;br /&gt;
===Nil===&lt;br /&gt;
The thread has terminated with an exception.&lt;br /&gt;
&lt;br /&gt;
==Mutual Exclusion==&lt;br /&gt;
The best way to handle mutual exclusion in Ruby is with the Monitor class.  A monitor has a synchronization() method that prevent access to a resource by another thread while one is execution in that method.  Figure 7 shows an example of how this can be used.   &lt;br /&gt;
&lt;br /&gt;
'''Figure 7: Ruby Monitor'''&lt;br /&gt;
&lt;br /&gt;
    require 'monitor'&lt;br /&gt;
        class Counter &amp;lt; Monitor&lt;br /&gt;
            attr_reader :count&lt;br /&gt;
        &lt;br /&gt;
            def initialize&lt;br /&gt;
                @count = 0&lt;br /&gt;
                super&lt;br /&gt;
            end&lt;br /&gt;
 &lt;br /&gt;
            def tick&lt;br /&gt;
                synchronize do&lt;br /&gt;
                @count += 1&lt;br /&gt;
            end&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    c = Counter.new&lt;br /&gt;
    t1 = Thread.new { 10000.times {  c.tick } } &lt;br /&gt;
    t2 = Thread.new { 10000.times {  c.tick } }&lt;br /&gt;
    t1.join; t2.join&lt;br /&gt;
    c.count&lt;br /&gt;
&lt;br /&gt;
=Java vs Ruby threads=&lt;br /&gt;
Java thread initialization is more involved than Ruby thread initialization. Ruby threads also have the advantage of a “quick and dirty” thread creation, since it only takes couple of lines of code.  A Ruby thread shares all global, instance and local variables that are in existence at the time the thread starts. A Java thread can share these variables, as well, depending on how the thread was created.  If the client thread class uses inheritance, any variables needed are passed along when creating the thread. If the thread is created through the interface, the variables can be shared as long as the class has been initialized and the variables in use. &lt;br /&gt;
	&lt;br /&gt;
Ruby’s green threads are completely portable, as they don’t rely on the OS. But, on a multi-core processor, native thread implementations can assign work to multiple processors while green threads cannot. In this environment native threads have a huge advantage as more work is done by the native threads.&lt;br /&gt;
&lt;br /&gt;
==Java and Ruby methods comparison==&lt;br /&gt;
&lt;br /&gt;
'''Table 1 lists thread actions and Java and Ruby’s equivalent methods of achieving them.'''&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12441</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12441"/>
		<updated>2008-06-06T17:10:04Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Mutual exclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
A thread is a basic unit of CPU utilization.  A traditional process has a single thread of control.  Many modern operating systems provide features enabling a process to contain multiple threads of control.  If the process has multiple threads of control, it can do more than one task at a time, such as, displaying graphics and reading keystrokes.  Threads are used mainly to run asynchronous tasks and pass the application’s tasks to an executor.  They are useful because they reduce the overall time of execution of programs. All threads belonging to the same process share its code section, data section and other operating system resources, such as open files and signals.  Thus multithreading is more efficient than having parallel processes running for the same program, which require a huge overhead.&lt;br /&gt;
&lt;br /&gt;
=Multi-threaded programming= &lt;br /&gt;
Multithreading support for single processors works by giving each of the threads a “time slice” of the CPU, similar to the parallel execution of processes.  On multi-core machines, different threads can run on the different processors and the threads truly run simultaneously.   Support for threads may be provided at either the user level, for user or green threads, or by the kernel, for kernel or native threads.  User threads are supported above the kernel and are managed without kernel support, whereas kernel threads are supported and managed directly by the operating system.&lt;br /&gt;
&lt;br /&gt;
==Multi-threading models==&lt;br /&gt;
There are three common multithreading models&lt;br /&gt;
&lt;br /&gt;
===One-to-one===&lt;br /&gt;
This model maps each user-thread to a kernel thread.  It provides more concurrency than the many-to-one model by allowing another thread to run when a thread makes a blocking system call.  It also allows multiple threads to run in parallel on multiprocessors.  The main disadvantage of this model is the overhead of creating each kernel thread for each user thread.  This burdens the performance of an application and limits the number of threads supported by the system.&lt;br /&gt;
&lt;br /&gt;
===Many-to-one===&lt;br /&gt;
This model maps many user-level threads to one kernel thread.  It is the model used by green threads.  Green threads are scheduled by a Virtual Machine instead of natively by the OS. They emulate multithreaded environments without relying on any native OS capabilities. These user-level threads are lightweight and very efficient.  They are an easy way to achieve parallelism in a program.   An application can have as many user-level threads as it needs, but true concurrency is not achieved because the kernel can schedule only one thread at a time. The developers can create as many user threads as necessary.  However, there are two main disadvantages:&lt;br /&gt;
1)	If a thread makes a blocking system call, the entire process will block.&lt;br /&gt;
2)	If you are running on a multi-core machine, the multiple threads are unable to run in parallel.&lt;br /&gt;
&lt;br /&gt;
===Many-to-Many===&lt;br /&gt;
This model multiplexes many user-level threads to a smaller or equal number of kernel threads.  This model has the best of both worlds.  Developers can create as many user threads as they need.  When a user thread performs a blocking system call, the kernel can schedule another thread for execution and the kernel threads can run in parallel on multi-core systems.&lt;br /&gt;
&lt;br /&gt;
==Benefits of multi-threading==&lt;br /&gt;
===Resource sharing===&lt;br /&gt;
Memory, code and process resource sharing - allocating memory and resources for process creation is costly and time consuming.  It is more economical to create threads than new processes.  Applications can benefit by having several different threads of activity within the same address space.&lt;br /&gt;
&lt;br /&gt;
===Responsiveness===&lt;br /&gt;
Multithreading an interactive application may allow a program to continue running, even if part of it is blocked doing IO or performing a lengthy operation, thereby increasing responsiveness to the user.  A web browser might have one thread display images or text while another thread retrieves data from the network.  A busy web server may have many clients concurrently accessing it.  If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time.&lt;br /&gt;
&lt;br /&gt;
==Potential problems of multi-threading==&lt;br /&gt;
Many threaded programs have shared resources that must be accessed by more than one thread.  These programs must implement a form of mutual exclusion to ensure that only one of the threads can access the resource at a time.  These shared resources must execute in code called critical sections.  These critical sections must be protected by either hardware or software means.&lt;br /&gt;
&lt;br /&gt;
=Java threads=&lt;br /&gt;
The Java programming language has a thread library for creating and managing threads at the user-level.  The Java virtual machine (JVM) manages the mapping of the user threads to the operating system kernel threads.  The particular mapping model that is used depends on the operating system on which the Java program is running.  Java’s Thread Scheduler monitors all the threads running in Java programs.  It decides which threads to run at any given time and when to switch between threads to run based on the thread’s priority with higher running threads running before lower priority threads.  The Java scheduler uses either preemptive or non-preemptive scheduling based on the operating system on which it is running.  With preemptive scheduling, each thread is given a constant period of time to run, after which time the thread will be suspended() to allow the next thread to resume() running.  With non-preemptive scheduling, the running thread is allowed to run until the thread completes or until it issues a yield() to allow other threads to run while it waits for some other processing to occur.  &lt;br /&gt;
A Java thread can be created either by having your Java class extend the Java Thread class or by having your Java class implement the Runnable interface and coding a run() method.  The two options are shown in Figures 1 and 2.   The preferred method for creating a thread is by implementing the Runnable interface.  It is more flexible and useful in complex applications.   Java does not support multiple inheritance, but a class may implement multiple interfaces.  By using the interface method, the Client class is open to inherit another class, if the need arose in the future.&lt;br /&gt;
  &lt;br /&gt;
'''Figure 1: Client Extends Thread Class'''&lt;br /&gt;
        &lt;br /&gt;
    public class Client extends Thread {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Server {&lt;br /&gt;
        public static void main(String args[]){&lt;br /&gt;
            Thread runner = new Client();&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 2: Client Implements Runnable Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
   &lt;br /&gt;
    public class Server {&lt;br /&gt;
    &lt;br /&gt;
        public static void main(String args[]) {&lt;br /&gt;
            Thread runner = new Thread(new Client());&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
If the main Java thread wants to wait for any threads it creates to finish their run() method, the thread method join() can be executed.  The join() method is useful in situations where the creating thread can continue only after a worker thread has completed.  Java threads can be asynchronously terminated using the stop() method.  However, this method has been deprecated and its used is discouraged.  The preferred cancellation technique is to have the target thread periodically check whether it should terminate by using the interrupt() method.&lt;br /&gt;
&lt;br /&gt;
==States of Java threads==&lt;br /&gt;
===New===&lt;br /&gt;
A thread is in this state when the thread object is first created with the new() method.&lt;br /&gt;
===Runnable===&lt;br /&gt;
Calling the start() method allocates memory for the new thread in the JVM and calls the run() method for the thread object.&lt;br /&gt;
===Blocked===&lt;br /&gt;
A thread becomes blocked if it performs a blocking statement, such as doing I/O or if it invokes a sleep() method.&lt;br /&gt;
===Dead===&lt;br /&gt;
A thread moves to the dead state when its run() method terminates.&lt;br /&gt;
&lt;br /&gt;
==Mutual exclusion==&lt;br /&gt;
The Java language implements mutual exclusion in a couple of ways.  There exists a MutualExclusion interface.  The Client class can implement this interface and code the methods, enteringCriticalSection() and leavingCriticalSection(), as shown in Figure 3.  The yield() method tells the Thread Scheduler to allow another thread to run.  &lt;br /&gt;
&lt;br /&gt;
'''Figure 3: Client Implements MutualExclusion Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements MutualExclusion{&lt;br /&gt;
    &lt;br /&gt;
        public Client(){&lt;br /&gt;
            flag0 = false; flag1 = false; turn = TURN_0;&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void enteringCriticalSection(int t) {&lt;br /&gt;
            int other = 1 - t;&lt;br /&gt;
            &lt;br /&gt;
            if (t == 0) {&lt;br /&gt;
                flag0 = true; turn = other;&lt;br /&gt;
                while ((flag1 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             } else {&lt;br /&gt;
                flag1 = true; turn = other;&lt;br /&gt;
     	        while ((flag0 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void leavingCriticalSection(int t) {&lt;br /&gt;
            if(t == 0) flag0 = false;&lt;br /&gt;
            else   flag1 = false;&lt;br /&gt;
        }&lt;br /&gt;
        private volatile int turn, boolean flag0, flag1;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
An alternative method of handling mutual exclusion is to code a synchronization tool called a semaphore.  A semaphore is variable that is accessed only through two standard operations: acquire() and release().  The semaphore is acquired, then the critical section of an object is entered and after the critical code completes, the semaphore is released.  An example of this code is in Figure 4.&lt;br /&gt;
&lt;br /&gt;
'''Figure 4: Client Has Semaphore'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
    &lt;br /&gt;
        public Client (Semaphore sem) {&lt;br /&gt;
            this.sem = sem;&lt;br /&gt;
        }&lt;br /&gt;
       &lt;br /&gt;
        public void run() {&lt;br /&gt;
            sem.acquire();&lt;br /&gt;
            System.out.println(&amp;quot;Entering critical section&amp;quot;);&lt;br /&gt;
            SleepUtilities.nap(3);&lt;br /&gt;
            System.out.println(&amp;quot;Leaving critical section&amp;quot;);&lt;br /&gt;
            sem.release();&lt;br /&gt;
        }&lt;br /&gt;
        private Semaphore sem;&lt;br /&gt;
    }&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12440</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12440"/>
		<updated>2008-06-06T17:07:15Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
A thread is a basic unit of CPU utilization.  A traditional process has a single thread of control.  Many modern operating systems provide features enabling a process to contain multiple threads of control.  If the process has multiple threads of control, it can do more than one task at a time, such as, displaying graphics and reading keystrokes.  Threads are used mainly to run asynchronous tasks and pass the application’s tasks to an executor.  They are useful because they reduce the overall time of execution of programs. All threads belonging to the same process share its code section, data section and other operating system resources, such as open files and signals.  Thus multithreading is more efficient than having parallel processes running for the same program, which require a huge overhead.&lt;br /&gt;
&lt;br /&gt;
=Multi-threaded programming= &lt;br /&gt;
Multithreading support for single processors works by giving each of the threads a “time slice” of the CPU, similar to the parallel execution of processes.  On multi-core machines, different threads can run on the different processors and the threads truly run simultaneously.   Support for threads may be provided at either the user level, for user or green threads, or by the kernel, for kernel or native threads.  User threads are supported above the kernel and are managed without kernel support, whereas kernel threads are supported and managed directly by the operating system.&lt;br /&gt;
&lt;br /&gt;
==Multi-threading models==&lt;br /&gt;
There are three common multithreading models&lt;br /&gt;
&lt;br /&gt;
===One-to-one===&lt;br /&gt;
This model maps each user-thread to a kernel thread.  It provides more concurrency than the many-to-one model by allowing another thread to run when a thread makes a blocking system call.  It also allows multiple threads to run in parallel on multiprocessors.  The main disadvantage of this model is the overhead of creating each kernel thread for each user thread.  This burdens the performance of an application and limits the number of threads supported by the system.&lt;br /&gt;
&lt;br /&gt;
===Many-to-one===&lt;br /&gt;
This model maps many user-level threads to one kernel thread.  It is the model used by green threads.  Green threads are scheduled by a Virtual Machine instead of natively by the OS. They emulate multithreaded environments without relying on any native OS capabilities. These user-level threads are lightweight and very efficient.  They are an easy way to achieve parallelism in a program.   An application can have as many user-level threads as it needs, but true concurrency is not achieved because the kernel can schedule only one thread at a time. The developers can create as many user threads as necessary.  However, there are two main disadvantages:&lt;br /&gt;
1)	If a thread makes a blocking system call, the entire process will block.&lt;br /&gt;
2)	If you are running on a multi-core machine, the multiple threads are unable to run in parallel.&lt;br /&gt;
&lt;br /&gt;
===Many-to-Many===&lt;br /&gt;
This model multiplexes many user-level threads to a smaller or equal number of kernel threads.  This model has the best of both worlds.  Developers can create as many user threads as they need.  When a user thread performs a blocking system call, the kernel can schedule another thread for execution and the kernel threads can run in parallel on multi-core systems.&lt;br /&gt;
&lt;br /&gt;
==Benefits of multi-threading==&lt;br /&gt;
===Resource sharing===&lt;br /&gt;
Memory, code and process resource sharing - allocating memory and resources for process creation is costly and time consuming.  It is more economical to create threads than new processes.  Applications can benefit by having several different threads of activity within the same address space.&lt;br /&gt;
&lt;br /&gt;
===Responsiveness===&lt;br /&gt;
Multithreading an interactive application may allow a program to continue running, even if part of it is blocked doing IO or performing a lengthy operation, thereby increasing responsiveness to the user.  A web browser might have one thread display images or text while another thread retrieves data from the network.  A busy web server may have many clients concurrently accessing it.  If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time.&lt;br /&gt;
&lt;br /&gt;
==Potential problems of multi-threading==&lt;br /&gt;
Many threaded programs have shared resources that must be accessed by more than one thread.  These programs must implement a form of mutual exclusion to ensure that only one of the threads can access the resource at a time.  These shared resources must execute in code called critical sections.  These critical sections must be protected by either hardware or software means.&lt;br /&gt;
&lt;br /&gt;
=Java threads=&lt;br /&gt;
The Java programming language has a thread library for creating and managing threads at the user-level.  The Java virtual machine (JVM) manages the mapping of the user threads to the operating system kernel threads.  The particular mapping model that is used depends on the operating system on which the Java program is running.  Java’s Thread Scheduler monitors all the threads running in Java programs.  It decides which threads to run at any given time and when to switch between threads to run based on the thread’s priority with higher running threads running before lower priority threads.  The Java scheduler uses either preemptive or non-preemptive scheduling based on the operating system on which it is running.  With preemptive scheduling, each thread is given a constant period of time to run, after which time the thread will be suspended() to allow the next thread to resume() running.  With non-preemptive scheduling, the running thread is allowed to run until the thread completes or until it issues a yield() to allow other threads to run while it waits for some other processing to occur.  &lt;br /&gt;
A Java thread can be created either by having your Java class extend the Java Thread class or by having your Java class implement the Runnable interface and coding a run() method.  The two options are shown in Figures 1 and 2.   The preferred method for creating a thread is by implementing the Runnable interface.  It is more flexible and useful in complex applications.   Java does not support multiple inheritance, but a class may implement multiple interfaces.  By using the interface method, the Client class is open to inherit another class, if the need arose in the future.&lt;br /&gt;
  &lt;br /&gt;
'''Figure 1: Client Extends Thread Class'''&lt;br /&gt;
        &lt;br /&gt;
    public class Client extends Thread {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Server {&lt;br /&gt;
        public static void main(String args[]){&lt;br /&gt;
            Thread runner = new Client();&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 2: Client Implements Runnable Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
   &lt;br /&gt;
    public class Server {&lt;br /&gt;
    &lt;br /&gt;
        public static void main(String args[]) {&lt;br /&gt;
            Thread runner = new Thread(new Client());&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
If the main Java thread wants to wait for any threads it creates to finish their run() method, the thread method join() can be executed.  The join() method is useful in situations where the creating thread can continue only after a worker thread has completed.  Java threads can be asynchronously terminated using the stop() method.  However, this method has been deprecated and its used is discouraged.  The preferred cancellation technique is to have the target thread periodically check whether it should terminate by using the interrupt() method.&lt;br /&gt;
&lt;br /&gt;
==States of Java threads==&lt;br /&gt;
===New===&lt;br /&gt;
A thread is in this state when the thread object is first created with the new() method.&lt;br /&gt;
===Runnable===&lt;br /&gt;
Calling the start() method allocates memory for the new thread in the JVM and calls the run() method for the thread object.&lt;br /&gt;
===Blocked===&lt;br /&gt;
A thread becomes blocked if it performs a blocking statement, such as doing I/O or if it invokes a sleep() method.&lt;br /&gt;
===Dead===&lt;br /&gt;
A thread moves to the dead state when its run() method terminates.&lt;br /&gt;
&lt;br /&gt;
==Mutual exclusion==&lt;br /&gt;
The Java language implements mutual exclusion in a couple of ways.  There exists a MutualExclusion interface.  The Client class can implement this interface and code the methods, enteringCriticalSection() and leavingCriticalSection(), as shown in Figure 3.  The yield() method tells the Thread Scheduler to allow another thread to run.  &lt;br /&gt;
&lt;br /&gt;
'''Figure 3: Client Implements MutualExclusion Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements MutualExclusion{&lt;br /&gt;
    &lt;br /&gt;
        public Client(){&lt;br /&gt;
            flag0 = false; flag1 = false; turn = TURN_0;&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void enteringCriticalSection(int t) {&lt;br /&gt;
            int other = 1 - t;&lt;br /&gt;
            &lt;br /&gt;
            if (t == 0) {&lt;br /&gt;
                flag0 = true; turn = other;&lt;br /&gt;
                while ((flag1 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             } else {&lt;br /&gt;
                flag1 = true; turn = other;&lt;br /&gt;
     	        while ((flag0 == true) &amp;amp;&amp;amp; (turn == other))&lt;br /&gt;
                    Thread.yield();&lt;br /&gt;
             }&lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public void leavingCriticalSection(int t) {&lt;br /&gt;
            if(t == 0) flag0 = false;&lt;br /&gt;
            else   flag1 = false;&lt;br /&gt;
        }&lt;br /&gt;
        private volatile int turn, boolean flag0, flag1;&lt;br /&gt;
    }&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12434</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12434"/>
		<updated>2008-06-06T16:47:53Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
A thread is a basic unit of CPU utilization.  A traditional process has a single thread of control.  Many modern operating systems provide features enabling a process to contain multiple threads of control.  If the process has multiple threads of control, it can do more than one task at a time, such as, displaying graphics and reading keystrokes.  Threads are used mainly to run asynchronous tasks and pass the application’s tasks to an executor.  They are useful because they reduce the overall time of execution of programs. All threads belonging to the same process share its code section, data section and other operating system resources, such as open files and signals.  Thus multithreading is more efficient than having parallel processes running for the same program, which require a huge overhead.&lt;br /&gt;
&lt;br /&gt;
=Multi-threaded programming= &lt;br /&gt;
Multithreading support for single processors works by giving each of the threads a “time slice” of the CPU, similar to the parallel execution of processes.  On multi-core machines, different threads can run on the different processors and the threads truly run simultaneously.   Support for threads may be provided at either the user level, for user or green threads, or by the kernel, for kernel or native threads.  User threads are supported above the kernel and are managed without kernel support, whereas kernel threads are supported and managed directly by the operating system.&lt;br /&gt;
&lt;br /&gt;
==Multi-threading models==&lt;br /&gt;
There are three common multithreading models&lt;br /&gt;
&lt;br /&gt;
===One-to-one===&lt;br /&gt;
This model maps each user-thread to a kernel thread.  It provides more concurrency than the many-to-one model by allowing another thread to run when a thread makes a blocking system call.  It also allows multiple threads to run in parallel on multiprocessors.  The main disadvantage of this model is the overhead of creating each kernel thread for each user thread.  This burdens the performance of an application and limits the number of threads supported by the system.&lt;br /&gt;
&lt;br /&gt;
===Many-to-one===&lt;br /&gt;
This model maps many user-level threads to one kernel thread.  It is the model used by green threads.  Green threads are scheduled by a Virtual Machine instead of natively by the OS. They emulate multithreaded environments without relying on any native OS capabilities. These user-level threads are lightweight and very efficient.  They are an easy way to achieve parallelism in a program.   An application can have as many user-level threads as it needs, but true concurrency is not achieved because the kernel can schedule only one thread at a time. The developers can create as many user threads as necessary.  However, there are two main disadvantages:&lt;br /&gt;
1)	If a thread makes a blocking system call, the entire process will block.&lt;br /&gt;
2)	If you are running on a multi-core machine, the multiple threads are unable to run in parallel.&lt;br /&gt;
&lt;br /&gt;
===Many-to-Many===&lt;br /&gt;
This model multiplexes many user-level threads to a smaller or equal number of kernel threads.  This model has the best of both worlds.  Developers can create as many user threads as they need.  When a user thread performs a blocking system call, the kernel can schedule another thread for execution and the kernel threads can run in parallel on multi-core systems.&lt;br /&gt;
&lt;br /&gt;
==Benefits of multi-threading==&lt;br /&gt;
===Resource sharing===&lt;br /&gt;
Memory, code and process resource sharing - allocating memory and resources for process creation is costly and time consuming.  It is more economical to create threads than new processes.  Applications can benefit by having several different threads of activity within the same address space.&lt;br /&gt;
&lt;br /&gt;
===Responsiveness===&lt;br /&gt;
Multithreading an interactive application may allow a program to continue running, even if part of it is blocked doing IO or performing a lengthy operation, thereby increasing responsiveness to the user.  A web browser might have one thread display images or text while another thread retrieves data from the network.  A busy web server may have many clients concurrently accessing it.  If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time.&lt;br /&gt;
&lt;br /&gt;
==Potential problems of multi-threading==&lt;br /&gt;
Many threaded programs have shared resources that must be accessed by more than one thread.  These programs must implement a form of mutual exclusion to ensure that only one of the threads can access the resource at a time.  These shared resources must execute in code called critical sections.  These critical sections must be protected by either hardware or software means.&lt;br /&gt;
&lt;br /&gt;
=Java threads=&lt;br /&gt;
The Java programming language has a thread library for creating and managing threads at the user-level.  The Java virtual machine (JVM) manages the mapping of the user threads to the operating system kernel threads.  The particular mapping model that is used depends on the operating system on which the Java program is running.  Java’s Thread Scheduler monitors all the threads running in Java programs.  It decides which threads to run at any given time and when to switch between threads to run based on the thread’s priority with higher running threads running before lower priority threads.  The Java scheduler uses either preemptive or non-preemptive scheduling based on the operating system on which it is running.  With preemptive scheduling, each thread is given a constant period of time to run, after which time the thread will be suspended() to allow the next thread to resume() running.  With non-preemptive scheduling, the running thread is allowed to run until the thread completes or until it issues a yield() to allow other threads to run while it waits for some other processing to occur.  &lt;br /&gt;
A Java thread can be created either by having your Java class extend the Java Thread class or by having your Java class implement the Runnable interface and coding a run() method.  The two options are shown in Figures 1 and 2.   The preferred method for creating a thread is by implementing the Runnable interface.  It is more flexible and useful in complex applications.   Java does not support multiple inheritance, but a class may implement multiple interfaces.  By using the interface method, the Client class is open to inherit another class, if the need arose in the future.&lt;br /&gt;
  &lt;br /&gt;
'''Figure 1: Client Extends Thread Class'''&lt;br /&gt;
        &lt;br /&gt;
    public class Client extends Thread {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public class Server {&lt;br /&gt;
        public static void main(String args[]){&lt;br /&gt;
            Thread runner = new Client();&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Figure 2: Client Implements Runnable Interface'''&lt;br /&gt;
&lt;br /&gt;
    public class Client implements Runnable {&lt;br /&gt;
        public void run() {&lt;br /&gt;
            System.out.println(“Client thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
   &lt;br /&gt;
    public class Server {&lt;br /&gt;
    &lt;br /&gt;
        public static void main(String args[]) {&lt;br /&gt;
            Thread runner = new Thread(new Client());&lt;br /&gt;
            runner.start();&lt;br /&gt;
            System.out.println(“Server thread”);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12432</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12432"/>
		<updated>2008-06-06T16:36:27Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
A thread is a basic unit of CPU utilization.  A traditional process has a single thread of control.  Many modern operating systems provide features enabling a process to contain multiple threads of control.  If the process has multiple threads of control, it can do more than one task at a time, such as, displaying graphics and reading keystrokes.  Threads are used mainly to run asynchronous tasks and pass the application’s tasks to an executor.  They are useful because they reduce the overall time of execution of programs. All threads belonging to the same process share its code section, data section and other operating system resources, such as open files and signals.  Thus multithreading is more efficient than having parallel processes running for the same program, which require a huge overhead.&lt;br /&gt;
&lt;br /&gt;
=Multi-threaded programming= &lt;br /&gt;
Multithreading support for single processors works by giving each of the threads a “time slice” of the CPU, similar to the parallel execution of processes.  On multi-core machines, different threads can run on the different processors and the threads truly run simultaneously.   Support for threads may be provided at either the user level, for user or green threads, or by the kernel, for kernel or native threads.  User threads are supported above the kernel and are managed without kernel support, whereas kernel threads are supported and managed directly by the operating system.&lt;br /&gt;
&lt;br /&gt;
==Multi-threading models==&lt;br /&gt;
There are three common multithreading models&lt;br /&gt;
&lt;br /&gt;
===One-to-one===&lt;br /&gt;
This model maps each user-thread to a kernel thread.  It provides more concurrency than the many-to-one model by allowing another thread to run when a thread makes a blocking system call.  It also allows multiple threads to run in parallel on multiprocessors.  The main disadvantage of this model is the overhead of creating each kernel thread for each user thread.  This burdens the performance of an application and limits the number of threads supported by the system.&lt;br /&gt;
&lt;br /&gt;
===Many-to-one===&lt;br /&gt;
This model maps many user-level threads to one kernel thread.  It is the model used by green threads.  Green threads are scheduled by a Virtual Machine instead of natively by the OS. They emulate multithreaded environments without relying on any native OS capabilities. These user-level threads are lightweight and very efficient.  They are an easy way to achieve parallelism in a program.   An application can have as many user-level threads as it needs, but true concurrency is not achieved because the kernel can schedule only one thread at a time. The developers can create as many user threads as necessary.  However, there are two main disadvantages:&lt;br /&gt;
1)	If a thread makes a blocking system call, the entire process will block.&lt;br /&gt;
2)	If you are running on a multi-core machine, the multiple threads are unable to run in parallel.&lt;br /&gt;
&lt;br /&gt;
===Many-to-Many===&lt;br /&gt;
This model multiplexes many user-level threads to a smaller or equal number of kernel threads.  This model has the best of both worlds.  Developers can create as many user threads as they need.  When a user thread performs a blocking system call, the kernel can schedule another thread for execution and the kernel threads can run in parallel on multi-core systems.&lt;br /&gt;
&lt;br /&gt;
==Benefits of multi-threading==&lt;br /&gt;
===Resource sharing===&lt;br /&gt;
Memory, code and process resource sharing - allocating memory and resources for process creation is costly and time consuming.  It is more economical to create threads than new processes.  Applications can benefit by having several different threads of activity within the same address space.&lt;br /&gt;
&lt;br /&gt;
===Responsiveness===&lt;br /&gt;
Multithreading an interactive application may allow a program to continue running, even if part of it is blocked doing IO or performing a lengthy operation, thereby increasing responsiveness to the user.  A web browser might have one thread display images or text while another thread retrieves data from the network.  A busy web server may have many clients concurrently accessing it.  If the web server ran as a traditional single-threaded process, it would be able to service only one client at a time.&lt;br /&gt;
&lt;br /&gt;
==Potential problems of multi-threading==&lt;br /&gt;
Many threaded programs have shared resources that must be accessed by more than one thread.  These programs must implement a form of mutual exclusion to ensure that only one of the threads can access the resource at a time.  These shared resources must execute in code called critical sections.  These critical sections must be protected by either hardware or software means.&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12430</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12430"/>
		<updated>2008-06-06T16:33:20Z</updated>

		<summary type="html">&lt;p&gt;Washao: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
A thread is a basic unit of CPU utilization.  A traditional process has a single thread of control.  Many modern operating systems provide features enabling a process to contain multiple threads of control.  If the process has multiple threads of control, it can do more than one task at a time, such as, displaying graphics and reading keystrokes.  Threads are used mainly to run asynchronous tasks and pass the application’s tasks to an executor.  They are useful because they reduce the overall time of execution of programs. All threads belonging to the same process share its code section, data section and other operating system resources, such as open files and signals.  Thus multithreading is more efficient than having parallel processes running for the same program, which require a huge overhead.&lt;br /&gt;
&lt;br /&gt;
=Multi-threaded programming= &lt;br /&gt;
Multithreading support for single processors works by giving each of the threads a “time slice” of the CPU, similar to the parallel execution of processes.  On multi-core machines, different threads can run on the different processors and the threads truly run simultaneously.   Support for threads may be provided at either the user level, for user or green threads, or by the kernel, for kernel or native threads.  User threads are supported above the kernel and are managed without kernel support, whereas kernel threads are supported and managed directly by the operating system.&lt;br /&gt;
&lt;br /&gt;
==Multi-threading models==&lt;br /&gt;
There are three common multithreading models&lt;br /&gt;
&lt;br /&gt;
===One-to-one===&lt;br /&gt;
This model maps each user-thread to a kernel thread.  It provides more concurrency than the many-to-one model by allowing another thread to run when a thread makes a blocking system call.  It also allows multiple threads to run in parallel on multiprocessors.  The main disadvantage of this model is the overhead of creating each kernel thread for each user thread.  This burdens the performance of an application and limits the number of threads supported by the system.&lt;br /&gt;
&lt;br /&gt;
===Many-to-one===&lt;br /&gt;
This model maps many user-level threads to one kernel thread.  It is the model used by green threads.  Green threads are scheduled by a Virtual Machine instead of natively by the OS. They emulate multithreaded environments without relying on any native OS capabilities. These user-level threads are lightweight and very efficient.  They are an easy way to achieve parallelism in a program.   An application can have as many user-level threads as it needs, but true concurrency is not achieved because the kernel can schedule only one thread at a time. The developers can create as many user threads as necessary.  However, there are two main disadvantages:&lt;br /&gt;
1)	If a thread makes a blocking system call, the entire process will block.&lt;br /&gt;
2)	If you are running on a multi-core machine, the multiple threads are unable to run in parallel.&lt;br /&gt;
&lt;br /&gt;
===Many-to-Many===&lt;br /&gt;
This model multiplexes many user-level threads to a smaller or equal number of kernel threads.  This model has the best of both worlds.  Developers can create as many user threads as they need.  When a user thread performs a blocking system call, the kernel can schedule another thread for execution and the kernel threads can run in parallel on multi-core systems.&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12429</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12429"/>
		<updated>2008-06-06T16:22:44Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Introduction =&lt;br /&gt;
    A thread is a basic unit of CPU utilization.  A traditional process has a single thread of control.  Many modern operating systems provide features enabling a process to contain multiple threads of control.  If the process has multiple threads of control, it can do more than one task at a time, such as, displaying graphics and reading keystrokes.  Threads are used mainly to run asynchronous tasks and pass the application’s tasks to an executor.  They are useful because they reduce the overall time of execution of programs. All threads belonging to the same process share its code section, data section and other operating system resources, such as open files and signals.  Thus multithreading is more efficient than having parallel processes running for the same program, which require a huge overhead.&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12217</id>
		<title>CSC/ECE 517 Summer 2008/wiki1 4 wm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Summer_2008/wiki1_4_wm&amp;diff=12217"/>
		<updated>2008-06-05T14:24:22Z</updated>

		<summary type="html">&lt;p&gt;Washao: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This is the placeholder for Wei And Mary's thread page&lt;/div&gt;</summary>
		<author><name>Washao</name></author>
	</entry>
</feed>