tag:blogger.com,1999:blog-42137994778970039792024-03-17T23:34:20.225-07:00Code like a bossAnonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.comBlogger26125tag:blogger.com,1999:blog-4213799477897003979.post-31783315027709559222015-08-12T19:49:00.001-07:002015-08-12T19:50:08.549-07:00Websockets in node.jsIn this post I'll show you how to start using websockets in node.js, the different types of modules there are, how to install them and use them to develop a simple example.<br />
<br />
For those who don't know what websockets is about, here is a brief introduction:<br />
<br />
Wikipedia says "WebSocket is a protocol providing full-duplex communications channels over a single TCP connection", this means that in a client-server communication the client as the server can send a message leaving behind the request-response protocol, where the exchange is always initiated by the client (usually a browser) and the server cannot send any data without the client requesting it first.<br />
<br />
It also says "WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application", websockets was introduced in the clients or browsers since the html5 specification.<br />
<br />
If you want to know more about websockets refer to the following links:<br />
<a href="http://www.websocket.org/">http://www.websocket.org/</a><br />
<a href="http://en.wikipedia.org/wiki/WebSocket">http://en.wikipedia.org/wiki/WebSocket</a><br />
<a href="https://developer.mozilla.org/en/docs/WebSockets">https://developer.mozilla.org/en/docs/WebSockets</a><br />
<br />
<h4>
<b>WS</b></h4>
<br />
Let's start with the first module "WS" , to start using it it needs to be installed so the following commands install the library:<br />
<br />
To install the module to the current directory use the following command:<br />
$ npm install ws<br />
<br />
To install the module in a global way use the following command:<br />
$ npm install ws -g<br />
<br />
Once install it we can create an example using this module, the code below shows how to create a simple server with ws:<br />
<br />
<script src="https://gist.github.com/anonymous/0d3677556af9623b23c6.js"></script>
<br />
Save the file as ws_server.js, from the code you can see that the server will be running in port 8080, any request to this port the server will attend it. To create a client use the code below:<br />
<br />
<script src="https://gist.github.com/anonymous/1139389e80f9490579c4.js"></script>
<br />
Save the file as ws_client.js and now lets run them, to run the server just type the following commands:<br />
<br />
Server:<br />
$ node ws_server.js<br />
Msg received in server: Msg from client<br />
<br />
Client:<br />
$ node ws_client.js<br />
Msg received in client: Msg from server<br />
<br />
From the output you can see that the server starts and listens to any message when the client starts it also listens to messages and it sends a message, then the server receives it and answers this message<br />
<br />
To find more about ws module go the following link <a href="https://github.com/einaros/ws">https://github.com/einaros/ws</a> is the page of the library.<br />
<br />
<h4>
WebSocket</h4>
<br />
Lets try another module for websocket, the WebSocket-Node module, this module has more requirements, needs c++ and python to compile the native modules but they are optional but its efficiency decreases if they are not installed, if you are a windows user you will find harder to install.<br />
<br />
To install WebSocket-Node module use the following command and use -g option to install it globally:<br />
<br />
$ npm install websocket -g<br />
<br />
Once installed the module lets proceed to create the example:<br />
<br />
<script src="https://gist.github.com/anonymous/170a73a7fad3dba6d972.js"></script>
<br />
Save the file as websocket_server.js. It creates a server for websockets that listens requests at the url ws://localhost:8080/example, in the code you can see that the port is configured at the instruction <span style="background-color: white; color: #333333; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; font-size: 12px; line-height: 16.7999992370605px; white-space: pre;">server.listen(</span><span class="pl-c1" style="background-color: white; box-sizing: border-box; color: #0086b3; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; font-size: 12px; line-height: 16.7999992370605px; white-space: pre;">8080</span><span style="background-color: white; color: #333333; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; font-size: 12px; line-height: 16.7999992370605px; white-space: pre;">)</span>, and the path is formed with <span style="background-color: white; color: #333333; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; font-size: 12px; line-height: 16.7999992370605px; white-space: pre;">request.</span><span class="pl-sc" style="background-color: white; box-sizing: border-box; color: #0086b3; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; font-size: 12px; line-height: 16.7999992370605px; white-space: pre;">accept</span><span style="background-color: white; color: #333333; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; font-size: 12px; line-height: 16.7999992370605px; white-space: pre;">(</span><span class="pl-s1" style="background-color: white; box-sizing: border-box; color: #df5000; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; font-size: 12px; line-height: 16.7999992370605px; white-space: pre;"><span class="pl-pds" style="box-sizing: border-box;">'</span>example<span class="pl-pds" style="box-sizing: border-box;">'</span></span><span style="background-color: white; color: #333333; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; font-size: 12px; line-height: 16.7999992370605px; white-space: pre;">, request.origin); .</span><br />
<br />
Let's create a client for the server:<br />
<br />
<script src="https://gist.github.com/anonymous/e15fb83c396f88af6917.js"></script>
<br />
Save the file as websocket_client.js, from the code you can see that the client creates a connection to the server using the instruction <span style="background-color: white; color: #333333; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; font-size: 12px; line-height: 16.7999992370605px; white-space: pre;">client.connect(</span><span class="pl-s1" style="background-color: white; box-sizing: border-box; color: #df5000; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; font-size: 12px; line-height: 16.7999992370605px; white-space: pre;"><span class="pl-pds" style="box-sizing: border-box;">'</span>ws://localhost:8080/<span class="pl-pds" style="box-sizing: border-box;">'</span></span><span style="background-color: white; color: #333333; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; font-size: 12px; line-height: 16.7999992370605px; white-space: pre;">, </span><span class="pl-s1" style="background-color: white; box-sizing: border-box; color: #df5000; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; font-size: 12px; line-height: 16.7999992370605px; white-space: pre;"><span class="pl-pds" style="box-sizing: border-box;">'</span>example<span class="pl-pds" style="box-sizing: border-box;">'</span></span><span style="background-color: white; color: #333333; font-family: Consolas, 'Liberation Mono', Menlo, Courier, monospace; font-size: 12px; line-height: 16.7999992370605px; white-space: pre;">);</span><i> ,</i>when a connection is done a message is sent to the server and the server should respond to the client with also a message.<br />
<br />
Now lets run the scripts using the following commands:<br />
<br />
Server:<br />
$ node websocket_server.js<br />
Received Message: Message from client<br />
<br />
Client:<br />
$ node websocket_client.js<br />
Received: 'Msg from server'<br />
<br />
The messages that the server and client are sending should be printed in the console if everything works as expected, if a problem happens with the connection you should see a message like this "Connection Error: Error: connect ECONNREFUSED".<br />
<br />
To find more about websocket module go the following link <a href="https://github.com/theturtle32/WebSocket-Node">https://github.com/theturtle32/WebSocket-Node</a> is the page of the library.<br />
<h4>
engine.io</h4>
<br />
Another module to use for creating websockets is engine.io, although this module is part of a bigger framework you can still use this module to create websockets.<br />
<br />
To install the module use the following command, to set it globally use the -g option:<br />
$ npm install engine.io -g<br />
<br />
To create a client for this module the module "engine.io-client" is required, lets install the module:<br />
$ npm install engine.io-client<br />
<br />
Lets create an example of a server:<br />
<br />
<script src="https://gist.github.com/anonymous/a618a81c2ad623cb775d.js"></script>
<br />
Save the file as engineio_server.js, from the code you can see the configuration needed to run the server, it is pretty simple.<br />
<br />
Now lets create a client for this server:<br />
<br />
<script src="https://gist.github.com/anonymous/6eb33b315fbfd5b2124a.js"></script>
<br />
Save the file as engineio_client.js and lets run the example with the following commands:<br />
<br />
Server:<br />
$ node engineio_server.js<br />
Msg Received at server:Msg from client<br />
<br />
Client:<br />
$ node engineio_client.js<br />
Msg Received at client:Msg from server<br />
<br />
As in the others examples if everything works as expected you should see the messages exchanged by the server and the client in console.<br />
<br />
To find more about engine.io module go the following link <a href="https://github.com/socketio/engine.io">https://github.com/socketio/engine.io</a> is the page of the library.<br />
<br />
There are many other libraries that can be used to create websockets with nodejs, every one with its pros and cons but it would take another post to discuss this topic. I guess the hardest part would be to choose which library to use.<br />
<br />
I wish this post helped you to better understand what websocket is and how to implement it in nodejs.<br />
<br />
<br />
<br />Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com72tag:blogger.com,1999:blog-4213799477897003979.post-50136611915159177282014-10-30T12:47:00.000-07:002014-10-30T12:47:13.102-07:00JavaFX dialogsThe JavaFX project doesn't have dialog controls, so when I wanted to add dialogs to my project I used the dialog controls from the <a href="http://fxexperience.com/controlsfx/">fxexperience</a> project, they release you from all the trouble of creating your own control, but recently they announced that the dialog controls will be in a separate project (<a href="http://fxexperience.com/2014/09/announcing-controlsfx-8-20-7/">announcing-controlsfx-8-20-7</a>) deprecating the current controls.<br />
<br />
The new project is called openjfx dialogs and it is located right here <a href="https://bitbucket.org/controlsfx/openjfx-dialogs">https://bitbucket.org/controlsfx/openjfx-dialogs</a>. Since right now it doesn't contain any documentation I will explain you how to start using it and ease the way to start adopting them.<br />
<br />
To start working first download the project repository from here <a href="https://bitbucket.org/controlsfx/openjfx-dialogs">bitbucket.org/controlsfx/openjfx-dialogs</a>, in the left side there is a link to download, it downloads a zip file, unzip it wherever you wan to.<br />
<br />
Next the project needs to be build, to do this we will need gradle, for thoose who don't know what is gradle here it is a brief description about it:<br />
<br />
"<i>Gradle combines the power and flexibility of Ant with the dependency management and conventions of Maven into a more effective way to build</i>"<br />
<br />
I'm not going to explain deeper gradle since it is another topic and this post wouldn't be enough to explain it.<br />
<br />
You can download and install gradle form here <a href="http://www.gradle.org/">www.gradle.org</a>, the project already contains a version of gradle you can just run the gradlew.bat file. Either you install it or use the version of the project, run the following command at the root of the project:<br />
<br />
gradle build<br />
<br />
If the project is built correctly you will find the folders build/lib under the root of the project, under these folders the openjfx-dialogs-X.X.X.jar is located we will need this jar to add the dialog controls.<br />
<br />
Now let's create an example to test the dialogs an see how they work, I'm going to use Netbeans to develop this example.<br />
<br />
Let's create a javafx application project:<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-OGM5_pWqLuE/VFHXzVdpcXI/AAAAAAAAH4g/5wIhMZW6LJM/s1600/jfx.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-OGM5_pWqLuE/VFHXzVdpcXI/AAAAAAAAH4g/5wIhMZW6LJM/s1600/jfx.jpg" height="220" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Let's name the project Dialogs, keep selected the checkbox "Create application class", then click finish.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Add to project the openjfx-dialogs jar, to do this over the project right click and select "properties" option. In the properties select the "libraries" option</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-X8lGzQXEn0s/VFHZPdlPelI/AAAAAAAAH4w/wssKc_nRjk4/s1600/jfx2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-X8lGzQXEn0s/VFHZPdlPelI/AAAAAAAAH4w/wssKc_nRjk4/s1600/jfx2.jpg" height="226" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Click over the Add Jar/Folder button, and select the jar previously built "openjfx-dialogs-X.X.X.jar".</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-pRuvUHZLvio/VFHZ4rP9cvI/AAAAAAAAH5E/fnQo3sgGmXc/s1600/jfx3.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-pRuvUHZLvio/VFHZ4rP9cvI/AAAAAAAAH5E/fnQo3sgGmXc/s1600/jfx3.jpg" height="219" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
With these steps everything is set to start creating dialogs, in the previous version the code to create a dialog was kind of messy and not intuitive from of my point of view, this is an example:<br />
<br />
It uses the builder pattern <a href="http://en.wikipedia.org/wiki/Builder_pattern">wikipedia.org/wiki/Builder_pattern</a>, a single class did handle all the types of dialogs, but now this code is deprecated. You can find more about the deprecated dialogs right here <a href="http://controlsfx.bitbucket.org/index.html?org/controlsfx/dialog/Dialogs.html">controlsfx.bitbucket.org/index.html?org/controlsfx/dialog/Dialogs.html</a><br />
<br />
In the new version each type of dialog has its own class making the code clearer and more intuitive, this is from my point of view. At this point the types of dialogs are javafx.scene.control.Alert, javafx.scene.control.ChoiceDialog and javafx.scene.control.TextInputDialog.<br />
<br />
Lets create an alert dialog, in the class created in the project change it to display the dialog as the following example:<br />
<br />
<script src="https://gist.github.com/anonymous/65d410be218ea7380352.js"></script>
From the example above an Alert object is created and it is passed a type of alert dialog, in this case is confirmation but there are others as error, information, warning, and so on.<br />
<br />
In the button's click event the show() is called to display the dialog, but this method doesn't wait the dialog to close, the method showAndWait() waits the dialog to close and returns an Optional object with the button typed if that was the case.<br />
<br />
The following example uses a text input dialog:<br />
<br />
<script src="https://gist.github.com/anonymous/afd97cbee9f84478d623.js"></script>
From the example above the only difference is that the showAndWait() method returns an Optional object with the content of the input element from the dialog.<br />
<br />
The ChoiceDialog displays a dialog with a combo control with a set of values, the following example show how to use it:<br />
<br />
<script src="https://gist.github.com/anonymous/d80356aa240e0e8da364.js"></script>
From the example above you can see that the options are passed through the constructor and later through the items property and uses the same mechanism as the TextInputDialog to retrieve the value selected.<br />
<br />
As I said before since the project is not finish and right now there is no documentation, I hope that with this post you can more easily adopt this new version or start using it.Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com49tag:blogger.com,1999:blog-4213799477897003979.post-37138752958786390752014-10-17T10:24:00.000-07:002014-10-17T10:24:50.023-07:00JavaFX workaround for rotate text on tabpane tab I have not much of experience with JavaFX, but I've been using it since almost over a year by now. I found that the tabs from the tabpane control have a restriction, when they are placed by a side either right or left the text can not be placed horizontal, the following image shows the behavior.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-dbkQLFjE4VM/VEBG1zEa1OI/AAAAAAAAHkI/2_3OE0n2IDo/s1600/tab.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-dbkQLFjE4VM/VEBG1zEa1OI/AAAAAAAAHkI/2_3OE0n2IDo/s1600/tab.jpg" /></a></div>
<br />
The issue is that the text is not displayed horizontally and it is hard to read, and javaFX does not provide a solution to it, actually there is feature request to it <a href="https://javafx-jira.kenai.com/browse/RT-19547">https://javafx-jira.kenai.com/browse/RT-19547</a> but it seems that it will not happen soon.<br />
<br />
I found some workarounds to it, but they have many issues such as the text doesn't properly resize the tab width, so I'm going to describe the workaround that I did, hoping that it could be helpful to you.<br />
<br />
A solution that I found from this post <a href="http://stackoverflow.com/questions/16708578/javafx-2-0-tabpane-tabs-at-left-and-keep-tab-header-horizontal">http://stackoverflow.com/questions/16708578/javafx-2-0-tabpane-tabs-at-left-and-keep-tab-header-horizontal </a>, mentions to add the following style:<br />
<br />
<script src="https://gist.github.com/anonymous/8a07fd24b20b9cacb305.js"></script>
Which works fine:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-NqyTMhGeHT4/VEBMFFbX66I/AAAAAAAAHkY/0s-CkooPWbA/s1600/tabs.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-NqyTMhGeHT4/VEBMFFbX66I/AAAAAAAAHkY/0s-CkooPWbA/s1600/tabs.jpg" height="292" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
But what if you have multiple tabs in your application and this tabs do not have the tabs by a side, it will also rotate the text of this tabs and will complicate everything.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-Uwt4Ow3eRFk/VEBNnVw7KEI/AAAAAAAAHkk/qUZZebHqGNA/s1600/tabs.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://4.bp.blogspot.com/-Uwt4Ow3eRFk/VEBNnVw7KEI/AAAAAAAAHkk/qUZZebHqGNA/s1600/tabs.jpg" height="147" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Another issue is, if the characters of the text increases the size also increases but not only its width but also its height:</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-6TdegZ7PGeo/VEBOj-9VM3I/AAAAAAAAHks/yBtuPSFIdQU/s1600/tabs.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-6TdegZ7PGeo/VEBOj-9VM3I/AAAAAAAAHks/yBtuPSFIdQU/s1600/tabs.jpg" height="320" width="254" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Due to all this issues this workaround and others seem to work fine only in certain scenarios.</div>
<div class="separator" style="clear: both; text-align: left;">
My workaround is not better than them, but it tries to avoid these issues.</div>
<div class="separator" style="clear: both; text-align: left;">
First, only rotate the tabs you want to rotate, to do this create a CSS class:</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<script src="https://gist.github.com/anonymous/726e45b36a49cb463a0f.js"></script>
<br />
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Then add it to the tabs objects you want to rotate:</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<script src="https://gist.github.com/anonymous/eb67758bc2078c6c2ce5.js"></script>
<br />
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Then create a CSS class to handle the size for the TabPane in which you are rotating the tabs:</div>
<br />
<script src="https://gist.github.com/anonymous/5760ac0f89f2d98c1671.js"></script>
Add this class to the TabPane object:<br />
<br />
<script src="https://gist.github.com/anonymous/be0b9edccdae203ce435.js"></script>
With this you will restrict the size of your tabs and they will not get bigger if the text increases. The limitation it has is that the amount of characters depends on the size you set to the TabPane object.<br />
<span style="background-color: white; font-family: Arial, FreeSans, Helvetica, sans-serif; font-size: 13px; line-height: 17.0000991821289px;"><br /></span>
<span style="background-color: white; font-family: Arial, FreeSans, Helvetica, sans-serif; font-size: 13px; line-height: 17.0000991821289px;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-6KErZdVTd44/VEBTn6gyuRI/AAAAAAAAHk8/t8C55-5K4Aw/s1600/tabs.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-6KErZdVTd44/VEBTn6gyuRI/AAAAAAAAHk8/t8C55-5K4Aw/s1600/tabs.jpg" height="320" width="204" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
As I said I'm not an expert on javaFX and I found this solution to this issue that seems to be different to others and might help you.<br />
If you have a different solution before this issue is fixed tell me about it.<br />
<span style="background-color: white; font-family: Arial, FreeSans, Helvetica, sans-serif; font-size: 13px; line-height: 17.0000991821289px;"><br /></span>
<span style="background-color: white; font-family: Arial, FreeSans, Helvetica, sans-serif; font-size: 13px; line-height: 17.0000991821289px;"><br /></span>
<span style="background-color: white; font-family: Arial, FreeSans, Helvetica, sans-serif; font-size: 13px; line-height: 17.0000991821289px;"><br /></span>Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com12tag:blogger.com,1999:blog-4213799477897003979.post-26093072242667639902014-06-09T22:14:00.002-07:002014-06-10T10:02:55.654-07:00Debug in node.jsA few days ago someone asked me if I knew how to debug in node.js and to be honest I was debugging with the console object, although it is effective I thought there should be better ways to debug a script, so I'm going to explain you my findings and hope to help someone that was in the same position as me.<br />
<div>
<br /></div>
<div>
So let's start with the simplest way to debug with the console object.</div>
<div>
<br /></div>
<div>
<script src="https://gist.github.com/anonymous/f88f938350c2593116e6.js"></script>
</div>
<div>
<br /></div>
<div>
Save the script and run it, the console will output in each iteration the value of the variables used in this case "i" and "sum", like the following:<br />
<br />
<i>Iteration:0, sum:0</i><br />
<i>Iteration:1, sum:1</i><br />
<i>Iteration:2, sum:3</i><br />
<i>Iteration:3, sum:6</i><br />
<i>Iteration:4, sum:10</i><br />
<i>Iteration:5, sum:15</i><br />
<i>Iteration:6, sum:21</i><br />
<i>Iteration:7, sum:28</i><br />
<i>Iteration:8, sum:36</i><br />
<i>Iteration:9, sum:45</i><br />
<br />
The console object has other methods besides log(), you can find more about it in the following link:<br />
<br />
<a href="http://nodejs.org/api/stdio.html">http://nodejs.org/api/stdio.html</a><br />
<br />
Since V8 node comes with a debugger, it has a built in client for this debugger to use it just add the debug argument when start running the script. Save the previous script as scriptDebug.js then type the following command to start the debugger:<br />
<br />
node debug scriptDebug.js<br />
<div>
<br /></div>
After that you will see a prompt to the debugger client as the following:<br />
<br />
<i>< debugger listening on port 5858</i><br />
<i>connecting... ok</i><br />
<i>break in scriptDebug.js:1</i><br />
<i> 1 var sum = 0;</i><br />
<i> 2</i><br />
<i> 3 for(i=0;i<10;i++) {</i><br />
<i>debug></i><br />
<br />
<div>
Now the debug client support some basic commands to debug the script, here are some of them:</div>
<div>
<div>
<ul>
<li>cont, c - Continue execution</li>
<li>next, n - Step next</li>
<li>step, s - Step in</li>
<li>out, o - Step out</li>
<li>pause - Pause running code (like pause button in Developer Tools)</li>
<li>setBreakpoint(), sb() - Set breakpoint on current line</li>
<li>clearBreakpoint, cb(...) - Clear breakpoint</li>
<li>.....</li>
</ul>
</div>
</div>
<div>
In the debugg mode if you type the command cont as this:<br />
<br />
<i>< debugger listening on port 5858</i><br />
<i>connecting... ok</i><br />
<i>break in scriptDebug.js:1</i><br />
<i> 1 var sum = 0;</i><br />
<i> 2</i><br />
<i> 3 for(i=0;i<10;i++) {</i><br />
<b><i>debug> cont</i></b><br />
<i>< Iteration:0, sum:0</i><br />
<i>< Iteration:1, sum:1</i><br />
<i>< Iteration:2, sum:3</i><br />
<i>< Iteration:3, sum:6</i><br />
<i>< Iteration:4, sum:10</i><br />
<i>< Iteration:5, sum:15</i><br />
<i>< Iteration:6, sum:21</i><br />
<i>< Iteration:7, sum:28</i><br />
<i>< Iteration:8, sum:36</i><br />
<i>< Iteration:9, sum:45</i><br />
<i>program terminated</i></div>
<div>
<br /></div>
<div>
You will see will be the output of the program, this is because the is no breakpoint in the code.</div>
<div>
<br />
To set a break point you could use the command sb(), for example to set a break point in the line 5, it would be like this:<br />
<br />
<i>connecting... ok</i><br />
<i>break in scriptDebug.js:1</i><br />
<i> 1 var sum = 0;</i><br />
<i> 2</i><br />
<i> 3 for(i=0;i<10;i++) {</i><br />
<b><i>debug> sb(5);</i></b><br />
<i> 1 var sum = 0;</i><br />
<i> 2</i><br />
<i> 3 for(i=0;i<10;i++) {</i><br />
<i> 4 <span class="Apple-tab-span" style="white-space: pre;"> </span>sum = sum + i;<span class="Apple-tab-span" style="white-space: pre;"> </span></i><br />
<b><i>* 5 console.log('Iteration:' + i +', sum:' + sum);<span class="Apple-tab-span" style="white-space: pre;"> </span></i></b><br />
<i> 6 }</i></div>
<div>
<br /></div>
<div>
Now every time a continue command is given it will stop in the breakpoint, as the following examples shows:</div>
<div>
<br /></div>
<div>
<b><i>debug> cont</i></b></div>
<div>
<div>
<i>< Iteration:0, sum:0</i></div>
<div>
<b><i>break in scriptDebug.js:5</i></b></div>
<div>
<i> 3 for(i=0;i<10;i++) {</i></div>
<div>
<i> 4 <span class="Apple-tab-span" style="white-space: pre;"> </span>sum = sum + i;<span class="Apple-tab-span" style="white-space: pre;"> </span></i></div>
<div>
<i>* 5 console.log('Iteration:' + i +', sum:' + sum);<span class="Apple-tab-span" style="white-space: pre;"> </span></i></div>
<div>
<i> 6 }</i></div>
<div>
</div>
</div>
<div>
Another way to place a breakpoint is to set the debugger instruction in your code as the following example:</div>
<div>
<br /></div>
<script src="https://gist.github.com/anonymous/6461b97840fe79edc7da.js"></script>
<br />
<div>
<br />
Once you can go through your code, what is missing is to inspect the values of the variables in your program, to do this let's use the watch command in the script we have used so far, the following example show how to use it:<br />
<br />
<i>$ node debug scriptDebug.js</i><br />
<i>< debugger listening on port 5858</i><br />
<i>connecting... ok</i><br />
<i>break in scriptDebug.js:1</i><br />
<i> 1 var sum = 0;</i><br />
<i> 2 </i><br />
<i> 3 for(i=0;i<10;i++) {</i><br />
<b><i>debug> watch('sum')</i></b><br />
<i>debug> cont</i><br />
<i>< Iteration:0, sum:0</i><br />
<i>break in scriptDebug.js:6</i><br />
<b><i>Watchers:</i></b><br />
<b><i> 0: sum = 0</i></b><br />
<i><br /></i>
<i> 4 <span class="Apple-tab-span" style="white-space: pre;"> </span>sum = sum + i;<span class="Apple-tab-span" style="white-space: pre;"> </span></i><br />
<i> 5 console.log('Iteration:' + i +', sum:' + sum);</i><br />
<i> 6 debugger;<span class="Apple-tab-span" style="white-space: pre;"> </span></i><br />
<i> 7 }</i><br />
<i> 8 </i><br />
<i>debug> cont</i><br />
<i>break in scriptDebug.js:6</i><br />
<i>< Iteration:1, sum:1</i><br />
<b><i>Watchers:</i></b><br />
<b><i> 0: sum = 1</i></b><br />
<i><br /></i>
<i> 4 <span class="Apple-tab-span" style="white-space: pre;"> </span>sum = sum + i;<span class="Apple-tab-span" style="white-space: pre;"> </span></i><br />
<i> 5 console.log('Iteration:' + i +', sum:' + sum);</i><br />
<i> 6 debugger;<span class="Apple-tab-span" style="white-space: pre;"> </span></i><br />
<i> 7 }</i><br />
<i> 8 </i><br />
<div>
<br /></div>
As you can see now every time a breakpoint is found the variable sum is printed with its value.<br />
<br />
With this tool you can easily go through your code, stop wherever you want and do many more things, you can find all the instructions in the following link:<br />
<br />
<a href="http://nodejs.org/api/debugger.html">http://nodejs.org/api/debugger.html</a><br />
<br />
The debbuger that comes with node.js is very powerful but still is a command based utility, there are debbugers with more visual help, lets use node inspector to have a visual aid to debug our script.<br />
<br />
First lets install globally node inspector, with the help of npm use the following command:<br />
<br />
<i>$ npm install -g node-inspector</i><br />
<br />
With node inspector installed let's start it with the following command:<br />
<br />
<i>$ node-inspector</i><br />
<i>Node Inspector v0.7.3</i><br />
<i>Visit http://127.0.0.1:8080/debug?port=5858 to start debugging.</i><br />
<div>
<br /></div>
With node inspector running in other terminal you have to start in debug mode your application with the following command:<br />
<br />
<i>$ node <b>--debug-brk </b>scriptDebug.js</i></div>
<i>debugger listening on port 5858</i><br />
<div>
<br /></div>
The --debug-brk option is a node inspector option which starts to debug the script and stops it in the first line.<br />
<br />
Now let's open a browser with url indicated "http://127.0.0.1:8080/debug?port=5858" by node inspector, you will see the following console:<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-zQF5kNNQ4LA/U5aTOFTYUtI/AAAAAAAAEE8/L_FFBIrCrmM/s1600/nodeinspector.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://1.bp.blogspot.com/-zQF5kNNQ4LA/U5aTOFTYUtI/AAAAAAAAEE8/L_FFBIrCrmM/s1600/nodeinspector.jpg" height="267" width="640" /></a></div>
<br />
As you can see the script is displayed and in the right side there is a window that displays all the information about the runtime values of the script, as in the upper right side there are some navigation buttons to go through the script.<br />
<br />
With node inspector the debugging of a script is made so much easier because it is a visual tool and all the commands are a click away.<br />
<br />
You can find more about node inspector in the following link:<br />
<a href="https://github.com/node-inspector/node-inspector">https://github.com/node-inspector/node-inspector</a><br />
<br />
This is a brief example of how to start using the debug tools of node.js and I hope it is useful to you.<br />
<br /></div>
<div>
<br />
<br /></div>
<div>
<br />
<br /></div>
Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com8tag:blogger.com,1999:blog-4213799477897003979.post-632745115161074872014-05-28T14:30:00.001-07:002015-08-12T19:50:33.995-07:00Websockets in Java EE 7 with wildflyIn the past few weeks I've trying the websockets technology introduced in JEE 7 and I would like to share you how to develop a simple example of it, for those who don't know what is about websockets, here is a brief introduction.<br />
<div>
<br /></div>
<div>
Wikipedia says "WebSocket is a protocol providing full-duplex communications channels over a single TCP connection", this means that in a client-server communication the client as the server can send a message leaving behind the request-response protocol, where the exchange is always initiated by the client (usually a browser) and the server cannot send any data without the client requesting it first.</div>
<div>
<br /></div>
<div>
It also says "WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application", websockets was introduced in the clients or browsers since the html5 specification, and in the Java servers since the JEE 7 version and the specification JSR 356.</div>
<div>
<br /></div>
<div>
If you want to know more about websockets refer to the following links:</div>
<div>
<a href="http://www.websocket.org/">http://www.websocket.org/</a></div>
<div>
<a href="http://en.wikipedia.org/wiki/WebSocket">http://en.wikipedia.org/wiki/WebSocket</a></div>
<div>
<a href="https://developer.mozilla.org/en/docs/WebSockets">https://developer.mozilla.org/en/docs/WebSockets</a></div>
<div>
<br /></div>
<div>
I'm going to use the wildfy 8 as server the open source version of jboss, you can download it from here <a href="http://wildfly.org/downloads/">http://wildfly.org/downloads/</a>, and as for the IDE I'm going to use JBoss tools, you can download it from here <a href="http://tools.jboss.org/downloads/">http://tools.jboss.org/downloads/</a> .<br />
<br />
To set up wildfly with eclipse you can use the following link for instructions: <a href="http://planet.jboss.org/post/getting_started_with_jboss_tools_and_wildfly_tech_tip_5">http://planet.jboss.org/post/getting_started_with_jboss_tools_and_wildfly_tech_tip_5</a><br />
<br />
Once you have everything installed and integrated lets start creating a websocket application.<br />
lets create a new project, select new project and from the options presented choose dynamic web project, set the name of the project as websockets and the target runtime to wildfy 8.<br />
<br />
The Java API for WebSocket consists of the following packages.<br />
<br />
<ul>
<li>The javax.websocket.server package contains annotations, classes, and interfaces to create and configure server endpoints.</li>
<li>The javax.websocket package contains annotations, classes, interfaces, and exceptions that are common to client and server endpoints.</li>
</ul>
<br />
Now lets create a new server endpoint class, this class will receive the messages from the client and also it could send messages to the client.</div>
<div>
<br />
<script src="https://gist.github.com/anonymous/573ea239966d720cf86e.js"></script>
<br />
From the class above notice the <complete id="goog_1815539736">@ServerEndpoint annotation, it indicates the class will be a socket endpoint, it takes a string ("example") as parameter this will be the URI of the endpoint.</complete><br />
<complete><br /></complete>
<complete>T</complete>he methods of the class are annotated with @OnOpen, @OnMessage, @OnClose annotations, these indicate the lifecycle of endpoint here is a brief description of them:<br />
<br />
<table border="1" cellpadding="3" cellspacing="0" class="HRuleFormal" dir="ltr" frame="hsides" rules="rows" style="background-color: white; color: #333333; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: small; line-height: 19.200000762939453px; width: 100%px;" summary="This table lists the annotations for methods that are invoked when an endpoint lifecyle event occurs." title="WebSocket Endpoint Lifecycle Annotations"><colgroup><col width="19%"></col><col width="27%"></col><col width="*"></col></colgroup><thead>
<tr align="left" valign="top"><th align="left" id="r1c1-t4" style="vertical-align: bottom;" valign="bottom">Annotation</th><th align="left" id="r1c2-t4" style="vertical-align: bottom;" valign="bottom">Event</th><th align="left" id="r1c3-t4" style="vertical-align: bottom;" valign="bottom">Example</th></tr>
</thead><tbody>
<tr align="left" valign="top"><td align="left" headers="r1c1-t4" id="r2c1-t4" style="vertical-align: top;"><code style="font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; font-size: 13px; white-space: pre-wrap; word-wrap: break-word;">OnOpen</code><a href="https://www.blogger.com/null" id="sthref1268" name="sthref1268"></a></td><td align="left" headers="r2c1-t4 r1c2-t4" style="vertical-align: top;">Connection opened</td><td align="left" headers="r2c1-t4 r1c3-t4" style="vertical-align: top;"><pre class="oac_no_warn" style="font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; font-size: 13px; white-space: pre-wrap; word-wrap: break-word;" xml:space="preserve">@OnOpen
public void open(Session session,
EndpointConfig conf) { }
</pre>
</td></tr>
<tr align="left" valign="top"><td align="left" headers="r1c1-t4" id="r3c1-t4" style="vertical-align: top;"><code style="font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; font-size: 13px; white-space: pre-wrap; word-wrap: break-word;">OnMessage</code><a href="https://www.blogger.com/null" id="sthref1269" name="sthref1269"></a></td><td align="left" headers="r3c1-t4 r1c2-t4" style="vertical-align: top;">Message received</td><td align="left" headers="r3c1-t4 r1c3-t4" style="vertical-align: top;"><pre class="oac_no_warn" style="font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; font-size: 13px; white-space: pre-wrap; word-wrap: break-word;" xml:space="preserve">@OnMessage
public void message(Session session,
String msg) { }
</pre>
</td></tr>
<tr align="left" valign="top"><td align="left" headers="r1c1-t4" id="r4c1-t4" style="vertical-align: top;"><code style="font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; font-size: 13px; white-space: pre-wrap; word-wrap: break-word;">OnError</code><a href="https://www.blogger.com/null" id="sthref1270" name="sthref1270"></a></td><td align="left" headers="r4c1-t4 r1c2-t4" style="vertical-align: top;">Connection error</td><td align="left" headers="r4c1-t4 r1c3-t4" style="vertical-align: top;"><pre class="oac_no_warn" style="font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; font-size: 13px; white-space: pre-wrap; word-wrap: break-word;" xml:space="preserve">@OnError
public void error(Session session,
Throwable error) { }
</pre>
</td></tr>
<tr align="left" valign="top"><td align="left" headers="r1c1-t4" id="r5c1-t4" style="vertical-align: top;"><code style="font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; font-size: 13px; white-space: pre-wrap; word-wrap: break-word;">OnClose</code><a href="https://www.blogger.com/null" id="sthref1271" name="sthref1271"></a></td><td align="left" headers="r5c1-t4 r1c2-t4" style="vertical-align: top;">Connection closed</td><td align="left" headers="r5c1-t4 r1c3-t4" style="vertical-align: top;"><pre class="oac_no_warn" style="font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; font-size: 13px; white-space: pre-wrap; word-wrap: break-word;" xml:space="preserve">@OnClose
public void close(Session session,
CloseReason reason) { }
</pre>
<div>
<br /></div>
</td></tr>
</tbody></table>
<complete><br /></complete>
<br />
<complete><br /></complete>
<complete>The endpoint now </complete>is ready to start a conversation so deploy it in wildfy and lets create a html client to communicate with this endpoint.<br />
<br />
<script src="https://gist.github.com/anonymous/043579bac0c1254149ee.js"></script>
<br />
In the previous html file the only thing to notice is the simple script that creates a connection to the endpoint, from the url "ws://localhost:8080/websockets/example" used check the name of the application and the URI of the endpoint.<br />
<br />
If you open the html file on browser that supports web sockets you should see the message "Web Socket is connected!!" and in the server you should see in console the message "Open session:...". This indicates that the communication has been established between the client and the server.<br />
<br />
To now more about the WebSocket javascript interface the following link will help:<br />
<a href="http://www.w3.org/TR/2011/WD-websockets-20110419/">http://www.w3.org/TR/2011/WD-websockets-20110419/</a><br />
<br />
Let's create a message and send it from the client to the server. To do this let's just add the following function in the javascript section of the html file.<br />
<br />
<script src="https://gist.github.com/anonymous/5a9e3815a17cca258b49.js"></script>
<br />
With this function the ws variable calls the sends() method and sends the message to the server.<br />
To call this function just add a html link and call it.<br />
<br />
<script src="https://gist.github.com/anonymous/089cb739ab399cd14d5d.js"></script>
<br />
Let's test it click on the link and you should see the following message on server's console: "Received : Message to server from client, session:..."<br />
<br />
Now to simulate a request-response communication lets return a message from the @OnMessage method in the websocket endpoint in the server.<br />
<br />
<script src="https://gist.github.com/anonymous/8188f71cd0c4e62ac4d7.js"></script>
<br />
Deploy it and test it, you should get the following sequence of messages:<br />
<br />
<ol>
<li>Browser displays "Web sockect is connected".</li>
<li>After calling send(), server console diplays: Received : Message to server from client, session:</li>
<li>Browser displays "Received, Response from the server"</li>
</ol>
<div>
To demonstrate full duplex communication lets send messages from the server without any request from the client. To do this, lets add and asynchronous task to send messages.</div>
<div>
<br /></div>
<script src="https://gist.github.com/anonymous/62c6a111e7b02b1b722b.js"></script>
<br />
<div>
<br /></div>
Notice that the @Stateless annotation has been added to the endpoint, it is required to send messages asynchronously, with this now the endpoint is also an EJB, also the endpoint makes use of the ManagedExecutorService resource, it takes runnables and executes them, this is done on the @OnOpen method so when the conversation starts the runnables are set.<br />
In the runnable we wait for 10 seconds and then sends a message to the client this is done without receiving any previous message and this is repeated 3 times so during 30 seconds, your browser should be receiving the message "Received, Message from server".<br />
<br />
With this is demonstrated the full-duplex communication this is a message can be sent without any prior message or request.<br />
<br />
Well this is basically a simple example that demonstrates how web sockets work, in further post I will keep showing more of their functionality. </div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
</div>
<div>
<br /></div>
<div>
<br /></div>
Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com8tag:blogger.com,1999:blog-4213799477897003979.post-25361676870291132042014-04-13T16:18:00.000-07:002014-04-16T08:23:43.739-07:00Different ways to run scripts in node.jsWell now I have some weeks learning node, the easiest way to run a script is through the node command, lets start with a simple script:<br />
<div>
<br /></div>
<script src="https://gist.github.com/anonymous/10507948.js"></script>
<br />
<div>
<br /></div>
<div>
Save it as server.js If you want to run this script all you have to do is go to the directory where the script is and run the following command:</div>
<div>
<br /></div>
<div>
<b>node server.js</b><br />
<br />
Another way to run a script is through the npm command, it requires a file named package.json at the root of the project, this way is more sophisticated because in the package.json file you can specify a command to run a script, so you can have several commands each one mapped to a script.<br />
Also it helps to configure dependencies, versions and a lot of other stuff, you can find more about the package.json configuration in the following link:<br />
<a href="https://www.npmjs.org/doc/json.html">https://www.npmjs.org/doc/json.html</a><br />
<br />
Well for the purpose of the blog the file package.json will be very simple just to show how it works, so it will contain the following:<br />
<br />
<script src="https://gist.github.com/anonymous/10508860.js"></script>
<br />
In the file the start command is mapped to the server.js script, once the file is saved in the directory where sript is located the following command will run the script:<br />
<br />
<b>npm start</b><br />
<br />
Another way to run a script is with the help of packages one of them is nodemon (<a href="http://nodemon.io/">http://nodemon.io/</a>), it stands for node monitor.<br />
<br />
The description of nodemon says that it is a utility that will monitor for any changes in your source and automatically restart your server. Perfect for development. Using nodemon instead of node to run your code, and now your process will automatically restart when your code changes.<br />
<br />
To install nodemon jus run the following command:<br />
<br />
<b>npm install -g nodemon</b><br />
<br />
The -g means that it will install nodemon in a global way, you don't have to install it for every project.<br />
<br />
Once installed you can see it working, just replace the node command for nodemon and run the script:<br />
<br />
<b>nodemon server.js</b><br />
<br />
To see it working type the address http://127.0.0.1:1337/ in your browser and see the output, then modify the script to output instead "Hello world" to something else, reload the browser and see that the changes are reflect, so this is the big advantage of using nodemon you don't have to waste any time running the scripts while developing them.<br />
<br />
Another package that does the same as nodemon is run (<a href="https://www.npmjs.org/package/run">https://www.npmjs.org/package/run</a>), install it just like nodemon:<br />
<br />
<b>npm install -g run</b><br />
<br />
Then run the script with the run command<br />
<br />
<b>run server.js</b><br />
<b><br /></b>
Do the same exercise go the address http://127.0.0.1:1337/ see the output and modify the script, reload the page and see the changes.<br />
<b><br /></b>
So far in my way to node these are the different ways to run scripts, I hope you can learn something new from it.<br />
<br /></div>
Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com5tag:blogger.com,1999:blog-4213799477897003979.post-49964342918670524572014-03-21T11:36:00.007-07:002014-03-21T12:11:43.177-07:00Creating processes in node.js In some of my previous posts I started comparing some of the features of node.js with java and since then my interest has started to grow for node.js.<br />
<br />
One thing I just learned is that node runs in a single thread mode, it uses an event-driven paradigm to handle concurrency.<br />
<br />
Well that's fine but what about parallel processes how can you take advantage of this when you are in a single thread program, well node.js has some mechanisms to create processes and take advantage of parallel computing, and I will tell you how.<br />
<br />
First we will need a process to run as a worker, there could be many instances running of this process at the same time.<br />
<br />
<script src="https://gist.github.com/anonymous/9632620.js"></script>
For the purpose of this blog this process will have just a log to console, also any kind of process can be created not just node process, but also for the blog I will use just this.<br />
<br />
For creating a child process the <b><i>child_process module</i></b> is required, this module has different ways to create process.<br />
<br />
The <b>exec</b> method of the child_process runs a command in a shell and buffers the output. It has the following signature:<br />
<br />
child_process.exec(command, [options], callback)<br />
<br />
<script src="https://gist.github.com/anonymous/9633179.js"></script>
<br />
In the example the command "node worker.js i" is executed where i is a parameter passed to the process.<br />
Also a callback function is passed and it is called when the process terminates and allows to read and process the output from it.<br />
<br />
After running the example the following should be printed in console for each process created.<br />
<br />
stdout: Process 0 at work<br />
stderr:<br />
<div>
<br /></div>
Child process exited with exit code 0<br />
<br />
The <b>spawn</b> method of the child_process module launches a new process with a given command, it has the following signature:<br />
<br />
child_process.spawn(command, [args], [options])<br />
<br />
<script src="https://gist.github.com/anonymous/9676638.js"></script>
<br />
After running the example the following should be printed in console for each process created.<br />
<div>
<br /></div>
stdout: Process 0 at work<br />
<br />
child process exited with code 0<br />
<div>
<br /></div>
Exec() and spawn() both create processes, but they differ in what they return, spawn returns streams (stdout & stderr), while exec returns a buffer with a max size. Spawn() should be used when the process returns large amount of data.<br />
<br />
Another difference is that spawn() starts receiving the response as soon as the process starts executing, and exec() otherwise waits for the process to end and tries to return all the buffered data at once<br />
<br />
The <b>fork</b> method is a special case of the spawn() functionality, it only creates Node processes. Its signature is the following:<br />
<br />
<br />
child_process.fork(modulePath, [args], [options])<br />
<br />
<script src="https://gist.github.com/anonymous/9692069.js"></script>
After running the example the following should be printed in console for each process created.<br />
<br />
Process 0 at work<br />
child process exited with code 0<br />
<div>
<br />
Node.js also has the <b><i>cluster module</i></b> and also allows to create processes, the definition of the cluster module says: "A single instance of Node runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node processes to handle the load".<br />
<br />
<script src="https://gist.github.com/anonymous/9692452.js"></script>
</div>
From the example you can notice that the cluster module is imported, once imported you can call <b>fork() </b>method to create a new child process, after calling fork() the same process will run but as a child, to distinguish if the process is running as a Master or child the cluster module has the <b>isMaster()</b> and <b>isWorker()</b> methods.<br />
<br />
After running the example above, the following should be printed.<br />
<br />
Master Forking!!!!<br />
Worker 4984 is online.<br />
....<br />
Child process running!!!<br />
....<br />
<br />
<br />
You can find more information about these modules in the following links:<br />
<a href="http://nodejs.org/api/child_process.html">http://nodejs.org/api/child_process.html</a><br />
<a href="http://nodejs.org/api/cluster.html">http://nodejs.org/api/cluster.html</a><br />
<br />
Node.js says that runs in a single thread mode, but as with this brief example, I show that node.js has different mechanisms to create processes and to take advantage of multiple processors.<br />
<br />
<br />
<br />
<br />
<br />Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com49tag:blogger.com,1999:blog-4213799477897003979.post-65333155390759681522014-02-07T15:26:00.001-08:002014-03-21T12:11:57.076-07:00Restful web services in node.jsIn my latest blog <a href="http://jlunaquiroga.blogspot.com/2014/01/restful-web-services-with-jetty-and.html">restful web services with jetty and jersey</a> I was trying to create rest web services simple as node.js, so I decide to show you how simple is to write this services with node.js.<br />
<br />
First you will need node installed, you can install it from here <a href="http://nodejs.org/">nodejs.org</a>, I'm going to use the express framework (<a href="http://expressjs.com/">expressjs.com</a>) for node to help me develop the services, so to install express just go to the folder in which your projects will reside and with the help of the npm (node packaged modules) type the following command:<br />
<br />
<b>[jluna@host projects]$ npm install express</b><br />
<br />
With this the express framework will be installed locally at your projects folder, now you can start creating the restful web services, first create a file in the projects folder for example services.js.<br />
<br />
To use express use the following:<br />
<br />
<script src="https://gist.github.com/anonymous/8873546.js"></script>
<br />
Once imported express to create a service just use one of its methods like this:<br />
<br />
<script src="https://gist.github.com/anonymous/8873625.js"></script>
Finally, just configure the port and listen:<br />
<br />
<b>app.listen(process.env.PORT || 9999);</b><br />
<br />
So here it is the whole script that contains the services:<br />
<br />
<script src="https://gist.github.com/anonymous/8873490.js"></script>
<br />
<br />
As you can see the first service receives a parameter, this is specified in the path '/employee/getEmployee/:name', and to obtain the value of the parameter just get it from the request:<br />
<br />
<b>var name = req.params.name;</b><br />
<br />
In javascript to create objects you don't have to define a class like in java just specify its properties when the object is created:<br />
<br />
<b>employee = new Object();</b><br />
<b> employee.name = name;</b><br />
<b> employee.age = 25;</b><br />
<b> employee.deparment = "HR";</b><br />
<b> employee.wage = 15000.00;<span class="Apple-tab-span" style="white-space: pre;"> </span></b><br />
<br />
This has its benefits and its risks but I won't get into there, also there are other ways in javascript to create objects, you can define a function.<br />
<br />
Finally to send the response to the client the json() method is used to parse the objects to json:<br />
<br />
<b>res.json(employee);</b><br />
<br />
In the post method the interesting thing to see is that it is receiving an object, to access this object just get it from the body<br />
<br />
<b>var employee = req.body;</b><br />
<br />
And then you can access the object like this:<br />
<br />
<b>console.log("Got name: " + employee.name);</b><br />
<br />
Well to run the script just use the following command in the path where the script is:<br />
<br />
<b> [jluna@host projects]$ node services.js</b><br />
<br />
And the script should be up and running.<br />
<br />
To test the script you can use the following commands:<br />
<br />
<b>curl -i -X GET -H 'Content-Type: application/json' http://localhost:9999/employee/getEmployee/James</b><br />
<br />
<b>curl -i -X POST -H 'Content-Type: application/json' -d '{"address": {"city": "Massachusetts","state": "Springfield","street": "Evergreen","zip": "66450"},"age": "25","deparment": "HR","name": "James","salary": "0.0"}' http://localhost:9999/employee/postEmployee</b><br />
<br />
In the console you should see the output, also here it is a java client you can use:<br />
<br />
<script src="https://gist.github.com/anonymous/8873928.js"></script>
<br />
As you can see is very simple to create the services in node.js.Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com8tag:blogger.com,1999:blog-4213799477897003979.post-9065052564919078182014-01-20T16:06:00.000-08:002014-04-16T08:24:06.915-07:00RESTful web services with jetty and jerseyRecently I was thinking if there is a way to start a web server in java just as easy as it is in node.js, if you don't know node.js you can check this link <a href="http://nodejs.org/">nodejs.org</a>, so in node you just write a few lines and you have a server like this:<br />
<br />
<script src="https://gist.github.com/anonymous/8525374.js"></script>
<br />
<div>
I thought that with something like this you can easily test your code without the burden of deploy it, and also saving some resources. </div>
<div>
<br /></div>
<div>
So I start looking if there is something similar in java and I found several projects to start a web server or a minimal server, but I decided to go with jetty <a href="http://www.eclipse.org/jetty/">www.eclipse.org/jetty</a>, so I'm going to show you how to run some restful web services using jetty. </div>
<div>
<br /></div>
<div>
Also I'm going to use jersey <a href="https://jersey.java.net/">jersey.java.net</a> which simplifies the development of RESTful Web services and their clients in Java.<br />
<br />
So you can download the jars from these projects or configure them through maven to your project to start using them, in these links <a href="http://www.eclipse.org/jetty/">www.eclipse.org/jetty</a> , <a href="https://jersey.java.net/">jersey.java.net</a> you can check the instructions to do it.<br />
<br />
So to create a web server with jetty is as easy as the following code:<br />
<br />
<script src="https://gist.github.com/anonymous/8525679.js"></script>
<br />
If you run the code and check the <a href="http://localhost:8080/hello">http://localhost:8080/hello</a> url you can see that your servlet is running, so basically in the code you create a Server object and set the port the Servlets and the servlets to run and that's it.<br />
<br />
With jetty you can do much more than this, but for the purpose of this blog I will no go further, you can check the jetty documentation.<br />
<br />
The following would be to create and deploy the RESTful web services, now we will use jersey to this.<br />
<br />
The first thing to do is to create the services that we will deploy, for the example I will create two services one using JSON and other using XML, I will create two objects used to transfer the data.<br />
<br />
<script src="https://gist.github.com/anonymous/8525715.js"></script>
<br />
<div>
<br /></div>
<div>
In the classes above you can see two classes Employee with a nested class Address and Student, the only thing to notice from these classes are the annotations @XmlRootElement and @XmlAttribute, these annotations are used to do the parsing from object to the protocol used (XML, JSON) and from protocol to object.</div>
<div>
<br /></div>
<div>
The following would be to create the classes for the services.</div>
<div>
<br /></div>
<script src="https://gist.github.com/anonymous/8525956.js"></script>
<br />
<div>
<br /></div>
<div>
<br /></div>
The classes above use the standard Java EE specification for RESTful web services they use the @Path annotation at the top level to set the service path and each method use the @GET, @POST annotations to describe the type of service and the @Produces annotation to set the type of protocol to use.<br />
<br />
The method getStudent of the class XMLStudentSvc has also the @Path("/student/{name}") this specifies a path for this method, also note that it receives a parameter named "name" through the path and this parameter will be mapped to the parameter of the method.<br />
For more about how define RESTful web services check the specification <a href="https://jcp.org/en/jsr/detail?id=311">https://jcp.org/en/jsr/detail?id=311</a><br />
<br />
Another thing to notice is that both classes are in a package called "rest", so the following to do would be to deploy these services in jetty as long as the jersey configuration.<br />
<br />
This is the class for the server:<br />
<br />
<script src="https://gist.github.com/anonymous/8526070.js"></script>
<br />
<div>
<br />
See in the class above all what it needs to configure jersey, a ServletHolder object is created to set the parameters, note that is indicated the package where the services are located and jersey will automatically deploy them. The ServletHolder object is passed to a ServletContextHandler object, and that's it with this the services should be up and running.</div>
<br />
The last thing to do is to create a client for our services, for the client I will use jersey to help. <br />
<br />
This is the client for the JSON service:<br />
<br />
<script src="https://gist.github.com/anonymous/8526122.js"></script>
<br />
The client will call two methods, the first will be to the GET method and it uses the url with the path specified for this method ("http://localhost:9999/employee/getEmployee"), this method returns a response in JSON, then this response is unmarshal to a object with the call to "response.getEntity(Employee.class)".<br />
<br />
If the JSON response is needed instead of the actual object all what is need to do is change the type to String in the unmarshal "response.getEntity(Employee.class)".<br />
<br />
The other method specified in this client is the POST method this call doesn't return a thing, it uses the url with the path specified for this method ("http://localhost:9999/employee/postEmployee") and it sends back the same object the client is receiving, you should see an output in the server since the service method is printing the object it is receiving.<br />
<br />
This is the client for the XML service:<br />
<br />
<script src="https://gist.github.com/anonymous/8526141.js"></script>
<br />
It is almost the same as the JSON client, the only difference is that a parameter is include in the url "http://localhost:9999/xmlServices/student/James", because the service is expecting it.<br />
<br />
After running these examples I notice how easy and fast is to run the services and the few resources that required, I'm using at most 30Mb of memory.<br />
<br /></div>
Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com165tag:blogger.com,1999:blog-4213799477897003979.post-67880913743242098222014-01-06T16:19:00.000-08:002014-03-27T11:22:07.719-07:00JDK 7 securtiy issues with web startWith the latest updates java increased its security and new features were added to the web start applications, so basically if you have a web start application and is not properly signed it will not run over the latest version of the JVM (1.7.45), giving you a warning like the following, and more errors.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-88fy4JOVCTg/UstFMA_c-EI/AAAAAAAADWI/B0wdbVmF4DA/s1600/warning.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/-88fy4JOVCTg/UstFMA_c-EI/AAAAAAAADWI/B0wdbVmF4DA/s1600/warning.jpg" height="263" width="400" /></a></div>
<br />
<br />
This is what happened to me and I will explain what I had to do to get over this new security requirements and kept your application running.<br />
<br />
The first step is get a code signing certificate with an certificate authority (CA), there are different CA and here are some of them:<br />
<ul>
<li><a href="https://www.digicert.com/order/order-1.php">www.digicert.com</a></li>
<li><a href="https://www.globalsign.com/developers/">www.globalsign.com</a></li>
<li><a href="http://www.symantec.com/code-signing?inid=vrsn_symc_cs_index&searchdomain=google.com&searchterms=">www.symantec.com</a></li>
<li><a href="http://www.godaddy.com/ssl/code-signing-certificate.aspx?ci=13314&isc=cjcdplink">www.godaddy.com</a></li>
</ul>
<div>
The process to get the certificate is the following:<br />
<br />
First you will have to request the CA for a certificate, and for this you will need a Keystore and a Certificate Signing Request (CSR), these are generated with the keytool.<br />
<br />
For generate the keystore use the following command:<br />
<br />
keytool -genkey -alias Alias -keyalg RSA -keysize 2048 -keystore Keysotre.jks<br />
<div>
<br /></div>
<div>
And for generate the CSR use the following command:</div>
<div>
<br /></div>
<div>
keytool -certreq -alias Alias -file Cert.csr -keystore Keysotre.jks </div>
<div>
<br /></div>
<div>
Each command will ask you for a password, after generating these files you will send the CSR file to the CA.</div>
<div>
<br /></div>
<div>
After the CA generates the certificate, it will send you the certificate, it is a file with probably one of the following extensions: PEM, DER, P7B, PFX, depending in the type of certificate, you can find more about the certificate types in this link: <a href="https://www.sslshopper.com/ssl-converter.html">www.sslshopper.com/ssl-converter.html</a></div>
<div>
<br /></div>
<div>
Once you have the certificate with you, you will have to import it using the keytool, with the following command:</div>
<div>
<br /></div>
<div>
keytool -import -trustcacerts -alias Alias -file CAcert.p7b -keystore Keysotre.jks</div>
<div>
<br /></div>
<div>
Make sure you use the same keystore file used in the generation of the CSR file. You can find more information of the keytool command in the following link:</div>
<div>
<a href="http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html">docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool</a></div>
<div>
<br /></div>
<div>
With this the jars files can be signed using the jarsigner command:</div>
<div>
<br /></div>
<div>
jarsigner -keystore Keysotre.jks -storepass password file.jar Alias</div>
<div>
<br /></div>
<div>
With these steps the jar file gets signed, but there is much more about this process of signing a jar.</div>
<div>
<br /></div>
<div>
Before the new features that were added in the latest releases of the JVM (1.7.XX) this was all you have to do to meet the security requirements for a web start application just sign the jars of the application.</div>
<div>
<br /></div>
<div>
These are some of the new features:</div>
<div>
<br /></div>
<div>
The META-INF/MANIFEST.MF file of the jar files must have the following attributes to grant permissions</div>
<div>
<br /></div>
<div>
<div>
Manifest-Version: 1.0</div>
<div>
Permissions: all-permissions</div>
<div>
Codebase: https://example.com</div>
</div>
<div>
<br /></div>
<div>
In this link you can find the new attributes of the Manifest file <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/manifest.html">http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/manifest.html</a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
Another feature is to sign the JNLP file, the oracle documents says the following in order to sign a JNLP file: </div>
<div>
<br /></div>
<div>
"To create a signed JNLP file you don't sign the JNLP file itself, but you include the JNLP file inside the directory structure before the JAR file is created and then signed. The JNLP file must be named APPLICATION.JNLP and is included in the JNLP-INF subdirectory. The JAR file is then created and signed in the usual manner. When a web start application is started, the JNLP file used must be identical to the JNLP file in the signed JAR in order for the application to run".</div>
<div>
<br /></div>
<div>
You can find more information about signing JNLP files in the following link: <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/signedJNLP.html">http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/signedJNLP.html</a></div>
<div>
<br /></div>
<div>
Well these are some of the new requirements in order to run properly a web start application, I hope with this blog you can now have an idea of what to do if your web start application does not run because of security issues.</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
</div>
Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com2tag:blogger.com,1999:blog-4213799477897003979.post-67819180557753683132013-10-16T14:58:00.003-07:002014-03-27T11:22:15.125-07:00UDDI: Universal Description, Discovery, and Integration<br />
<h2 class="western">
</h2>
<div style="margin-bottom: 0in;">
I recently found out about this
protocol I never heard of, so I decided to write a post about it to
share it with you.
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
If you want to implement a Service
Oriented Architecture UDDI will help a lot to implement it, most of
the Enterprise Service Bus solutions that are in the market implement
this protocol.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>Introduction </b>
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
UDDI is a standard for publishing and discovering information about web services, it behaves as a directory service for describing services, discovering businesses, and integrating business services. </div>
<div style="margin-bottom: 0in;">
It defines a group of Web services and programmatic interfaces for publishing, retrieving, and managing information about services. (In true SOA fashion, a UDDI registry is itself composed of Web services!) </div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
It is a protocol developed by <a href="https://www.oasis-open.org/committees/tc_home.php?wg_abbrev=uddi-spec">OASIS</a>, It focuses on the process of discovery in the service-oriented architecture, so most of the Enterprise Service Bus implements this standard.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
UDDI registry can have three types of information white pages, yellow pages and green pages:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<ul>
<li>White pages: Basic contact information and identifiers, such as business name, address. </li>
</ul>
<br />
<div style="margin-bottom: 0in;">
</div>
<ul>
<li>Yellow pages: Information that describes a web service using different categorizations, such as business type manufacturing.</li>
</ul>
<br />
<div style="margin-bottom: 0in;">
</div>
<ul>
<li>Green pages: Technical information that describes the behaviors and supported functions of a web service hosted by your business.</li>
</ul>
<br />
<div>
Developers use the UDDI to publish services and query the registry to discover services matching various criteria., they can query one or more UDDI registries to view the different businesses that expose web services and the specifications of those services.</div>
<div>
<div>
<br /></div>
<div>
<b>Architecture</b></div>
<div>
<br /></div>
<div>
The UDDI Business Registry (UBR) or the Public Cloud, is built from multiple nodes that has their data synchronized through replication, so each node has the same information.</div>
</div>
<div style="margin-bottom: 0in;">
</div>
<div>
<br /></div>
<div>
Content inserted into the UBR is done at a single node, and that operator node becomes the master owner of that content. Any subsequent updates or deletes of the data must occur at the operator node where the data was inserted.</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGrQrQHUBd5LPCLgUJl7BgXcgltq_PcvW71nMgNH-gkG_3b19FaLtDVUoYbnBkmNapYTywEEHhpPpkwzUXrB7PsLQjjh6beTsIDRVlYCrdnzGv-zJxrwv_bocgTbbrAsiHWIZYVM6Hi5WB/s1600/UDDI.gif" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGrQrQHUBd5LPCLgUJl7BgXcgltq_PcvW71nMgNH-gkG_3b19FaLtDVUoYbnBkmNapYTywEEHhpPpkwzUXrB7PsLQjjh6beTsIDRVlYCrdnzGv-zJxrwv_bocgTbbrAsiHWIZYVM6Hi5WB/s1600/UDDI.gif" height="319" width="400" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<br />
<div>
Private nodes can be created too forming a private cloud, these nodes do not have data synchronized with the UBR they just have information replicated between them.</div>
<div>
<div>
<br /></div>
<div>
<b>Specifications</b></div>
<div>
<br /></div>
<div>
UDDI builds upon several other established industry standards, including HTTP, XML, XML Schema (XSD), SOAP, and WSDL.</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgG-PZn74PtLCsHLiZj_T8d0jtbXv_D0Gm1OOJVHgInNOGok8EBreLLdtX_TcmBtTalN6l4mWRCkIU3BgxvcgpyT-Vd9GSCcEzdfT_LIXQHcRvBrotFsNyKCylwdFk2OWwvRzJD5bxd7WSE/s1600/UDDI_spec.gif" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgG-PZn74PtLCsHLiZj_T8d0jtbXv_D0Gm1OOJVHgInNOGok8EBreLLdtX_TcmBtTalN6l4mWRCkIU3BgxvcgpyT-Vd9GSCcEzdfT_LIXQHcRvBrotFsNyKCylwdFk2OWwvRzJD5bxd7WSE/s1600/UDDI_spec.gif" height="363" width="400" /></a></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<div>
UDDI defines a set of XML Schema definitions that describe the data formats used by the various specification APIs.</div>
<div>
UDDI Version 3.0.2 XML Schema. UDDI uses the XML Schema Language to formally describe its data structures. UDDI Version 3.0.2 XML Schema is provided by these files:</div>
</div>
<div>
<div>
<ul>
<li>UDDI API Schema: <a href="http://uddi.org/schema/uddi_v3.xsd">http://uddi.org/schema/uddi_v3.xsd</a></li>
<li>UDDI Custody Schema: <a href="http://uddi.org/schema/uddi_v3custody.xsd">http://uddi.org/schema/uddi_v3custody.xsd</a></li>
<li>UDDI Subscription Schema: <a href="http://uddi.org/schema/uddi_v3subscription.xsd">http://uddi.org/schema/uddi_v3subscription.xsd</a></li>
<li>UDDI Subscription Listener Schema: <a href="http://uddi.org/schema/uddi_v3subscriptionListener.xsd">http://uddi.org/schema/uddi_v3subscriptionListener.xsd</a></li>
<li>UDDI Replication Schema: <a href="http://uddi.org/schema/%20uddi_v3replication.xsd">http://uddi.org/schema/ uddi_v3replication.xsd</a></li>
<li>UDDI Value Set Validation Schema: <a href="http://uddi.org/schema/uddi_v3valueset.xsd">http://uddi.org/schema/uddi_v3valueset.xsd</a></li>
<li>UDDI Value Set Caching: <a href="http://uddi.org/schema/uddi_v3valuesetcaching.xsd">http://uddi.org/schema/uddi_v3valuesetcaching.xsd</a></li>
<li>UDDI Policy: <a href="http://uddi.org/schema/uddi_v3policy.xsd">http://uddi.org/schema/uddi_v3policy.xsd</a></li>
<li>UDDI Policy Instance Parameters: <a href="http://uddi.org/schema/uddi_v3policy_instanceParms.xsd">http://uddi.org/schema/uddi_v3policy_instanceParms.xsd</a></li>
</ul>
</div>
</div>
<div>
<br /></div>
<div>
<div>
UDDI Version 3.0.2 WSDL Service Interface Descriptions. The complete set of UDDI Version 3.0.2 WSDL definitions is provided by these files:</div>
<div>
<ul>
<li>UDDI API Binding: <a href="http://uddi.org/schema/uddi_api_v3_binding.wsdl">http://uddi.org/schema/uddi_api_v3_binding.wsdl</a></li>
<li>UDDI API Port Type: <a href="http://uddi.org/schema/uddi_api_v3_portType.wsdl">http://uddi.org/schema/uddi_api_v3_portType.wsdl</a></li>
<li>UDDI Custody Binding: <a href="http://uddi.org/schema/uddi_custody_v3_binding.wsdl">http://uddi.org/schema/uddi_custody_v3_binding.wsdl</a></li>
<li>UDDI Custody Port Type: <a href="http://uddi.org/schema/uddi_custody_v3_portType.wsdl">http://uddi.org/schema/uddi_custody_v3_portType.wsdl</a></li>
<li>UDDI Replication Binding: <a href="http://uddi.org/schema/uddi_repl_v3_binding.wsdl">http://uddi.org/schema/uddi_repl_v3_binding.wsdl</a></li>
<li>UDDI Replication Port Type: <a href="http://uddi.org/schema/uddi_repl_v3_portType.wsdl">http://uddi.org/schema/uddi_repl_v3_portType.wsdl</a></li>
<li>UDDI Subscription Binding: <a href="http://uddi.org/schema/uddi_sub_v3_binding.wsdl">http://uddi.org/schema/uddi_sub_v3_binding.wsdl</a></li>
<li>UDDI Subscription Port Type: <a href="http://uddi.org/schema/uddi_sub_v3_portType.wsdl">http://uddi.org/schema/uddi_sub_v3_portType.wsdl</a></li>
<li>UDDI Subscription Listener Binding: <a href="http://uddi.org/schema/uddi_subr_v3_binding.wsdl">http://uddi.org/schema/uddi_subr_v3_binding.wsdl</a></li>
<li>UDDI Subscription Listener Port Type: <a href="http://uddi.org/schema/uddi_subr_v3_portType.wsdl">http://uddi.org/schema/uddi_subr_v3_portType.wsdl</a></li>
<li>UDDI Value Set Validation Binding: <a href="http://uddi.org/schema/uddi_vs_v3_binding.wsdl">http://uddi.org/schema/uddi_vs_v3_binding.wsdl</a></li>
<li>UDDI Value Set Validation Port Type: <a href="http://uddi.org/schema/uddi_vs_v3_portType.wsdl">http://uddi.org/schema/uddi_vs_v3_portType.wsdl</a></li>
<li>UDDI Value Set Caching Binding: <a href="http://uddi.org/schema/uddi_vscache_v3_binding.wsdl">http://uddi.org/schema/uddi_vscache_v3_binding.wsdl</a></li>
<li>UDDI Value Set Caching Port Type: <a href="http://uddi.org/schema/uddi_vscache_v3_portType.wsdl">http://uddi.org/schema/uddi_vscache_v3_portType.wsdl</a></li>
</ul>
<div>
<div>
What you can do with these documents:</div>
<div>
<br /></div>
<div>
<b>UDDI replication</b></div>
<div>
<br /></div>
<div>
This document describes the data replication processes and interfaces to which a registry operator must conform to achieve data replication between sites. This specification is not a programmer's API; it defines the replication mechanism used among UBR nodes.</div>
<div>
<br /></div>
<div>
<b>UDDI operators</b></div>
<div>
<br /></div>
<div>
This document outlines the behavior and operational parameters required by UDDI node operators. This specification defines data management requirements to which operators must adhere. For example, node operators are responsible for durable recording and backup of all data, ensuring that each business registration has a valid email address associated with it, and the integrity of the data during deletions (e.g., deleting a business means that all of its service entries must also be deleted). This document is not a programmer's API and private registries are not required to support it.</div>
<div>
<br /></div>
<div>
<b>UDDI Programmer's API</b></div>
<div>
<br /></div>
<div>
This specification defines a set of functions that all UDDI registries support for inquiring about services hosted in a registry and for publishing information about a business or a service to a registry. This specification defines a series of SOAP messages containing XML documents that a UDDI registry accepts, parses, and responds to. This specification, along with the UDDI XML API schema and the UDDI Data Structure specification, makes up a complete programming interface to a UDDI registry.</div>
<div>
<br /></div>
<div>
<b>UDDI data structures</b></div>
<div>
<br /></div>
<div>
This specification covers the specifics of the XML structures contained within the SOAP messages defined by the UDDI Programmer's API. This specification defines five core data structures and their relationships to one another.</div>
<div>
<br /></div>
<div>
So this is a brief introduction to UDDI protocol so in case you heard of it you can know what is all about.</div>
<div>
<br /></div>
<div>
</div>
</div>
</div>
</div>
Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com2tag:blogger.com,1999:blog-4213799477897003979.post-29211141229001034892013-08-19T21:34:00.001-07:002014-03-27T11:22:27.970-07:00JAVA EE SERVERS<div lang="en-US" style="margin-bottom: 0in;">
<b>JAVA EE SERVERS</b></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
I recently notice that
Jboss changed the name of its community server version from JBoss AS
to Wildfly. It took me some time to understand what was all the fuzz
about, first I thought it was a new server but then I finally get it,
Red hat was just making a bigger distinction between the JBoss supported
(Jboss EAP) and community (now Wildfly) version nothing else, just
like red hat and fedora.
</div>
<div lang="en-US" style="margin-bottom: 0in;">
You can find more
information about it in the following link:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://planet.jboss.org/post/jboss_eap_and_wildfly_a_symbiotic_relationship">http://planet.jboss.org/post/jboss_eap_and_wildfly_a_symbiotic_relationship</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
With this I realized that
there are plenty versions of JEE servers in the market and is hard to
understand for a non expert or a newbie which one does what and what is
the difference between all of them, so I decided to write a post
about the JEE Servers that are available, just to list some of its
features and not a benchmark because that would require expertise in
each server and I don't have that.</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Before getting into serves
here is a list of the specifications that a full Java EE 7 server
should have, I will refer to it in a future as figure 1.</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhcYkkGISNZ7kTr2caJYWU7KZeougkZWFVY_HZ_N771N2FyX3pUSsYAl1B8nrEVBhRG0PuAniC6Z-uCWjwO1WiDSJ1irWelDR0WmzXZrZygyml4lRrNjHuAiw47UOg3iPwOqr0GvgxODKPA/s1600/Specs.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhcYkkGISNZ7kTr2caJYWU7KZeougkZWFVY_HZ_N771N2FyX3pUSsYAl1B8nrEVBhRG0PuAniC6Z-uCWjwO1WiDSJ1irWelDR0WmzXZrZygyml4lRrNjHuAiw47UOg3iPwOqr0GvgxODKPA/s1600/Specs.jpg" height="640" width="335" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br />
<b></b></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkBN-vTcHg1V2Y-hUK7ZQTKUHF1_ybbgA-vCq1dCIhhriewa0_o_NPfZp5TrOdeOQhjqZnLoGtgiY6OcNT8ruxgnHVl3H0AemDhN_bbxcNufiaEqp2RM0xSK7ncBZu7qp3wlJIMxBRc0-X/s1600/tomcat_logo.gif" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkBN-vTcHg1V2Y-hUK7ZQTKUHF1_ybbgA-vCq1dCIhhriewa0_o_NPfZp5TrOdeOQhjqZnLoGtgiY6OcNT8ruxgnHVl3H0AemDhN_bbxcNufiaEqp2RM0xSK7ncBZu7qp3wlJIMxBRc0-X/s1600/tomcat_logo.gif" /></a><b></b></div>
<br />
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<b style="text-align: center;">A</b><b style="text-align: center;">p</b><b style="text-align: center;">ache </b><b style="text-align: center;">Tomcat </b></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br />
Apache tomcat is an open
source web server, it has many years in the market and is very common
to find implementations using it.</div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
Tomcat is a web server
because it supports the Java Servlet and JavaServer Pages and others
related to them, the table below shows the specification version
supported by the tomcat version.<br />
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDd3x6DQTksv1Q9o0FyFurRPTlSkhiNGatXUOGubbQMY4OZRw2X4-DdT-q9QbcgXnVS2eOMIqRb8sxZAay9XIDnqYi8QDf3In4sjNasn7TQBTn6hOOptfZ8Pa_swwE6SeEeiADheEkBldj/s1600/tomcat_features.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDd3x6DQTksv1Q9o0FyFurRPTlSkhiNGatXUOGubbQMY4OZRw2X4-DdT-q9QbcgXnVS2eOMIqRb8sxZAay9XIDnqYi8QDf3In4sjNasn7TQBTn6hOOptfZ8Pa_swwE6SeEeiADheEkBldj/s1600/tomcat_features.jpg" height="116" width="640" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
Tomcat home page:
<a href="http://tomcat.apache.org/">http://tomcat.apache.org/</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEsi_vL86nBdBylfuDzTB2i4ZMZp52sWgiF_mbvTYSzAxXRhLFc8h6fjX4jnKdehCoe7xkGE1KGen01PZ2qFaKEiyCegcy8oxjkOebHqGNTQ1Ff39cXGdIo7cGipiJ71W-yKCUzE1hrm0k/s1600/jetty-logo-80x22.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjEsi_vL86nBdBylfuDzTB2i4ZMZp52sWgiF_mbvTYSzAxXRhLFc8h6fjX4jnKdehCoe7xkGE1KGen01PZ2qFaKEiyCegcy8oxjkOebHqGNTQ1Ff39cXGdIo7cGipiJ71W-yKCUzE1hrm0k/s1600/jetty-logo-80x22.png" height="56" width="200" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<b>Jetty</b></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br />
Jetty is a open source web
container, it an Eclipse project and is hosted entirely at the
Eclipse Foundation. It is known for be a lightweight server and be
easily embedded in devices, tools, frameworks, application servers,
and clusters. It has support for SPDY, WebSocket, OSGi, JMX, JNDI,
JAAS and many other integrations.</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
The specifications that
jetty has support are:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjnxGihzmK_Shyphenhyphen5UF5IysP9VQh6fG5o8h8mQd9j__Y1HP1XgzaCzXb2KbFjPvEOvX_fa7bkbnwDrMDbE8koglLa3JJp_J91-8qmdUBKKs63QDVq5Xby3fVfR_2tZP8UrlI_ynRtHKAkzdgP/s1600/Jetty_specs.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjnxGihzmK_Shyphenhyphen5UF5IysP9VQh6fG5o8h8mQd9j__Y1HP1XgzaCzXb2KbFjPvEOvX_fa7bkbnwDrMDbE8koglLa3JJp_J91-8qmdUBKKs63QDVq5Xby3fVfR_2tZP8UrlI_ynRtHKAkzdgP/s1600/Jetty_specs.jpg" height="252" width="400" /></a></div>
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<div lang="en-US" style="margin-bottom: 0in;">
More information about
jetty can be found in the following link:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://www.eclipse.org/jetty/">http://www.eclipse.org/jetty/</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhWOYcT3KIiUzdCNWNW9aI-QT6akQU_snXWp4hOTY4AcGVePiI_RAiHpmlhsWXO3YCPxmC0WEnu2wNvbAB94fgl6RGsT0kXLbwu0wMMKeR81JJa3Q6v7K2XJeY3xJRe0U0lZB1h4hZb0IdC/s1600/tomee_logo.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhWOYcT3KIiUzdCNWNW9aI-QT6akQU_snXWp4hOTY4AcGVePiI_RAiHpmlhsWXO3YCPxmC0WEnu2wNvbAB94fgl6RGsT0kXLbwu0wMMKeR81JJa3Q6v7K2XJeY3xJRe0U0lZB1h4hZb0IdC/s1600/tomee_logo.png" height="59" width="200" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<b>Apache TomEE</b></div>
<br />
<br />
<br />
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Apache TomEE is an open
source Java EE 6 Web Profile server, it is based on Tomcat with EE
features, that's the reason of its name “TomEE” pronounced as
"Tommy”. It is practically new its first release came out in
April of 2012, but it is gaining popularity and it has the support of
the apache community.</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
TomEE server supports more
JEE specifications than tomcat such as Enterprise JavaBeans, Java
Persistence API (JPA), and others. It comes in different packages
each with different specifications, the following table shows a
comparison of the different packages.</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhe0KnyHeRwMMEA-Umi6f6wjzF9H_ACp9BBNXa_l5jrQrTh8Uhnm01WAt_fSfSaeHxfvf22MTnPCIyx23LQtY8xysncq_WL4iuFI8XUX4IOrqGVNdh-W4Zt2e9hYWHL2ElVQHaXZLOtFQE1/s1600/tomee.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhe0KnyHeRwMMEA-Umi6f6wjzF9H_ACp9BBNXa_l5jrQrTh8Uhnm01WAt_fSfSaeHxfvf22MTnPCIyx23LQtY8xysncq_WL4iuFI8XUX4IOrqGVNdh-W4Zt2e9hYWHL2ElVQHaXZLOtFQE1/s1600/tomee.jpg" height="268" width="400" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br />
<br />
<br />
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br />
TomEE uses other project
to provide the specifications:</div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<ul>
<li>CDI - Apache OpenWebBeans</li>
<li>EJB - Apache OpenEJB</li>
<li>JPA - Apache OpenJPA</li>
<li>JSF - Apache MyFaces</li>
<li>JSP - Apache Tomcat</li>
<li>JSTL - Apache Tomcat</li>
<li>JTA - Apache Geronimo Transaction</li>
<li>Servlet - Apache Tomcat</li>
<li>Javamail - Apache Geronimo JavaMail</li>
<li>Bean Validation - Apache BVal</li>
<li>JAX-RS - Apache CXF</li>
<li>JAX-WS - Apache CXF</li>
<li>JMS - Apache ActiveMQ</li>
<li>Connector - Apache Geronimo Connector</li>
</ul>
<br />
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Use the following link for
more information:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://tomee.apache.org/index.html">http://tomee.apache.org/index.html</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgY3xTkbM-CDv3-uqeAMz0ZuxQaD8V5aZ9T7WLGh2dE2_j8sW_RbDNNzhtjb06XRY6hARtVoSQ_ZgvN9McFTtifdeKstX0h-YzkERZT_gyqE50hzJdBvuUe-fV-4AcXuP3O7Skt8KcvzkS7/s1600/glassfish_logo.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgY3xTkbM-CDv3-uqeAMz0ZuxQaD8V5aZ9T7WLGh2dE2_j8sW_RbDNNzhtjb06XRY6hARtVoSQ_ZgvN9McFTtifdeKstX0h-YzkERZT_gyqE50hzJdBvuUe-fV-4AcXuP3O7Skt8KcvzkS7/s1600/glassfish_logo.png" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<b>Glassfish</b></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Glassfish is an open
source Java EE application server sponsored by Oracle, it works as a
reference implementation of the latest Java EE specifications. Its
latest version Glassfish 4 supports the Java EE 7 specifications, so it should support all the specifications shown in figure 1.</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in; page-break-before: always;">
It makes use of some others opens source projects to implement the
specifications:</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgm9NfH3y0LOnVCaeqz8GtOAOAtUUZMZCbgPM0ekiV1Q7ee7mtkgmjoSYwWmiCet2ZSFEamvWGijvmqJAkpZiVl6v-BWVPH88sLqnW8cXhEzICYSa_RhVyCByt5dOi8GS2a-pD3jgSS8LoA/s1600/Glassfish_projects.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgm9NfH3y0LOnVCaeqz8GtOAOAtUUZMZCbgPM0ekiV1Q7ee7mtkgmjoSYwWmiCet2ZSFEamvWGijvmqJAkpZiVl6v-BWVPH88sLqnW8cXhEzICYSa_RhVyCByt5dOi8GS2a-pD3jgSS8LoA/s1600/Glassfish_projects.jpg" height="177" width="400" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Also Oracle provides a
commercial version of this server which offers support. The following
links will provide more information.</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://glassfish.java.net/">http://glassfish.java.net/</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="https://wikis.oracle.com/display/GlassFish/PlanForGlassFish4.0#PlanForGlassFish4.0-Overview">https://wikis.oracle.com/display/GlassFish/PlanForGlassFish4.0#PlanForGlassFish4.0-Overview</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://www.oracle.com/technetwork/middleware/glassfish/overview/index.html">http://www.oracle.com/technetwork/middleware/glassfish/overview/index.html</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJ-iCPuL2BIGlEv2HrDqcqA0a5nNmctfYd8lVzQhy-RjMSM_o554ApVYIoHu6RWvgx2bu2vpqnEFKlV7inTGEAJRjwapxQiTr1Kdoeu7OG-r0fMSauSXTlRH1ZZMzegZ6S06LIQLdlzVlU/s1600/geronimo.gif" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJ-iCPuL2BIGlEv2HrDqcqA0a5nNmctfYd8lVzQhy-RjMSM_o554ApVYIoHu6RWvgx2bu2vpqnEFKlV7inTGEAJRjwapxQiTr1Kdoeu7OG-r0fMSauSXTlRH1ZZMzegZ6S06LIQLdlzVlU/s1600/geronimo.gif" height="46" width="320" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<b>Geronimo</b></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Apache Geronimo is an open
source server, it is Java EE 6 certified and it is based in OSGI
offering a more modular design.</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Geronimo also uses other
source projects to implement the specifications:</div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<ul>
<li>OpenEJB</li>
<li>OpenJPA</li>
<li>ActiveMQ</li>
<li>Tomcat</li>
<li>Jetty</li>
<li>TranQL</li>
</ul>
<br />
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
In the following link you
can find a list of all the components or projects used in geronimo:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://geronimo.apache.org/GMOxDOC30/component-versions.html">http://geronimo.apache.org/GMOxDOC30/component-versions.html</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Geronimo home page:</div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://geronimo.apache.org/">http://geronimo.apache.org/</a></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgRRIQE2JnP8XG8h7mrxjTSBkXFdW_9ZpAalWW_KrdJ4irA6YGGYbZFKedlmMAfdtebbpEMnxFs8kishLTEK8ExbfYnunGpY-Hqh0Qhoanxx7GIJNK5Yb50q9wSoAaJhnl-_sR4-pSTEH3g/s1600/wildflylogo_small.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><br /></a><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgRRIQE2JnP8XG8h7mrxjTSBkXFdW_9ZpAalWW_KrdJ4irA6YGGYbZFKedlmMAfdtebbpEMnxFs8kishLTEK8ExbfYnunGpY-Hqh0Qhoanxx7GIJNK5Yb50q9wSoAaJhnl-_sR4-pSTEH3g/s1600/wildflylogo_small.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgRRIQE2JnP8XG8h7mrxjTSBkXFdW_9ZpAalWW_KrdJ4irA6YGGYbZFKedlmMAfdtebbpEMnxFs8kishLTEK8ExbfYnunGpY-Hqh0Qhoanxx7GIJNK5Yb50q9wSoAaJhnl-_sR4-pSTEH3g/s1600/wildflylogo_small.png" height="66" width="200" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<b>JBoss Wildfly and Jboss
AS</b></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Wildfly formerly JBoss AS
is an open source Java EE server now sponsored by Red Hat. Wildfly is
still in alpha version but it would've be the Jboss AS 8 version. It
supports the Java EE 7 specifications shown in “figure 1”, and it
is based in OSGI offering a more modular design.</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
It makes use of some
others opens source projects to implement the specifications, such
as:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Hibernate -
<a href="http://www.hibernate.org/">http://www.hibernate.org/</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
Weld -
<a href="http://www.seamframework.org/Weld">http://www.seamframework.org/Weld</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
RESTEasy -
<a href="http://www.jboss.org/resteasy">http://www.jboss.org/resteasy</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
Mojarra -
<a href="https://java.net/projects/mojarra">https://java.net/projects/mojarra</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
Apache CXF -
<a href="http://cxf.apache.org/">http://cxf.apache.org/</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Red hat also offers a
commercial version of Wildfly named JBoss EAP and it has all the
benefits of a commercial product such as support, extra tools and
many others. Its fees are not cheap it will probably cost tens of
thousand of dollar, so be careful at the time of choosing a
commercial server, the following link is a calculator from RED HAT so
you can get an idea about the fees
<a href="http://www.redhat.com/promo/eap_calculator/">http://www.redhat.com/promo/eap_calculator/</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Some of the links where
you can find more information about Jboss are:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://www.wildfly.org/">http://www.wildfly.org/</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://www.jboss.org/products/eap.html">http://www.jboss.org/products/eap.html</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNtOeOAuPfiKhD8v5SEHkyjDZisAdWFNXSehw9dLXFrHwG9U1zCLKFfJB7hig63pK6cqq3JrRJRTi6VF2iBuyxEML2R-Fw4I2HVnXSiJZHy55ugmmawYBtXz7iE8bRBDi_Z2h_ZJ1Y00HW/s1600/weblogic_logo.gif" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNtOeOAuPfiKhD8v5SEHkyjDZisAdWFNXSehw9dLXFrHwG9U1zCLKFfJB7hig63pK6cqq3JrRJRTi6VF2iBuyxEML2R-Fw4I2HVnXSiJZHy55ugmmawYBtXz7iE8bRBDi_Z2h_ZJ1Y00HW/s1600/weblogic_logo.gif" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<b>Weblogic</b></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Oracle WebLogic Server is
a commercial Java EE application server, its latest version is
weblogic 12 is a Java EE 6 Full Profile, so the Java EE 6
specifications are supported. The following image shows the platforms
supported by Weblogic.</div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKQVeSktCLYvYBGG2xXfH0qnOPABcaVWtR_pzqhFo-KxxE8KhcmPwIIhJLjc5sjiswcLAL-QQqL1H6_Q6w_AWYf0LVyg-Edw79LYZ9nHtu0mIEumMlvnd11UgdWd_SQ0ar7QROEb2hb8Jp/s1600/Weblogic.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKQVeSktCLYvYBGG2xXfH0qnOPABcaVWtR_pzqhFo-KxxE8KhcmPwIIhJLjc5sjiswcLAL-QQqL1H6_Q6w_AWYf0LVyg-Edw79LYZ9nHtu0mIEumMlvnd11UgdWd_SQ0ar7QROEb2hb8Jp/s1600/Weblogic.jpg" height="303" width="320" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
As it is commercial
counterpart from redhat, oracle provides support and many tools for
maintain the server, but is not a cheap server it will probably cost
tens of thousand of dollar also. The following link is a pdf about
the costs so you can get an idea about the fees:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://www.oracle.com/us/products/middleware/application-server/weblogic-vs-jboss-460235.pdf">http://www.oracle.com/us/products/middleware/application-server/weblogic-vs-jboss-460235.pdf</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Some of the links where
you can find more information about Weblogic are:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://www.oracle.com/technetwork/middleware/weblogic/overview/index.html">http://www.oracle.com/technetwork/middleware/weblogic/overview/index.html</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhqxT6vZXhJ4kYQ9cdiZoT-65NhQC4ONqbnzCkJLC3rxW3lRKZ-6IM3mu4OxkPSvwettKhjgCnFgejDmcluUAgiIgzHee9nuJCQTuot83SG3pKabheZkYq3fehddkOmTl9y-J9BuX5Owxn9/s1600/Websphere_logo.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhqxT6vZXhJ4kYQ9cdiZoT-65NhQC4ONqbnzCkJLC3rxW3lRKZ-6IM3mu4OxkPSvwettKhjgCnFgejDmcluUAgiIgzHee9nuJCQTuot83SG3pKabheZkYq3fehddkOmTl9y-J9BuX5Owxn9/s1600/Websphere_logo.png" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<b>Websphere </b>
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
IBM WebSphere Application
Server is a commercial Java EE application server, its latest
version is WebSphere 8, it is JEE6 certified based in OSGI offering
a more modular design, some of the features they include are:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
● Enterprise JavaBeans
(EJB) 3.1</div>
<div lang="en-US" style="margin-bottom: 0in;">
● Java Servlet 3.0</div>
<div lang="en-US" style="margin-bottom: 0in;">
● Contexts and
Dependency Injection for Java (CDI) 1.0</div>
<div lang="en-US" style="margin-bottom: 0in;">
● Bean Validation 1.0</div>
<div lang="en-US" style="margin-bottom: 0in;">
● Java Architecture for
XML Binding (JAXB) 2.2</div>
<div lang="en-US" style="margin-bottom: 0in;">
● Enterprise Web
Services 1.3</div>
<div lang="en-US" style="margin-bottom: 0in;">
● Java API for XML-Based
Web Services (JAX-WS) 2.2</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
The Operative Systems
supported are:</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2g0PaZhaGHxA8CkwYnl08LkVBcJn3kQEf4JXGty4MjSGDgPjVj4_U-PVaIQGd1oYdzRZEy72v7_O17kld5KwkFodGpe3hQgLTVIWr-miz0xdcR1lcRxmi9kH1pOKoxRW5TQ9032-XUWMY/s1600/Websphere_OS.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj2g0PaZhaGHxA8CkwYnl08LkVBcJn3kQEf4JXGty4MjSGDgPjVj4_U-PVaIQGd1oYdzRZEy72v7_O17kld5KwkFodGpe3hQgLTVIWr-miz0xdcR1lcRxmi9kH1pOKoxRW5TQ9032-XUWMY/s1600/Websphere_OS.jpg" height="330" width="400" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
As it is commercial as
Weblogic and JBoss EAP, it comes with all the benefits from a
commercial product but also its fees, the following image shows how
much could it cost to have Webshpere:</div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhkdBHX0ZDOxD8x74UrkWfqA1gkENtEEmNlGos-BcoNUmJfwnY1N7xszR1uEIpSuxN3xFoK2JZ7SMgxIi1XxyUnPVLjZCr1ztbYR3caDUCJ2UrMeDR7Acqtrb8w29L_A3sZmdrEz0iFq4kE/s1600/websphere_cost.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhkdBHX0ZDOxD8x74UrkWfqA1gkENtEEmNlGos-BcoNUmJfwnY1N7xszR1uEIpSuxN3xFoK2JZ7SMgxIi1XxyUnPVLjZCr1ztbYR3caDUCJ2UrMeDR7Acqtrb8w29L_A3sZmdrEz0iFq4kE/s1600/websphere_cost.jpg" height="120" width="400" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br />
<br />
<br />
<br />
<br />
<br />
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
In the following link more
information about websphere can be found:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://www-03.ibm.com/software/products/us/en/appserv-was/">http://www-03.ibm.com/software/products/us/en/appserv-was/</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<b>FUJITSU </b>
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
FUJITSU Software
Interstage Application Server is a commercial server and support
standards such as Java EE, Web Service, and CORBA. Interstage
Application Server component technologies and development frameworks.</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
It has support for the
following features:</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh00L3EpBtIsWdu89PmCLKxhdadqVXf91NGVepJFlA7wblWeS9rdqiS2KEJ4qpZUsfp8oR-2s2tSJ91K7VY3V9U-AZ88V48-C_N1ceGMuxuUMzQBz1ngnwCHbFbcVy9v9SQfqg3VTtNhjH3/s1600/Fujitsu_features.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh00L3EpBtIsWdu89PmCLKxhdadqVXf91NGVepJFlA7wblWeS9rdqiS2KEJ4qpZUsfp8oR-2s2tSJ91K7VY3V9U-AZ88V48-C_N1ceGMuxuUMzQBz1ngnwCHbFbcVy9v9SQfqg3VTtNhjH3/s1600/Fujitsu_features.jpg" height="400" width="386" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br />
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
The OS supported are:</div>
<ul>
<li><div lang="en-US" style="margin-bottom: 0in;">
Microsoft Windows
Server 2008 R2</div>
</li>
<li><div lang="en-US" style="margin-bottom: 0in;">
Microsoft Windows
Server 2008</div>
</li>
<li><div lang="en-US" style="margin-bottom: 0in;">
Microsoft Windows
Server 2003 R2</div>
</li>
<li><div lang="en-US" style="margin-bottom: 0in;">
Microsoft Windows
Server 2003</div>
</li>
<li><div lang="en-US" style="margin-bottom: 0in;">
Windows Azure Guest
OS 1.18~(4)</div>
</li>
<li><div lang="en-US" style="margin-bottom: 0in;">
Windows Azure Guest
OS 2.6~(4)</div>
</li>
<li><div lang="en-US" style="margin-bottom: 0in;">
Red Hat Enterprise
Linux 6</div>
</li>
<li><div lang="en-US" style="margin-bottom: 0in;">
Red Hat Enterprise
Linux 5</div>
</li>
<li><div lang="en-US" style="margin-bottom: 0in;">
Solaris 11</div>
</li>
<li><div lang="en-US" style="margin-bottom: 0in;">
Solaris 10</div>
</li>
</ul>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
For more information about
fujitsu server go to the following links:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://www.fujitsu.com/global/services/software/interstage/solutions/ai/apserver/">http://www.fujitsu.com/global/services/software/interstage/solutions/ai/apserver/</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://www.fujitsu.com/global/news/pr/archives/month/2012/20120820-02.html">http://www.fujitsu.com/global/news/pr/archives/month/2012/20120820-02.html</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<b>JEUS </b>
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
TmaxSoft's JEUS is a
commercial Java EE certified application server. It supports the
following specifications:</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi2x1DTz28hM0hp4Tzc7ShWCs-x_DqcwQgMJcWbtQLbvrE_ZXcJjQT6c5IlpVO6XHtERnGlkUp8etQmGCLCzWSe7zX1u8hXiKkylYo7YYHIQyvsqetX0DStLR8TgJUFsYrvmn2aHxMedDkA/s1600/jeus7_release_1.gif" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi2x1DTz28hM0hp4Tzc7ShWCs-x_DqcwQgMJcWbtQLbvrE_ZXcJjQT6c5IlpVO6XHtERnGlkUp8etQmGCLCzWSe7zX1u8hXiKkylYo7YYHIQyvsqetX0DStLR8TgJUFsYrvmn2aHxMedDkA/s1600/jeus7_release_1.gif" height="308" width="400" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br />
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
JEUS offer support for
clustering, load balancing and has tools for the development and
administration process.</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
For more information about
JEUS go to the following link:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://us.tmaxsoft.com/jsp/product/detailcontents.jsp?psCd=00PD04&menuCd=00PDMSJE">http://us.tmaxsoft.com/jsp/product/detailcontents.jsp?psCd=00PD04&menuCd=00PDMSJE</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgjQtyu9wnHLkDsYqrUMzUto_YyTxiIXxIsMTRgwLxWZ6N72g3Tc5NFN-TPEv-lFROP98tI9EhUK0rHhTKLjMKjby4DuvT4b9s-Q9mjNNDZvxH8DbUWnvxu4e4uQarso6YoEcaJTCXq9Fn3/s1600/jonas_logo.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgjQtyu9wnHLkDsYqrUMzUto_YyTxiIXxIsMTRgwLxWZ6N72g3Tc5NFN-TPEv-lFROP98tI9EhUK0rHhTKLjMKjby4DuvT4b9s-Q9mjNNDZvxH8DbUWnvxu4e4uQarso6YoEcaJTCXq9Fn3/s1600/jonas_logo.jpg" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<b><br /></b></div>
<div lang="en-US" style="margin-bottom: 0in;">
<b>J</b><b>ONAS</b></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
OW2 Jonas is an open
source Java EE application server, it is Java EE 5 certified and has
a Java EE 6 preview version, is based in OSGI offering a more
modular design.</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Jonas use other opens
source projects to implement the specifications, and since it is
based on osgi different options and you can choose what project to
use:</div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<ul>
<li><div style="margin-bottom: 0in;">
<span lang="en-US">EasyBeans (EJB3
container) </span><a href="http://www.easybeans.net/xwiki/bin/view/Main/WebHome">http://www.easybeans.net/xwiki/bin/view/Main/WebHome</a></div>
</li>
<li><div style="margin-bottom: 0in;">
<span lang="en-US">Joram (JMS)
</span><a href="http://www.easybeans.net/xwiki/bin/view/Main/WebHome">http://www.easybeans.net/xwiki/bin/view/Main/WebHome</a></div>
</li>
<li><div lang="en-US" style="margin-bottom: 0in;">
Tomcat/Jetty (Web
container)</div>
</li>
<li><div lang="en-US" style="margin-bottom: 0in;">
Hibernate/TopLink/OpenJPA
(JPA)
</div>
</li>
<li><div lang="en-US" style="margin-bottom: 0in;">
.....</div>
</li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgEOf0o9DYefPcIv-rE-GiDN1H4yCxSQ2cLddfCnRPLm_tX_oMe7c70g16hvWADOdGtxjJEiebxiVhE302ZyDUvrXkot7k6GUp2Es_wD4n98pTRziPT6Z4_gU3Y4herWBFsdFyn0xTbUFDJ/s1600/jonas-5-schema.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgEOf0o9DYefPcIv-rE-GiDN1H4yCxSQ2cLddfCnRPLm_tX_oMe7c70g16hvWADOdGtxjJEiebxiVhE302ZyDUvrXkot7k6GUp2Es_wD4n98pTRziPT6Z4_gU3Y4herWBFsdFyn0xTbUFDJ/s1600/jonas-5-schema.png" height="246" width="400" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
OW2 do not offer a
commercial version of Jonas server but it offers a support
subscription for professional support and training, it has tools for
managing and clustering but they are for free.</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
In the following link more
information about JONAS can be found:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://jonas.ow2.org/">http://jonas.ow2.org</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbVi7px0l6vuhtoNpujAJhUrANLAuBYlAxK_FvDr9muF8QljV_eyM0w2t8U1bAIfNKGKdWUHo7Z3HT5ufHVOLJmP9TlUoyJtovvLrBsm_TP1zgctcjAqZ4xQweW4s9WTtGWhJKWUPDlXae/s1600/resin_logo_25.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbVi7px0l6vuhtoNpujAJhUrANLAuBYlAxK_FvDr9muF8QljV_eyM0w2t8U1bAIfNKGKdWUHo7Z3HT5ufHVOLJmP9TlUoyJtovvLrBsm_TP1zgctcjAqZ4xQweW4s9WTtGWhJKWUPDlXae/s1600/resin_logo_25.png" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<b>Resin </b>
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Resin is a commercial Java
application server by Caucho, it supports the Java EE 6 Web Profile.
It supports Servlet, JSP, JSTL, EJB, Candi (Java CDI), JSF, JPA, and
more. It is a lightweight server designed with CDI.It has Java
monitoring and OS monitoring facilities available via built-in
console or third party applications via JMX and REST</div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwT1qrXIoo6f5Fcg3LIPE7VDm1k1D34wQgNCQJg6BzQeybbs5D5G-ACZ5ZvUfXEiIp6aNB6Dsrz8AkVwnjDfM4vz4xTm9uCU_oM70D495I23emx9DnaoyOaKVPQSAkaqwzcU_9u92UXXlG/s1600/graphresin-web-profile.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwT1qrXIoo6f5Fcg3LIPE7VDm1k1D34wQgNCQJg6BzQeybbs5D5G-ACZ5ZvUfXEiIp6aNB6Dsrz8AkVwnjDfM4vz4xTm9uCU_oM70D495I23emx9DnaoyOaKVPQSAkaqwzcU_9u92UXXlG/s1600/graphresin-web-profile.png" height="320" width="320" /></a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
It has support for
clustering and tools for application deployment, distributed
caching, load balancing and messaging, and so on.
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Resin can be used with
Amazon Web Services for cloud deployment. More information about
resin and amazon can be found in the following link:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://wiki3.caucho.com/Resin_Cloud_deployment_with_Amazon">http://wiki3.caucho.com/Resin_Cloud_deployment_with_Amazon</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
The prices of the licenses
of resin can be found in the following link:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://www.caucho.com/purchase/resin-professional-application-server/">http://www.caucho.com/purchase/resin-professional-application-server/</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Resin has an open source
version <a href="http://resin.caucho.com/">http://resin.caucho.com/</a>
, the differences between the open source and the commercial version,
is the amount of tools offered by the commercial version, in the
following link a comparison between the two versions can be found:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://www.caucho.com/sales-price-list/">http://www.caucho.com/sales-price-list/</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
For more information about
resin go to the following link:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://www.caucho.com/resin-application-server-2/">http://www.caucho.com/resin-application-server-2/</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
Well these are the most
known options that can be found for a JEE server, I try to list some
of its features and useful links. As I said before this is not a
benchmark, but for choosing one server first you have to check if you
want a commercial option or open source option, then check what
options are among between your budget and then evaluate these
options, its features, the support, if it is open source the
community support, the documentation and so on.</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
And finally here is a link
where you can find which servers are compatible with each JEE
profile:</div>
<div lang="en-US" style="margin-bottom: 0in;">
<a href="http://www.oracle.com/technetwork/java/javaee/overview/compatibility-jsp-136984.html">http://www.oracle.com/technetwork/java/javaee/overview/compatibility-jsp-136984.html</a></div>
<div lang="en-US" style="margin-bottom: 0in;">
</div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
<div lang="en-US" style="margin-bottom: 0in;">
<br /></div>
</div>
Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com0tag:blogger.com,1999:blog-4213799477897003979.post-46798594635613775002013-08-04T14:15:00.000-07:002014-03-27T11:19:32.566-07:00Java Collections Framework Part 7 - Collections Utility<div style="margin-bottom: 0in;">
<b>Collections Utility class</b></div>
<div style="margin-bottom: 0in;">
<br />
<a href="http://jlunaquiroga.blogspot.com/2013/07/java-collections-framework-part-6-queues.html">This is the seventh part of the tutorial, and this link goes to the previous post java collections framework part 6-queues.html</a><br />
<br /></div>
<div style="margin-bottom: 0in;">
The <b>java.util.Collection</b><b>s</b>
class is an utility class, an utility class defines a set of static
methods that perform common operations, all the methods of
Collections are public and static.
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The java API says about the Collection
class “This class consists exclusively of static methods that
operate on or return collections. It contains polymorphic algorithms
that operate on collections, "wrappers", which return a new
collection backed by a specified collection, and a few other odds and
ends”.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The Collections class has methods for
changing the order of lists:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
void <b>reverse(List<?> list)</b>:
Reverses the order of the elements</div>
<div style="margin-bottom: 0in;">
void <b>rotate(List<?> list, int
distance)</b>: Rotates the elements in the specified list by the
specified distance.</div>
<div style="margin-bottom: 0in;">
void <b>shuffle(List<?> list)</b>:
Randomly permutes the list elements</div>
<div style="margin-bottom: 0in;">
void <b>shuffle(List<?> list,
Random rnd)</b>: Randomly permutes the list using the randomness
source rnd</div>
<div style="margin-bottom: 0in;">
<T extends Comparable<? super T>>
<b>void sort(List<T> list)</b>: Sorts the supplied list using
natural ordering</div>
<div style="margin-bottom: 0in;">
<T> void <b>sort(List<T>
list, Comparator<? super T> c)</b>: Sorts the supplied list
using the supplied ordering</div>
<div style="margin-bottom: 0in;">
void <b>swap(List<?> list, int i,
int j)</b>: Swaps the elements at the specified positions</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
It has methods for changing the
contents of a list, the copy() transfers elements from the source
list into an initial a the destination list, the fill() replaces
every element of a list with a specified object and replaceAll()
replaces every occurrence of one value in a list with another.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<T> void <b>copy(List<? super
T> dest, List<? extends T> src)</b>: Copies all of the
elements from one list into another</div>
<div style="margin-bottom: 0in;">
<T> void <b>fill(List<? super
T> list, T obj)</b>: Replaces every element of list with obj</div>
<div style="margin-bottom: 0in;">
<T> boolean <b>replaceAll(List<T>
list, T old, T new)</b>: Replaces all occurrences of old in list with
new.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
It has methods for finding elements in
ordered collections:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<T extends Object & Comparable<?
super T>> <b>T max(Collection<? extends T> coll)</b>:
Returns the maximum element using natural ordering.</div>
<div style="margin-bottom: 0in;">
<T> T <b>max(Collection<?
extends T> coll, Comparator<? super T> comp)</b>: Returns
the maximum element using the supplied comparator</div>
<div style="margin-bottom: 0in;">
<T extends Object & Comparable<?
super T>> T <b>min(Collection<? extends T> coll)</b>:
Returns the minimum element using natural ordering</div>
<div style="margin-bottom: 0in;">
<T> T <b>min(Collection<?
extends T> coll, Comparator<? super T> comp)</b>: Returns
the minimum element using the supplied comparator</div>
<div style="margin-bottom: 0in;">
<T> int <b>binarySearch(List<?
extends Comparable<? super T>> list, T key)</b>: Searches
for key using binary search</div>
<div style="margin-bottom: 0in;">
<T> int <b>binarySearch(List<?
extends T> list, T key, Comparator<? super T> c)</b>:
Searches for key using binary search</div>
<div style="margin-bottom: 0in;">
int <b>indexOfSubList(List<?>
source, List<?> target)</b>: Finds the first sublist of source
which matches target</div>
<div style="margin-bottom: 0in;">
int <b>lastIndexOfSubList(List<?>
source, List<?> target)</b>: Finds the last sublist of source
which matches target</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Some methods require that the
collection should be ordered before using them otherwise their
outcome will make no sense, this is the case of the binarySearch(),
if the list is not ordered then the binarySearch() will return a
wrong value, Example:</div>
<script src="https://gist.github.com/anonymous/6151951.js"></script>
<br />
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the example you can see how the
collection is ordered before using the binarySearch() method.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Some methods are overloaded with a
version that takes a Comparator, in this case the type of the
Collection doesn't have to implement the Comparable interface,
Example:</div>
<script src="https://gist.github.com/anonymous/6151961.js"></script>
<br />
<div style="margin-bottom: 0in;">
<br /></div>
</div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the example you can see that the
List is of type Person and it doesn't implements the Comparable
interface but at the time to order the collection and search it, a
Comparator instance is used it.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The Collections class has methods for
creating collections:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<T> List<T> emptyList():
Returns the empty list (immutable)
</div>
<div style="margin-bottom: 0in;">
<K,V> Map<K,V> emptyMap():
Returns the empty map (immutable)</div>
<div style="margin-bottom: 0in;">
<T> Set<T> emptySet():
Returns the empty set (immutable)</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
These methods can be used to indicate
there are no values, the collections returned by this methods are
immutable, this means no elements can be added to them.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
</div>
<script src="https://gist.github.com/anonymous/6151974.js"></script>
<br />
<div style="margin-bottom: 0in;">
The previous example will throw a
java.lang.UnsupportedOperationException at the time the new element
was added.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
There are also methods for creating
collections containing only a single element.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<T> Set<T> <b>singleton(T
o)</b>: Returns an immutable set containing only the specified
object.</div>
<div style="margin-bottom: 0in;">
<T> List<T> <b>singletonList(T
o)</b>: Returns an immutable list containing only the specified
object.</div>
<div style="margin-bottom: 0in;">
<K,V> Map<K,V>
<b>singletonMap(K key, V value)</b>: Returns an immutable map,
mapping only the key K to the value V</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The collections returned by this
methods are also immutable and no elements can be added to them.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<script src="https://gist.github.com/anonymous/6151984.js"></script>
<br />
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
The previous example will throw a
java.lang.UnsupportedOperationException at the time the new element
was added.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
There is a method that creates a list
containing a number of copies of a given object.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<T> List<T><b> nCopies(int
n, T o</b>): Returns an immutable list containing n references to the
object o</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Sometimes a collection implementation
is not synchronized, in order to make a collection thread safe the
Collections class provides methods for this purpose:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<T> Collection<T>
<b>synchronizedCollection(Collection<T> c)</b>;</div>
<div style="margin-bottom: 0in;">
<T> Set<T>
<b>synchronizedSet(Set<T> s)</b>;</div>
<div style="margin-bottom: 0in;">
<T> List<T>
<b>synchronizedList(List<T> list)</b>;</div>
<div style="margin-bottom: 0in;">
<K, V> Map<K, V>
<b>synchronizedMap(Map<K, V> m)</b>;</div>
<div style="margin-bottom: 0in;">
<T> SortedSet<T>
<b>synchronizedSortedSet(SortedSet<T> s)</b>;</div>
<div style="margin-bottom: 0in;">
<K, V> SortedMap<K, V>
<b>synchronizedSortedMap(SortedMap<K, V> m)</b>;</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Basically this last post is a summary
of the java.util.Collections class, but if I was doing a tutorial
about collections I had to add it. So with this I finish the tutorial
and I hope you can find a quick reference to the collections API and
learn something new.</div>
<br />
<div style="margin-bottom: 0in;">
<br /></div>
<br />
<br /></div>
Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com2tag:blogger.com,1999:blog-4213799477897003979.post-72005265532731702222013-07-27T17:26:00.002-07:002014-03-27T11:19:43.445-07:00Java Collections Framework Part 6 - QueuesThis is the sixth part of the tutorial, and this link goes to the previous post <a href="http://jlunaquiroga.blogspot.com/2013/07/java-collections-framework-part-5-maps.html">java collections framework part 5</a><br />
<br />
<div style="margin-bottom: 0in;">
<b>Queues</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
A queue is a collection that implements
the interface <b>java.util.Queue</b> , usually a queue is an ordered
collection that follows the FIFO (First-In, First-Out) rule, but the
queue implementations allow other ways to order the collection as
well, such as LIFO or based on priority and so on.</div>
<br />
<div style="margin-bottom: 0in;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgn2Pd_7TLcsmOrvq4nHexUGuhHMyFsft5PzVYViZ0AJK4e7ZX4GtM4gbtzl15aH2t8D01IQxqNCHRuu5LXwhqesLI_PE6OhyphenhyphenPnmjJNYujO5Oj1w1O0C1T6pTSiSZ7wyQW3wr9WUxOx9l5e/s1600/queue.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgn2Pd_7TLcsmOrvq4nHexUGuhHMyFsft5PzVYViZ0AJK4e7ZX4GtM4gbtzl15aH2t8D01IQxqNCHRuu5LXwhqesLI_PE6OhyphenhyphenPnmjJNYujO5Oj1w1O0C1T6pTSiSZ7wyQW3wr9WUxOx9l5e/s1600/queue.png" height="287" width="400" /></a></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The Queue interface defines the
following methods:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
boolean <b>add(E e)</b>: Inserts the
specified element into this queue if it is possible to do so
immediately without violating capacity restrictions, returning true
upon success and throwing an IllegalStateException if no space is
currently available.</div>
<div style="margin-bottom: 0in;">
E <b>element()</b>: Retrieves, but does
not remove, the head of this queue.</div>
<div style="margin-bottom: 0in;">
Boolean <b>offer(E e)</b>: Inserts the
specified element into this queue if it is possible to do so
immediately without violating capacity restrictions.</div>
<div style="margin-bottom: 0in;">
E <b>peek()</b>: Retrieves, but does
not remove, the head of this queue, or returns null if this queue is
empty.</div>
<div style="margin-bottom: 0in;">
E <b>poll()</b>: Retrieves and removes
the head of this queue, or returns null if this queue is empty.</div>
<div style="margin-bottom: 0in;">
E <b>remove()</b>: Retrieves and
removes the head of this queue.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Whatever the ordering used, the head of
the queue is that element which would be removed by a call to
remove() or poll(). In a FIFO queue, all new elements are inserted at
the tail of the queue. Other kinds of queues may use different
placement rules. Every Queue implementation must specify its ordering
properties.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>PriorityQueue</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The class <b>java.util.PriotiyQueue</b>
is an implementation of the Queue interface, it is an ordered
collection and allows duplicates, it works as a “Priority-In,
Priority-Out” collection, its elements are ordered by priority and
its default priority is given by its natural order, it can be defined
another priority order with an instance of a Comparator.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example</div>
<script src="https://gist.github.com/anonymous/59534ef5d5bd93456ccb.js"></script>
<br />
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The previous example should print the
elements in the collection according to its priority, in this case it
should print 1 2 3 4 5 6 7 8 9, this means they priority is the
natural order.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
To specify a different priority an
instance of a Comparator should be used:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example</div>
<script src="https://gist.github.com/anonymous/6096850.js"></script>
<br />
<div style="margin-bottom: 0in;">
The previous example should print its
elements according to the new priority specified at the time the
collection was created, this new priority is the inverse of the
natural order and the example should print 9 8 7 6 5 4 3 2 1
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>Deque</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>java.util.Deque</b> interface
extends the Queue interface, the deque name means “double-ended
queue”. In a double-ended queue elements can be inserted and
removed at both ends of the queue, unlike queue that elements only
can be inserted at the tail and removed at the head.</div>
<div style="margin-bottom: 0in;">
With this a deque can also act as a
LIFO collection or Stack.</div>
<br />
<div style="margin-bottom: 0in;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhVtqHWIqyHxSvALZvPIHtax_VagVfEbXT9onrstAQBmsMZrpNpafd5A1tXQOP6OVMEcANhLJ1KqkX-GZQGNVBPi7MkuMWXTAail7eIlEN1cCeaYCAGvJmFhQDo274zPME9_i1F85aT8v2S/s1600/deque.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhVtqHWIqyHxSvALZvPIHtax_VagVfEbXT9onrstAQBmsMZrpNpafd5A1tXQOP6OVMEcANhLJ1KqkX-GZQGNVBPi7MkuMWXTAail7eIlEN1cCeaYCAGvJmFhQDo274zPME9_i1F85aT8v2S/s1600/deque.png" height="112" width="400" /></a></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The Deque interface defines new methods
besides the ones defined in the Queue interface:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
void <b>addFirst(E e)</b> : Inserts e
at the head if there is enough space</div>
<div style="margin-bottom: 0in;">
void <b>addLast(E e)</b>: Inserts e at
the tail if there is enough space</div>
<div style="margin-bottom: 0in;">
void <b>push(E e)</b>: Inserts e at the
head if there is enough space</div>
<div style="margin-bottom: 0in;">
boolean <b>removeFirstOccurrence(Object
o)</b>: Removes the first occurrence of o</div>
<div style="margin-bottom: 0in;">
boolean <b>removeLastOccurrence(Object
o)</b>: Removes the last occurrence of o</div>
<div style="margin-bottom: 0in;">
Iterator<E> <b>descendingIterator()</b>:
Gets an iterator that returns the elements in reverse order</div>
<div style="margin-bottom: 0in;">
boolean <b>offerFirst(E e)</b>: Inserts
e at the head if the deque has space</div>
<div style="margin-bottom: 0in;">
boolean <b>offerLast(E e)</b>: Inserts
e at the tail if the deque has space</div>
<div style="margin-bottom: 0in;">
E <b>peekFirst()</b>: Gets but do not
removes the first element</div>
<div style="margin-bottom: 0in;">
E <b>peekLast()</b>: Gets but do not
removes the last element</div>
<div style="margin-bottom: 0in;">
E <b>pollFirst()</b>: Gets and removes
the first element</div>
<div style="margin-bottom: 0in;">
E <b>pollLast()</b>: Gets and removes
the last element</div>
<div style="margin-bottom: 0in;">
E <b>getFirst()</b>: Gets but do not
removes the first element</div>
<div style="margin-bottom: 0in;">
E <b>getLast()</b>: Gets but do not
removes the last element</div>
<div style="margin-bottom: 0in;">
E <b>removeFirst()</b>: Gets and
removes the first element</div>
<div style="margin-bottom: 0in;">
E <b>removeLast()</b>: Gets and removes
the last element</div>
<div style="margin-bottom: 0in;">
E <b>pop()</b>: Gets and removes the
first element</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example</div>
<script src="https://gist.github.com/anonymous/6096858.js"></script>
<br />
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
In the previous example a deque
collection was created and elements were added in different ways,
first the elements were added at the head so the collection final
order was:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The the elements were added to the tail
the collection final order was:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
And this is also the default behavior
for adding elements, in the example were used methods for querying
the head and the tail of the collection. The example should print:</div>
<div style="margin-bottom: 0in;">
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]</div>
<div style="margin-bottom: 0in;">
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</div>
<div style="margin-bottom: 0in;">
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</div>
<div style="margin-bottom: 0in;">
0</div>
<div style="margin-bottom: 0in;">
9</div>
<div style="margin-bottom: 0in;">
0</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>LinkedList</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The class <b>java.util.LinkedList</b>
besides being a List also implements the Deque interface, this class
is very popular because with one class many different behaviors can
be implemented.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<a href="http://jlunaquiroga.blogspot.com/2013/08/java-collections-framework-part-7.html">Go to part 7</a><br />
<div style="margin-bottom: 0in;">
<br /></div>
<br />
<br />
<br />Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com1tag:blogger.com,1999:blog-4213799477897003979.post-24782265815240409492013-07-21T13:57:00.003-07:002014-03-27T11:19:53.196-07:00Java Collections Framework Part 5 - MapsThis is the sixth part of the tutorial, and this link goes to the previous post <a href="http://jlunaquiroga.blogspot.com/2013/07/java-collections-framework-part-4-sets.html">java collections framework part 4</a><br />
<br />
<div style="margin-bottom: 0in;">
<b>Maps</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
A Map implements the <b>java.util.Map</b>
interface, this interface doesn't extends from the Collection
interface. A map is a collection of key-value mappings, they don't
allow duplicate keys and like Sets, maps rely on the equals() method
to determine whether two keys are the same or different.
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Maps do not have order but some
implementations are sorted like the TreeMap.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Maps like the Collection interface have
methods for adding and removing elements, querying collection
contents, and providing different views of the contents of a
collection, and some of this methods are:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
V <b>put(K key, V value)</b>: Add or
replace a key-value association, returns the old value (may be null)
if the key was present; otherwise returns null.</div>
<div style="margin-bottom: 0in;">
void <b>putAll(Map<? extends K,?
extends V> m)</b>: Adds each of the key-value associations in the
supplied map into the receiver.</div>
<div style="margin-bottom: 0in;">
void <b>clear()</b>: Removes all
associations from this map.</div>
<div style="margin-bottom: 0in;">
V <b>remove(Object key)</b>: Removes
the association, if any, with the given key; returns the value with
which it was associated, or null.</div>
<div style="margin-bottom: 0in;">
V <b>get(Object k)</b>: Returns the
value corresponding to k, or null if k is not present as a key.</div>
<div style="margin-bottom: 0in;">
boolean <b>containsKey(Object k)</b>:
Returns true if k is present as a key.</div>
<div style="margin-bottom: 0in;">
boolean <b>containsValue(Object v)</b>:
Return true if v is present as a value.</div>
<div style="margin-bottom: 0in;">
int <b>size()</b>: Returns the number
of mappings.</div>
<div style="margin-bottom: 0in;">
boolean <b>isEmpty()</b>: Returns true
if there are no mappings.</div>
<div style="margin-bottom: 0in;">
Set<Map.Entry<K, V>>
<b>entrySet()</b>: Returns a Set view of the associations.</div>
<div style="margin-bottom: 0in;">
Set<K> <b>keySet()</b>: Return a
Set view of the keys</div>
<div style="margin-bottom: 0in;">
Collection<V> <b>values()</b>:
Return a Collection view of the values</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>java.util.HashMap</b> class is
an implementation of the Map interface. HashMap it keeps its elements
unsorted and unordered.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
You should know that HashMap allows one
null key and multiple null values in a collection.</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiAONzLjzZxwjmVqXjxMtRKMpdHhFk4vLPgPgt3qRKOHzYpPVr25SLlC1DGkdjaRmJoxAUOqBh_rM0xHjiWg0QyiXhiSHNJjkIs8EUS_D2CxopsbofM8MCl7lNo_LyVsMe2dpPM4JrAkYz2/s1600/hashmap.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiAONzLjzZxwjmVqXjxMtRKMpdHhFk4vLPgPgt3qRKOHzYpPVr25SLlC1DGkdjaRmJoxAUOqBh_rM0xHjiWg0QyiXhiSHNJjkIs8EUS_D2CxopsbofM8MCl7lNo_LyVsMe2dpPM4JrAkYz2/s1600/hashmap.jpg" height="116" width="400" /></a></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<script src="https://gist.github.com/anonymous/6049920.js"></script>
<br />
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
<br /></div>
In the previous example a HashMap of
Integers as keys and Strings as values was created, five elements
were added and then an element was added again replacing its previous
value. The output of the example should be:<br />
<br />
<div style="margin-bottom: 0in;">
Map:{[1, one] [2, two] [3, three-again]
[4, four] [5, five] }</div>
<br />
<div style="margin-bottom: 0in;">
The <b>java.u</b><b>t</b><b>il.Hashtable</b>
class is also an implementation of the Map interface and it is almost
identical</div>
<div style="margin-bottom: 0in;">
to the HashMap class but it is
synchronized so it performs slower than HashMap and another
difference is that Hashtable doesn't let you have anything that's
null.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>java.u</b><b>t</b><b>il.</b><b>Linked</b><b>Hash</b><b>Map</b>
class extends from the HashMap class and therfore is an
Implementation of the Map interface, and as the LinkedHashSet class
the LinkedHashMap it maintains insertion order (or, optionally,
access order). Access ordered is defined by the argument of of the
constructor:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
public LinkedHashMap(int
initialCapacity, float loadFactor, <b>boolean accessOrder</b>)</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
A value false will give an
insertion-ordered map, if order constructor is used to create the
LinkedHashMap by default it would be an insertion-ordered map.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<script src="https://gist.github.com/anonymous/6049927.js"></script>
<br />
<div style="margin-bottom: 0in;">
<br /></div>
The output of the example should be the
following:<br />
<div style="margin-bottom: 0in;">
Map { [1-1] [2-2] [3-3] [4-4] [5-5] }</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Changing the the iteration order for an
access order in the previous example:</div>
<script src="https://gist.github.com/anonymous/6049930.js"></script>
<br />
<br />
<div style="margin-bottom: 0in;">
Notice that after adding the elements
an access to the element “1” is done with this the iteration
order is changed and the output should be the following:</div>
<div style="margin-bottom: 0in;">
Map Keys { [2] [3] [4] [5] [1] }</div>
<div style="margin-bottom: 0in;">
Also notice that the output format has
changed and now just the keys are printed, this is because if the
element is obtained inside the iteration loop a
ConcurrentModificationException would arise because the iteration
order is changed , and this can not be done while the map is
iterated. So be careful when the Map is in this mode.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>TreeMap</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The class <b>java.util.TreeMap</b> is
an implementation of the Map interface, it also implements the
</div>
<div style="margin-bottom: 0in;">
java.util.NavigableMap and
java.util.SortedMap interfaces. This collection is pretty similar to
<b>TreeSet</b><span style="font-weight: normal;">, it is an sorted
collection and guarantees that the keys will be in ascending order,
according to their natural order, or by a Comparator provided at map
creation time, depending on which constructor is used.</span></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The TreeMap class implements methods
that help navigate the map, and some of these methods are:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
K <b>ceilingKey(key)</b>: Returns the
lowest key >= key</div>
<div style="margin-bottom: 0in;">
K <b>higherKey(key)</b>: Returns the
lowest key > key</div>
<div style="margin-bottom: 0in;">
K <b>floorKey(key)</b>: Returns the
highest key <= key</div>
<div style="margin-bottom: 0in;">
K <b>lowerKey(key)</b>: Returns the
highest key < key</div>
<div style="margin-bottom: 0in;">
Map.Entry<K,V> <b>pollFirstEntry()</b>:
Returns and removes the first key-value pair</div>
<div style="margin-bottom: 0in;">
Map.Entry<K,V> <b>pollLastEntry()</b>:
Returns and removes the last key-value pair</div>
<div style="margin-bottom: 0in;">
NavigableMap<K,V>
<b>descendingMap()</b>: Returns a NavigableMap in reverse order</div>
<div style="margin-bottom: 0in;">
NavigableSet<K>
<b>descendingKeySet()</b>: Returns a reverse-order key set</div>
<div style="margin-bottom: 0in;">
NavigableMap<K,V> <b>subMap(K
fromKey, boolean fromInclusive, K toKey, boolean toInclusive)</b>:Returns
a part of the map whose keys range from fromKey to toKey.</div>
<div style="margin-bottom: 0in;">
NavigableMap<K,V> <b>headMap(K
toKey, boolean inclusive)</b>:Returns a part of the map whose keys
are less than toKey.</div>
<div style="margin-bottom: 0in;">
NavigableMap<K,V> <b>tailMap(K
fromKey, boolean inclusive)</b>:Returns a part of the map whose keys
are greater than or equal to fromKey.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<script src="https://gist.github.com/anonymous/6049935.js"></script>
<br />
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The example should print in console the
following:</div>
<div style="margin-bottom: 0in;">
keys: [1, 2, 3, 4, 5]</div>
<div style="margin-bottom: 0in;">
Ceiling: 3</div>
<div style="margin-bottom: 0in;">
Higher: 4</div>
<div style="margin-bottom: 0in;">
Floor: 3</div>
<div style="margin-bottom: 0in;">
Lower: 2</div>
<div style="margin-bottom: 0in;">
Descending keys: [5, 4, 3, 2, 1]</div>
<div style="margin-bottom: 0in;">
Head map: {1=one, 2=two}</div>
<div style="margin-bottom: 0in;">
Tail map: {1=one, 2=two}</div>
<div style="margin-bottom: 0in;">
Poll first: 1=one</div>
<div style="margin-bottom: 0in;">
Poll last: 5=five</div>
<div style="margin-bottom: 0in;">
keys: [2, 3, 4]</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
You can notice how the elements in the
map are printed in ascending order, but the map can also be iterated
in descending order with the method descendingKeySet().
</div>
<div style="margin-bottom: 0in;">
The sub maps obtained with the methods
headMap(), tailMap() and others are backed maps ant hey behave just
like any other backed collection this is if submap is modified then
also the map is modified</div>
<div style="margin-bottom: 0in;">
and viceversa.</div>
<br />
<div style="margin-bottom: 0in;">
<a href="http://jlunaquiroga.blogspot.com/2013/07/java-collections-framework-part-6-queues.html">Go to part 6</a></div>
<br />
<br />Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com0tag:blogger.com,1999:blog-4213799477897003979.post-62957694593204700392013-07-14T15:01:00.002-07:002014-03-27T11:20:15.790-07:00Java Collections Framework Part 4 - SetsThis is the sixth part of the tutorial, and this link goes to the previous post <a href="http://jlunaquiroga.blogspot.com/2013/07/java-collections-framework-part-3-lists.html"> java collections framework part 3</a><br />
<div style="margin-bottom: 0in;">
<b><br /></b>
<b>Sets</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
A Set implements the interface
<b>java.util.Se</b><b>t</b><span style="font-weight: normal;">, it has
the same methods as those of the Collection interface. </span>
</div>
<div style="margin-bottom: 0in;">
Sets do not accept duplicate elements,
if the add() method is called with an object that already is in the
set it should return false. The elements of the set must have a good
implementation of the equals() method.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
There are different implementations of
the Set interface they can have order, can be sorted, or neither
this is they can be unordered and unsorted.</div>
<br />
<div style="margin-bottom: 0in;">
<b>HashSet</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The class <b>java.util.HashSet</b> is
an implementation of the Set interface, it is not sorted and it
doesn't have an order. If the hashset is iterated it states that it
does not guarantee that the order will remain constant over time.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The elements of this type of set must
implement the the <b>hashcode()</b> and the <b>equals()</b> methods,
this is because it is implemented as a <b>hash table</b> in which
elements are stored at a position derived from their contents. So,
Two elements are considered equal or duplicate if they return the
same hash code from the hashcode() method and they return true from
testing them with the equals() method.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The Set first gets the hash code from
the element then places the element in a bucket of the hash table for
that hash code, if the bucket already has an element then it tests
for duplicity the elements with their equals().</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCK8WoQ9qBi_zdXDbDnxeG90A5dRxbsOi2ykrrgRIWKQyYEfGpFohrM3yRgSeeqwqIn7H_MnK2w2Cwh7PU2H4mNMveoe-c8J7yhjxpViXqGAaZFJD_3SUQ6Kfy0n-63TYvuj1AR7-g83w8/s1600/hashtable.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCK8WoQ9qBi_zdXDbDnxeG90A5dRxbsOi2ykrrgRIWKQyYEfGpFohrM3yRgSeeqwqIn7H_MnK2w2Cwh7PU2H4mNMveoe-c8J7yhjxpViXqGAaZFJD_3SUQ6Kfy0n-63TYvuj1AR7-g83w8/s1600/hashtable.png" height="300" width="400" /></a></div>
<br />
<div style="margin-bottom: 0in;">
Example:</div>
<script src="https://gist.github.com/anonymous/5996254.js"></script>
<br />
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
In the previous example the Element
class has two implementations of the hashcode() method one that uses
the hashcode of its value attribute of type String and other that
generates random integers, if the implementation that uses the String
is used then the Set would not accept duplicate elements this is
because same strings should generate the same hashcode so the ouptut
with this implementation should not contain any duplicate element as
this:</div>
<div style="margin-bottom: 0in;">
[3, 2, 1, 4]
</div>
<div style="margin-bottom: 0in;">
But if the implementation that
generates random integer is used then the Set would accept duplicate
elements because it would be placing each element in a different
bucket of its hash table, the output would be something like this:.</div>
<div style="margin-bottom: 0in;">
[3, 2, 1, 4, 1]
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>LinkedHashSet</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The class <b>java.util.</b><b>Linked</b><b>HashSet</b>
extends from the class HashSet and therefore is an implementation of
the Set interface. LinkedHashSet is hash table and a doubly-linked
list, it has an order, its iterators will return their elements in
the order in which they were added.</div>
<div style="margin-bottom: 0in;">
The LinkedHashSet doesn't define any
new method, it just adds the linked functionality to the HashSet
class.</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9lcU6R7We-R9sHEpCN3U_mSixKYMUN0Z6uFoGPbwRpIHRaaxSPmA7xLtKZL-lCF-IOiDbRnb9IrYKoLlZBxStXVfoDPQwBVJQchGabwUR7H4L0QDru04G1pDouA80vY7md89lXhRe2m2c/s1600/linkedhashset.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9lcU6R7We-R9sHEpCN3U_mSixKYMUN0Z6uFoGPbwRpIHRaaxSPmA7xLtKZL-lCF-IOiDbRnb9IrYKoLlZBxStXVfoDPQwBVJQchGabwUR7H4L0QDru04G1pDouA80vY7md89lXhRe2m2c/s1600/linkedhashset.jpg" /></a></div>
<div style="margin-bottom: 0in;">
<br /></div>
<br />
<div style="margin-bottom: 0in;">
Example:</div>
<script src="https://gist.github.com/anonymous/5996265.js"></script>
<br />
<br />
<div style="margin-bottom: 0in;">
In the previous example the output
should in the order in which the elements were added, so it should
print this:</div>
<div style="margin-bottom: 0in;">
[ 6, 5, 3, 4, 1, ]</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>TreeSet</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The class <b>java.util.</b><b>TreeSet</b>
is an implementation of the Set interface, it also implements the
java.util.NavigableSet and java.util.SortedSet interfaces, it is an
sorted collection and guarantees that the elements will be in
ascending order, according to their natural order, or by a Comparator
provided at set creation time, depending on which constructor is
used.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The TreeSet class implements methods
that help navigate the set, and some of these methods are:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
E <b>ceiling(e)</b>: Returns the
lowest element >= e</div>
<div style="margin-bottom: 0in;">
E <b>higher(e)</b>: Returns the
lowest element > e</div>
<div style="margin-bottom: 0in;">
E <b>floor(e)</b>: Returns the
highest element <= e</div>
<div style="margin-bottom: 0in;">
E <b>lower(e)</b>: Returns the
highest element < e</div>
<div style="margin-bottom: 0in;">
E <b>pollFirst()</b>: Returns and
removes the first entry</div>
<div style="margin-bottom: 0in;">
E <b>pollLast()</b>: Returns and
removes the last entry</div>
<div style="margin-bottom: 0in;">
NavigableSet <b>descendingSet()</b>: Returns
a NavigableSet in reverse order</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<script src="https://gist.github.com/anonymous/5996286.js"></script>
<br />
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The example should print
</div>
<div style="margin-bottom: 0in;">
First:1</div>
<div style="margin-bottom: 0in;">
Last:5</div>
<div style="margin-bottom: 0in;">
Higher:4</div>
<div style="margin-bottom: 0in;">
Lower:2</div>
<div style="margin-bottom: 0in;">
Ceiling:3</div>
<div style="margin-bottom: 0in;">
Floor:3</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The TreeSet class also has more methods
that return section of its collection, some of this methods are:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
NavigableSet <b>headSet(e, b*)</b>:
Returns a subset ending at element e and exclusive of e</div>
<div style="margin-bottom: 0in;">
NavigableSet <b>tailSet(e, b*)</b>:
Returns a subset starting at and inclusive of element e</div>
<div style="margin-bottom: 0in;">
NavigableSet <b>subSet(s, b*, e, b*)</b>:
Returns a subset starting at element s and ending just before element
e</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The collections that return this
methods are backed collections, this means when an element is added
to the original or to the backed collection, the new entries were
automatically added to the other collection</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<script src="https://gist.github.com/anonymous/5996289.js"></script>
<br />
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The example should print
</div>
<div style="margin-bottom: 0in;">
Set: [a, b, c, d, g]</div>
<div style="margin-bottom: 0in;">
Sub set: [c, d]</div>
<div style="margin-bottom: 0in;">
Set: [a, b, c, d, e, g]</div>
<div style="margin-bottom: 0in;">
Sub set: [c, d, e]</div>
<div style="margin-bottom: 0in;">
Note that the subset was modified and
also the set is modified, this is because subset is a backed
collection of the set.</div>
<br />
<a href="http://jlunaquiroga.blogspot.com/2013/07/java-collections-framework-part-5-maps.html">Go to part 5</a><br />
<div style="margin-bottom: 0in;">
<br /></div>
Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com0tag:blogger.com,1999:blog-4213799477897003979.post-79788328843320582162013-07-07T14:00:00.002-07:002014-03-27T11:20:26.427-07:00Java Collections Framework Part 3 - ListsThis is the sixth part of the tutorial, and this link goes to the previous post <a href="http://jlunaquiroga.blogspot.com/2013/06/java-collections-framework-part-2-basics.html">java collections framework part 2</a><br />
<br />
<div style="margin-bottom: 0in;">
<b>Lists</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
A list implements the interface
<b>java.util.List</b>. Lists are based by indexed elements, they are
ordered by index positions. Lists can contain duplicate elements.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
List have methods based in index that
other collections don't have:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
void <b>add(int index, E element)</b>:
Inserts the specified element at the specified position in this list.</div>
<div style="margin-bottom: 0in;">
boolean <b>addAll(int index,
Collection<? extends E> c)</b>: Inserts all of the elements in
the specified collection into this list at the specified position.</div>
<div style="margin-bottom: 0in;">
E <b>get(int index)</b>: Returns the
element at the specified position in this list.</div>
<div style="margin-bottom: 0in;">
E <b>remove(int index)</b>: Removes the
element at the specified position in this list.</div>
<div style="margin-bottom: 0in;">
E <b>set(int index, E element)</b>:
Replaces the element at the specified position in this list with the
specified element.</div>
<div style="margin-bottom: 0in;">
List <E> <b>subList(int
fromIndex, int toIndex)</b>: Returns a view of the portion of this
list between the specified fromIndex, inclusive, and toIndex,
exclusive.</div>
<div style="margin-bottom: 0in;">
int <b>indexOf(Object o)</b>: Returns
the index of the first occurrence of the specified element in this
list, or -1 if this list does not contain the element.</div>
<div style="margin-bottom: 0in;">
int <b>lastIndexOf(Object o)</b>:
Returns the index of the last occurrence of the specified element in
this list, or -1 if this list does not contain the element.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The class <b>java.util.ArrayList</b> is
an implementation of a list. It stores its element starting at index
0, it is like a growable array. It is NOT synchronized as its
counterpart the java.util.Vector class.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">List <String><string> list = new ArrayList <String> <string>();
list.add("1");
list.add("2");
list.add(2, "3");
System.out.println(list.size());
System.out.println(list.indexOf(“3”));
</string></string></code></pre>
<br />
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the example the index has to be not
bigger than the index of the last element plus one. The size of the
list would be 3 since it contains 3 elements and it would print 2 as
the index of the element “3”, this is because they start at index
0.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>java.util.Vector</b> class
basically is the same as the ArrayList class with the difference that
it is thread safe, this means that its methods are synchronized. The
Vector class may perform slower than the ArrayList class, so if a
list is needed and only one thread will interact with it, so it is
better to choose ArrayList over Vector.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>java.util.Stack</b> class is a
List implementation which extends from Vector class. But it also
implements other functionality besides being and index ordered
collection, it can implement a LIFO (Last In, First Out) collection.
</div>
<div style="margin-bottom: 0in;">
<br />
For this functionality the Stack class
has the following methods:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
boolean <b>empty()</b>: Tests if this
stack is empty.</div>
<div style="margin-bottom: 0in;">
E <b>peek()</b>: Looks at the object at
the top of this stack without removing it from the stack.</div>
<div style="margin-bottom: 0in;">
E <b>pop()</b>: Removes the object at
the top of this stack and returns that object as the value of this
function.</div>
<div style="margin-bottom: 0in;">
E <b>push(E item)</b>: Pushes an item
onto the top of this stack.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">Stack <String><string> stack = new Stack <String><string> ();
stack.push("1");
stack.push("2");
stack.push("3");
stack.push("4");
stack.push("5");
System.out.println(stack .pop());//Removes the top of the stack
System.out.println(stack .peek());//Doesn't remove the element
</string></string></code></pre>
<br />
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the example the element 5 is printed
and removes since it was the top of the stack, then the element 4 is
printed but not removed.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The Stack list it also can act as a
normal list and get its elements with an iterator:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">...
Iterator iter = stack.iterator();
while(iter.hasNext()) {
System.out.print(iter.next()+ " ");
}
</code></pre>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In this way the elements are obtained
as a list not as a stack, this is the first printed element would be
1 then 2 and so on.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The Stack is an old implementation of a
LIFO stack, since java 1.6 new mechanisms were added for this with
the interface java.util.Deque.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Tha <b>java.util.LinkedList</b> class
is a List implementation, it is also an index ordered collection, but
its elements are doubly-linked to one another. This behavior allows
adding or removing from the beginning or end, making it easier to
implement a stack or queue, so it can be a LIFO (Last In, First Out)
or FIFO (First In, First Out) collection. It implements the
java.util.Deque and java.util.Queue interfaces.</div>
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi78s_i48AABlBbtlu-MEsB2ZHCjdps9_x27vza1CmpvRGVswqA6SKGDL97SrFXDCZdhdCT8SvwAb3__Npe6CrefGBgmDi0q9I3zO5faE07pPQJwY-TGltzKN2woATaXPI8bSiQw8o2sQLe/s1600/linkedlist.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi78s_i48AABlBbtlu-MEsB2ZHCjdps9_x27vza1CmpvRGVswqA6SKGDL97SrFXDCZdhdCT8SvwAb3__Npe6CrefGBgmDi0q9I3zO5faE07pPQJwY-TGltzKN2woATaXPI8bSiQw8o2sQLe/s1600/linkedlist.jpg" height="112" width="400" /></a></div>
<div style="margin-bottom: 0in;">
And some of its methods are:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
void <b>addFirst(E e)</b>: Inserts the
specified element at the beginning of this list.</div>
<div style="margin-bottom: 0in;">
void <b>addLast(E e)</b>: Appends the
specified element to the end of this list.</div>
<div style="margin-bottom: 0in;">
boolean <b>offerFirst(E e)</b>: Inserts
the specified element at the front of this list.</div>
<div style="margin-bottom: 0in;">
boolean <b>offerLast(E e)</b>: Inserts
the specified element at the end of this list.</div>
<div style="margin-bottom: 0in;">
E <b>pollFirst()</b>: Retrieves and
removes the first element of this list, or returns null if this list
is empty.</div>
<div style="margin-bottom: 0in;">
E <b>pollLast()</b>: Retrieves and
removes the last element of this list, or returns null if this list
is empty.</div>
<div style="margin-bottom: 0in;">
E <b>peekFirst()</b>: Retrieves, but
does not remove, the first element of this list, or returns null if
this list is empty.</div>
<div style="margin-bottom: 0in;">
E <b>peekLast()</b>: Retrieves, but
does not remove, the last element of this list, or returns null if
this list is empty.</div>
<div style="margin-bottom: 0in;">
E <b>removeFirst()</b>: Removes and
returns the first element from this list.</div>
<div style="margin-bottom: 0in;">
E <b>removeLast()</b>: Removes and
returns the last element from this list.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
These are some of its methods and the
class contains many others, so before using it, its API should be
reviewed.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">LinkedList <String><string> ll = new LinkedList <String><string> ();
ll.add("1");
ll.add("2");
ll.add("3");
ll.add("4");
System.out.println("First: "+ ll.getFirst());
System.out.println("Last: "+ ll.getLast());
ll.addFirst(“5”);
System.out.println("First: "+ ll.pollFirst());
System.out.println("First: "+ ll.peekFirst());
</string></string></code></pre>
<br />
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
The example should print 1, 4 and then
5, 1.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>Lists and Arrays</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The java collections framework has some
mechanisms to convert arrays to lists and lists to arrays, but with
some implications such as the lists and the arrays produced they
become joined or bind.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>java.util.Collection</b>
interface has the <b>toArray()</b> method which returns an array
containing all of the elements in the collection and since List
interface extends from the Collection interface it has an
implementation for this method.The returned array will be "safe"
in that no references to it are maintained by this collection, this
means that in this cases the List and array are not linked or bind.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"></pre>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"><integer><integer><code style="word-wrap: normal;">List <Integer><integer> ls = new ArrayList </integer></code><span style="font-family: arial;"><Integer> ();</span>ls.add(1);
ls.add(2);
ls.add(3);
Object[] obj = ls.<b>toArray()</b>;//Returns Object[] array
for(Object o:obj)
System.out.print(o + " ");
Integer [] in = new Integer[3];
ls.<b>toArray</b>(in);//Copies the list to the array passed
</integer></integer></code></pre>
</div>
</div>
<div style="margin-bottom: 0in;">
<br /></div>
</div>
</div>
<div style="margin-bottom: 0in;">
In the previous example the conversion
to an array from a list the two versions of the toArray() method are
used.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>java.util.Arrays</b> class has
the <b>asList()</b> method, it copies all of the elements from an
array into a List, returns a fixed-size list backed or bind by the
specified array.
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">String [] s = {"one", "two", "three", "four"};
List <string> ls = Arrays.asList(s);
ls.set(0, "1");//If the list is updated the array is updated too and viceversa
System.out.println(“Array updated”+Arrays.toString(s));
//ls.add("five"); //Will produce an error since it is linked to the array
</string></code></pre>
<br />
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the previous example an array is
converted to an array and they are linked or bind, so since arrays
are fixed size no element can be added to the list, and if one
element is updated in the list or in the array the other will see the
change.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>List ordered and search</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The class <b>java.util.Collections</b>
has the <b>sort()</b> method to sort lists in a specific order, it is
overloaded with two versions one that accepts just a list, and the
other that accepts a list and an instance of the
<b>java.util.Comparator</b> interface.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
There are some restrictions with the
version of the sort() method that accepts just a list, and these are:</div>
<ul>
<li><div style="margin-bottom: 0in;">
The list elements mus implement
the java.lang.Comparable interface.</div>
</li>
<li><div style="margin-bottom: 0in;">
All the elements in the list must
be mutually comparable, this means they must be of the same type.</div>
</li>
</ul>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">List </code><String> <string> lst = new ArrayList </string><String> ();<string><string>
lst.add("2");
lst.add("5");
lst.add("4");
lst.add("1");
lst.add("3");
Collections.sort(lst);
System.out.print("Arraylist of strings: ");
System.out.println(lst);
</string></string></pre>
</div>
<br />
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the previous example the String
classes implement Comparable interface and the list only contains
strings, so there should not be a problem ordering the collection.
The collection is ordered according to its natural order, this means
according to the comparable interface, and the output should be
Arraylist of strings: [1, 2, 3, 4, 5]</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The other version of the sort method
the one that takes an instance of Comparator interface besides the
list, the list elements are not required to implement the Comparable
interface, and the sort order is given by the Comparator interface.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">List </code><String> lst = new ArrayList <String>();<string><string>
lst.add("2");
lst.add("5");
lst.add("4");
lst.add("1");
lst.add("3");
Collections.sort(lst, new Comparator <String> <string>(){
public int compare(String one, String two) {
return two.compareTo(one);
}
});
System.out.print("Arraylist of strings: ");
System.out.println(lst);
</string></string></string></pre>
</div>
<br />
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the previous example the list is
ordered according to the Comparator order and it is just reversing
the natural order, the output should be Arraylist of strings: [5, 4,
3, 2, 1]</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The The class <b>java.util.Collections</b>
has the <b>binarySearch</b><b>(</b><b>)</b><span style="font-weight: normal;">
method which searches the list for a specific element, the list must
be sorted before a search is done, if is not the results are
unpredictable.</span></div>
<div style="font-weight: normal; margin-bottom: 0in;">
It returns and int
indicating the index of the element or (-(insertion point) – 1),
where insertion point is the point at which the element would be
inserted into the list</div>
<div style="font-weight: normal; margin-bottom: 0in;">
<br /></div>
<div style="font-weight: normal; margin-bottom: 0in;">
Example (The list
would be the used in the previous examples):</div>
<div style="font-weight: normal; margin-bottom: 0in;">
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">System.out.println("three=" + Collections.binarySearch(ls, "3"));
System.out.println("five="+ Collections.binarySearch(ls, "5"));
</code></pre>
<div style="font-weight: normal; margin-bottom: 0in;">
<br /></div>
<div style="font-weight: normal; margin-bottom: 0in;">
The output of the
example would be 2, -5</div>
<div style="font-weight: normal; margin-bottom: 0in;">
<br /></div>
<div style="font-weight: normal; margin-bottom: 0in;">
If a collection is
ordered with an instance of the Comparator interface, then there is
an overloaded method of binary search in the Colletions interface
which accepts the Comparator to do the search.</div>
<div style="font-weight: normal; margin-bottom: 0in;">
<br />
<a href="http://jlunaquiroga.blogspot.com/2013/07/java-collections-framework-part-4-sets.html">Go to part 4</a></div>
</div>
</div>
Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com0tag:blogger.com,1999:blog-4213799477897003979.post-18340000863137512302013-06-30T15:51:00.000-07:002014-03-27T11:20:34.836-07:00Java Collections Framework Part 2 - BasicsThis is the sixth part of the tutorial, and this link goes to the previous post <a href="http://jlunaquiroga.blogspot.com/2013/06/java-collections-framework-part-1-intro.html">java collections framework part 1</a><br />
<div>
<br /></div>
<div>
<div style="margin-bottom: 0in;">
<b>Iterator</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
An iterator is an object that
implements the interface <b>java.util.Iterator</b>, it has three
methods <b>hasNext()</b>, <b>next()</b> and <b>remove()</b>.
</div>
<div style="margin-bottom: 0in;">
Iterators are used to traverse or
access a collection in a standard way, the <b>java.util.Collection</b>
interface provides the <b>iterator()</b> method so any collection
that implements this interface provides a way to return an iterator.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> Iterator it = collection.iterator() ;
while( it.hasNext() ) {
System.out.println(it.next());
}
</code></pre>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
<b>Iterable</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>java.lang.Iterable</b> interface
was introduced in Java 5, it just has the <b>iterator()</b> method
and
</div>
<div style="margin-bottom: 0in;">
the <b>java.util.Collection </b>interface
extends from this interface. The Iterable interface is used in the
foreach statement in this way, any class that implements the Iterable
interface could be used in the foreach statement.</div>
<div style="margin-bottom: 0in;">
The advantages of the foreach statement
are that the code needed to traverse a collection is reduced and
that no casts are needed to access the elements of a collection.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> for(Object o : collection) {
System.out.println(o);
}
</code></pre>
<br />
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the example the code looks much more
cleaner than before.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
A precaution to take with iterators is
that they are fail-fast, they check collection has not changed. If
they detect a change, a <b>java.util.ConcurrentModificationException</b>
exception is thrown.
</div>
<div style="margin-bottom: 0in;">
This means if a collection is modified
while it is being iterated a <span style="font-weight: normal;">ConcurrentModificationException
is thrown.</span></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>Generics and collections</b></div>
<br /></div>
</div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
Generics were introduced in Java 5,
before that collections could hold any kind of object, there was no
way to guarantee collection type.</div>
<br />
<div style="margin-bottom: 0in;">
Since collections could hold any type
of object, there were no ways to prevente runtime errors such cast
exceptions.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">List list = new ArrayList();
list.add(new Person());
String s = (String) list.get(0);</code></pre>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
The example would rise a
ClassCastException.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
With generics collections have a way to
do a compile time check by enforcing the type of your collections.
All what it needs is just place the type of the collection between
angle brackets.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">List<string> <String> list = new ArrayList <String> <string>();
<b>list.add(new Person());//Compiler error</b>
</string></string></code></pre>
<div style="margin-bottom: 0in;">
<br /></div>
</div>
</div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
Another advantage is that since the
type is now specified at compile, then the cast for getting an
element could be omitted because now the compiler can check if what
you are doing is correct.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">List <String><string> list = new ArrayList <String> <string>();
<b>String s = list.get(0);</b>
</string></string></code></pre>
<div style="margin-bottom: 0in;">
<br /></div>
</div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
Also collection can be iterated in a
for-each statement or with an Iterator with its own type without
doing any cast.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">for (String s : list) {
...
}
.....
Iterator<string> it = collection.iterator() ;
while( it.hasNext() ) {
String s = it.next();
}
</string></code></pre>
<br />
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
There is a wildcard in collections and
generics the “<b>?</b> “ question mark symbol, you have to be
very careful if you used it has many behaviors and restrictions and I
would recommend you to do a further research of it.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
If it is used alone in a collection, it
means it can hold any type of object, but you can not add any element
to it, since the compiler doesn't know its exact type.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">List <?> list = new ArrayList <String> ();
<b>list.add(“Hello world”);//compiler error </b>
</code></pre>
<br />
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
If it is used with the <b>extends</b>
keyword, it means it can hold any type that extends or implements the
type specified, but still can not add elements to it, since the
compiler doesn't know its exact type.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> List <? extends CharSequence> list = new ArrayList <String> ();//OK
List <? extends CharSequence> list = new ArrayList <StringBuffer> ();//OK
</code></pre>
</div>
</div>
</div>
</div>
<br />
<div style="margin-bottom: 0in;">
If it is used with the <b>super</b>
keyword, it means it can hold any super type of the type specified,
in this case elements can be added but of the same type or subtype of
the right element in the super expression.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> class Employee extends Person
.......
List <? super Employee> list = new ArrayList <Person> ();
list.add(new Employee);
</code></pre>
<br />
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the exapmle the class Employee
extends Person, so the list can add any element of type Employee of a
subtype of it.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Java 7 added <b>type inference</b>
which says “You can replace the type arguments required to invoke
the constructor of a generic class with an empty set of type
parameters (<>) as long as the compiler can infer the type
arguments from the context”.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> List<String> list = new ArrayList<>();
list.add("A");//OK
</code></pre>
<br />
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
As I said before there are many other
restrictions with generics so you better check them, before start
using them.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>The java.util.Collection interface </b>
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The Collection interface defines the
core functionality of almost every collection, Maps are different.</div>
<div style="margin-bottom: 0in;">
It defines the following methods:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Adding Elements</div>
<div style="margin-bottom: 0in;">
<b>boolean add(E e):</b>Ensures that
this collection contains the specified element (optional operation).</div>
<div style="margin-bottom: 0in;">
<b>boolean addAll(Collection<?
extends E> c)</b>: Adds all of the elements in the specified
collection to this collection (optional operation).</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Removing Elements</div>
<div style="margin-bottom: 0in;">
<b>void clear()</b>:Removes all of the
elements from this collection (optional operation).</div>
<div style="margin-bottom: 0in;">
<b>b</b><b>oolean remove(Object o)</b>:
Removes a single instance of the specified element from this
collection, if it is present (optional operation).</div>
<div style="margin-bottom: 0in;">
<b>b</b><b>oolean
removeAll(Collection<?> c)</b>: Removes all of this
collection's elements that are also contained in the specified
collection (optional operation).</div>
<div style="margin-bottom: 0in;">
<b>b</b><b>oolean
retainAll(Collection<?> c)</b>: Retains only the elements in
this collection that are contained in the specified collection
(optional operation).</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Contents of collection</div>
<div style="margin-bottom: 0in;">
<b>b</b><b>oolean contains(Object o)</b>:
Returns true if this collection contains the specified element.</div>
<div style="margin-bottom: 0in;">
<b>b</b><b>oolean
containsAll(Collection<?> c)</b>: Returns true if this
collection contains all of the elements in the specified collection.</div>
<div style="margin-bottom: 0in;">
<b>b</b><b>oolean isEmpty()</b>:
Returns true if this collection contains no elements.</div>
<div style="margin-bottom: 0in;">
<b>i</b><b>nt size()</b>: Returns the
number of elements in this collection.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Processing contents</div>
<div style="margin-bottom: 0in;">
<b>Iterator<E> iterator()</b>:
Returns an iterator over the elements in this collection.</div>
<div style="margin-bottom: 0in;">
<b>Object[] toArray()</b>: Returns an
array containing all of the elements in this collection.</div>
<div style="margin-bottom: 0in;">
<b><T> T[] toArray(T[] a)</b>:
Returns an array containing all of the elements in this collection;
the runtime type of the returned array is that of the specified
array.</div>
<br />
<div style="margin-bottom: 0in;">
<a href="http://jlunaquiroga.blogspot.com/2013/07/java-collections-framework-part-3-lists.html">Go to part 3</a></div>
</div>
</div>
Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com2tag:blogger.com,1999:blog-4213799477897003979.post-87437946640400748002013-06-23T15:32:00.000-07:002014-03-27T11:20:45.820-07:00Java Collections Framework Part 1 - IntroContinuing with another series of articles about java, now I'm going to try to explain the java collections framework, hoping you can get something from it.<br />
<br />
<div style="margin-bottom: 0in;">
A collection in java is an object that
represents a data structure which groups data or other objects.</div>
<div style="margin-bottom: 0in;">
The collection framework is a set of
interfaces and classes from the packages java.util and
java.util.concurrent, some of the core interfaces are Collection,
Set, List, Map, Queue, SortedSet, SortedMap, and so on. Each one of
these interfaces has a model or structure for organizing objects.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The next figure shows the interface and
class hierarchy of the interfaces and classes in the collection
framework.<br />
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgrr5G9hK6ncIfA3p7DwahuHzTdxaW1rwtAagjt-zyLdqgScdXFJEoHDoWwGn-qbA5QUAZ3XMcHijbWCX-YoJNQbeARdxD24Bq4ud5xv2mUbKDB7amum9Blycti_aAU3jZd4A4lTftuA4IA/s1600/collections.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgrr5G9hK6ncIfA3p7DwahuHzTdxaW1rwtAagjt-zyLdqgScdXFJEoHDoWwGn-qbA5QUAZ3XMcHijbWCX-YoJNQbeARdxD24Bq4ud5xv2mUbKDB7amum9Blycti_aAU3jZd4A4lTftuA4IA/s1600/collections.jpg" height="281" width="400" /></a></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The basic operations in a collection
are add, remove and find an object, also iterate objects through the
collection.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The main types of collections are List,
Set , Queue and Map. List, Set, Queue extend from the Collection
interface, and Map doesn't, a brief description of each type of
collection is the following:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>List</b>: A list is a collection
that groups objects with an order, assigns an index to each element.</div>
<div style="margin-bottom: 0in;">
<b><br /></b></div>
<div style="margin-bottom: 0in;">
<b>Set</b>: A set is a collection that
groups object without an order and without duplicates, each element
is unique.</div>
<div style="margin-bottom: 0in;">
<b><br /></b></div>
<div style="margin-bottom: 0in;">
<b>Queue</b>: A queue is a collection
that groups objects with a certain order, they are arranged by the
order in which they are processed.</div>
<div style="margin-bottom: 0in;">
<b><br /></b></div>
<div style="margin-bottom: 0in;">
<b>Map</b>: A map is a collection that
associates each object with an identifier, it uses key-value
associations to store and retrieve elements, also the identifiers
must be unique.</div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Each of this type is represented by an
interface in the collection framework as the previous figure shows,
and an implementation of a collection (concrete class) implements one
of this interface to define its type, but it can implement other
interfaces to add or achieve another behavior.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
A collection can be sorted, unsorted,
ordered and unordered.
</div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
An ordered collection is a collection
that can be iterated in a specific order, lists are indexed so they
can be iterated through their index, another order would be the LIFO
(Last-In, First-Out) or FIFO (First-In, First-Out) collections.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
A sorted collection is a collection
that its elements were set by a rule, like a natural order, its
position in the collection is determined by a condition or rule set
by the programmer. To achieve this the collection framework uses the
<b>java.lang.Comparable</b> interface and the <b>java.util.Comparator</b>
interface.</div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
There are some restrictions or
recommendations in the implementation of the elements of some
collections such as the ones that no duplicate are allowed or its
elements are sorted. So is good to know some of these before getting
into these collections.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>equals()</b> method of the
java.lang.Object class tests if two objects are equal, if this method
is not overridden in an object its behavior is given by its default
implementation which only tests if two objects reference are the same
like the “==” operator. To provide a better implementation of the
equals() it must be overridden and test if the variables of an object
are the same to one that is compared to .</div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
Example</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class Person {
private String name;
...
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!obj instanceof Person) {
return false;
}
.......
return this.name.equalsIgnoreCase((((Person)obj).name);
}
}
</code></pre>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
In the example, the equals() test for
if the name of the objects is the same then both objects are equal.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>hashCode()</b> method of the
java.lang.Object class returns a hashcode for the object and its
contract says If two objects are equal according to the
equals(Object) method, then calling the hashCode method on each of
the two objects must produce the same integer result, if two objects
are unequal() it is recommended to return different values.</div>
<div style="margin-bottom: 0in;">
In order to accomplish this restriction
of two equal objects return the same hashcode, it is recommended to
use in the hashcode() the same instance variables used in the
equals().</div>
<br /></div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
Example</div>
</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class Person {
private String name;
...
public boolean equalsIgnoreCase(Object obj) {
if (this == obj) {
return true;
}
if (!obj instanceof Person) {
return false;
}
.......
return this.name.equals(((Person)obj).name);
}
public int hashCode() {
return this.name.hashCode();
}
}
</code></pre>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the example two equals objects would
return the same hashcode and two different objects would return
different hashcodes.
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
You have to know that there is more
about these methods or contracts, but for the purpose of the blog
with this basic information is alright.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
These methods are used in the “hash“
collections that don't allow duplicate elements.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>java.lang,Comparable</b>
interface must be implemented by elements of a collection that is
sorted, it helps to give a natural order to the collection. It only
has the <b>compareTo()</b> method, it compares ans object with the
specified object for order. Returns a negative integer, zero, or a
positive integer as this object is less than, equal to, or greater
than the specified object.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class Person implements Comparable <Person>{
private String name;
......
public int compareTo(Person p) {
return this.name.compareTo(p);
}
}
</code></pre>
<div style="margin-bottom: 0in;">
<br /></div>
</div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the expample since the name
attribute is a String an Strings implement the comparable interface
the is ok to call this method on the attribute.<br />
<br />
<a href="http://jlunaquiroga.blogspot.com/2013/06/java-collections-framework-part-2-basics.html">Go to part 2</a></div>
</div>
Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com1tag:blogger.com,1999:blog-4213799477897003979.post-2390852829805347832013-06-09T15:25:00.001-07:002014-03-27T11:20:58.446-07:00Java Concurrency Part 7This is the seventh and final part of the tutorial, and this link goes to the previous post <a href="http://jlunaquiroga.blogspot.com/2013/06/java-concurrency-part-6.html">java concurrency part 6</a><br />
<br />
<div style="margin-bottom: 0in;">
<b>Utility Classes For Synchronization</b></div>
<div style="margin-bottom: 0in;">
<b><br /></b></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
A semaphore has a counter that allows the access to a shared
resource, it is similar to the Lock interface but when a thread wants
to acquire a semaphore it checks its counter and if it is greater
than zero, then the thread acquires the semaphore and it decrements
the counter. But if the counter is zero the thread waits until the
counter is incremented.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<div style="margin-bottom: 0in;">
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class Resource {
<b>Semaphore semaphore = new Semaphore(2);//Indicates two threads can access the resource at the same time. </b>
public void lock() {
<b> semaphore.acquire();//If the counter is zero the thread sleeps otherwise it decrements it and gets the access </b>
System.out.println(“Begining thread ” + Thread.currentThread().getName() + “has the lock”);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(“Ending thread ” + Thread.currentThread().getName() + “has the lock”);
<b> semaphore.release();//Release the semaphore and increments the counter </b>
}
}
.......
</code></pre>
</div>
<br />
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the example the <b>acquire()</b> method obtains the semaphore if
the counter is greater than zero, otherwise it waits until it increments
and decrements the counter, then the thread that obtains the
semaphore execute the resource and finally it executes the <b>release()</b>
method and increments the counter.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
If the semaphore initializes its counter with a value of one then it
is called a binary semaphore and it behaves just like the
java.util.concurrent.locks.Lock interface.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>CountDownLatch</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The CountDownLatch can be used to make one thread wait until N
threads have completed some action, or some action has been completed
N times. It has a count and it is initialized with an integer value,
this count is the number actions to wait for.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The CountDownLatch has the method <b>countdown()</b> method which
decreases the internal count, and the <b>await()</b> method blocks or
puts to sleep a thread until the count reaches zero.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<div style="margin-bottom: 0in;">
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class Test implements Runnable {
//CountDownLatch controls the answer of 10 questions
private final <b>CountDownLatch controller = new CountDownLatch(10); </b>
public void setQuestionAnswered(){
<b>controller.countDown();</b>// Decrements the counter
}
public void run() {
try {
<b>controller.await();</b>// Wait for all the question to be answered
// Starts the test evaluation
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
</code></pre>
</div>
</div>
<br />
<div style="margin-bottom: 0in;">
In the example the task Test will wait to evaluate until all the
questions of the test are answered.</div>
<div style="margin-bottom: 0in;">
Other tasks will call the setQuestionAnswered() which calls the
countDown(), decreasing the counter, since the CountDownLatch is
initialized with a value of 10, the countDown() method has to be
called 10 times in order to proceed after the await() method to
evaluate the test.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>CyclicBarrier</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The CyclicBarrier allows to a set of threads to all wait for each
other or to reach a common barrier point, it is simlar to the
CountDownLatch class, but it has some diferences. It is also
initialized with an integer value known as parties or the number of
threads involve, but it has an optional parameter which is a Runnable
that will be executed when the threads arrive the common point.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The CyclicBarrier has the <b>await()</b> method which blocks until
all the parties invoke this method.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<div style="margin-bottom: 0in;">
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class Test implements Runnable {
private CountDownLatch controller = new CountDownLatch(10);
private CyclicBarrier cyclicBarrier;
public Test(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
}
public void setQuestionAnswered(){
controller.countDown();
}
@Override
public void run() {
try {
controller.await();
// Starts the test evaluation
<b>cyclicBarrier.await();//WAITS FOR ALL THREADS OR PARTIES </b>
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public double getTestResult() {
}
}
..........
final Test [] tests = new Test[10];
CyclicBarrier cyclicBarrier = new CyclicBarrier(10,
new Runnable(){
public void run() {
//Get the media or average of the tests
..........
}
});
for(int i=0; i<tests.length; i++)
tests[i] = new Test(cyclicBarrier);
..........
</code></pre>
</div>
<br />
<div style="margin-bottom: 0in;">
In the example the same Test class used as in the previous example,
but here the CyclicBarrier will get the average or media result from
all the tests. When all the Test thread finish the exam the
CyclicBarrier will execute the Runnable object that is passed as
parameter and will get the average of the tests.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>Phaser</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The Phaser class is similar to CyclicBarrier and CountDownLatch but
more flexible, the tasks or threads synchronize in steps or phases.
The parties registered to synchronize on a phaser may vary over
time, it can dynamically change with the methods register(),
bulkRegister().</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The arriveAndDeregister() mehtod notifies the phasar that a task has
finished and will not participate in future phases decreasing the
number of parties.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The arriveAndAwaitAdvance() method makes a task wait for all the
participants to finish.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<div style="margin-bottom: 0in;">
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class Task implements Runnable {
private Phaser phaser;
public Task(Phaser phaser) {
this. phaser = phaser;
}
@Override
public void run() {
try {
<b>phaser.arriveAndAwaitAdvance(); </b>
//Start phase1
<b>phaser.arriveAndAwaitAdvance();</b>
//Start phase2
<b>phaser.arriveAndAwaitAdvance(); </b>
//Start phase3
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
..........
final Task [] tasks = new Task[10];
<b> Phaser phaser = new Phaser(10);</b>
for(int i=0; i<tasks .length; i++)
tasks[i] = new Task(phaser);
..........
</code></pre>
</div>
<br />
<div style="margin-bottom: 0in;">
In the example the phaser is set to 10 parties, when all the tasks
reach the first <b> </b>arriveAndAwaitAdvance() they will start the
phase 1 and then they will have to wait to all threads again before
they start phase 2, and so on.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>Exchanger</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<a href="https://www.blogger.com/blogger.g?blogID=4213799477897003979" name="__DdeLink__4634_1670658659"></a>
The Exchanger class synchronizes two threads in a point, when both
get to this point they swap or interchange an object. An Exchanger
may be viewed as a bidirectional form of a SynchronousQueue.
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The Exchanger class has the <b>exchange()</b> method which
interchanges data between threads.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The producer consumer example can be implemented with this mechanism.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class Consumer extends Thread {
private Exchanger <String> exchanger;
public Consumer(Exchanger exchanger) {
this.exchanger = exchanger;
}
public void run() {
String message = "";
while (!message.equalsIgnoreCase("end")) {
//message = mb.take();
try {
message = <b>exchanger.exchange(message);//Waits and exchanges messages with the producer; </b>
System.out.print(message + " ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Producer extends Thread {
private Exchanger exchanger;
public Producer(Exchanger exchanger) {
this.exchanger = exchanger;
}
public void run() {
String [] messages = {"Hello", "world", "end"};
for (String msg:messages) {
try {
<b>exchanger.exchange(msg);//Waits and exchanges messages with the consumer;</b>
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
.......
Exchanger <String> exchanger = new Exchanger<String>();
Consumer consumer = new Consumer(exchanger);
Producer producer = new Producer(exchanger);
consumer.start();
producer.start();
.......
</code></pre>
<br />
<br />
<div style="margin-bottom: 0in;">
This example is similar to the one in the part 4, but instead of
having a class that acts as a monitor, here the Exchanger does that
job and synchronizes the messages between the threads.</div>
<br />
<br />Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com5tag:blogger.com,1999:blog-4213799477897003979.post-90304474544158332332013-06-02T13:09:00.001-07:002014-03-27T11:21:08.111-07:00Java Concurrency Part 6This is the sixth part of the tutorial, and this link goes to the previous post <a href="http://jlunaquiroga.blogspot.com/2013/05/java-concurrency-part-5.html">java concurrency part 5</a><br />
<br />
<div style="margin-bottom: 0in;">
<b>Fork/Join
Framework</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The fork/join framework is an implementation of the ExecutorService
interface that uses a different approach, it solves tasks splitting
them into smaller tasks recursively.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgX7GjHQ9otZ596Jvs0qfB0XmTBhh2BvY-zn8oxwNsZ_yHg_fqnL93BgLZ_6kT0LVSAWUwHOwvVj5fjBOhQ-5pN1nU51ai47VBaaVZorTUNarfWo1-iSYMiSAvVlsjT3Nm3rO4smpRkHLv-/s1600/fork_join.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgX7GjHQ9otZ596Jvs0qfB0XmTBhh2BvY-zn8oxwNsZ_yHg_fqnL93BgLZ_6kT0LVSAWUwHOwvVj5fjBOhQ-5pN1nU51ai47VBaaVZorTUNarfWo1-iSYMiSAvVlsjT3Nm3rO4smpRkHLv-/s1600/fork_join.jpg" height="198" width="400" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
</div>
<div style="margin-bottom: 0in;">
The fork/join framework implements the work-stealing algorithm, this
algorithm says worker threads that run out of things to do can steal
tasks from other threads that are still busy. Put it in another way,
it says a thread that is waiting for the finalization of other
threads, looks for threads that have not been executed and executes
them.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Basically there are two operations, one to divide a task into smaller
tasks “<b>fork</b>”, and other to wait for the tasks to finalize
“<b>join</b>”.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>java.util.concurrent.ForkJoinPool</b> class implements the
ExecutorSevice interface and also implements the work-stealing
algorithm.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>java.util.concurrent.ForkJoinTask</b> class implements the
Future interface, is an abstract class for the tasks that execute
within the ForkJoinPool, provides the <b>fork()</b> method to arrange
asynchronous execution and the <b>join()</b> method for proceed until
the task's result has been computed.
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<div style="margin-bottom: 0in;">
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class IncrementTask extends <b>RecursiveAction </b>{
private int [] array;
private int first;
private int last;
public IncrementTask(int [] array, int first, int last) {
this.array = array;
this.first = first;
this.last = last;
}
protected void <b>compute() </b>{
if (last - first < 10) {
increment();
System.out.println("Completed from "+first+", to: "+last);
} else {
int middle = (last + first) / 2;
System.out.println("Pending tasks: " + getQueuedTaskCount());
IncrementTask it1 = new IncrementTask(array, first, middle + 1);
IncrementTask it2 = new IncrementTask(array, middle + 1, last);
<b>invokeAll(it1, it2); //Waits for the finalization of these tasks </b>
}
}
private void increment() {
for (int i = first; i < last; i++) {
array[i] = ++array[i];
}
}
}
...............
int array [] = new int [100];
Random random = new Random();
for (int i=0; i<array.length; i++) {
array[i] = random.nextInt(10000);
}
System.out.print("Array: {");
for (int i=0; i<array.length; i++) {
System.out.print(array[i] + ", ");
}
System.out.print(" }");
<b>IncrementTask task = new IncrementTask(array, 0, array.length); </b>
<b>ForkJoinPool pool = new ForkJoinPool(); </b>
<b>pool.execute(task); </b>
do {
System.out.println("Threads active: " + pool.getActiveThreadCount());
try {
TimeUnit.MILLISECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (!task.isDone());
pool.shutdown();
if (task.isCompletedNormally()) {
System.out.println("The process has completed normally");
}
System.out.print("Array incremented: {");
for (int i=0; i<array.length; i++) {
System.out.print(array[i] + ", ");
}
System.out.print(" }");
...............
</code></pre>
</div>
<br />
<div style="margin-bottom: 0in;">
<a href="https://www.blogger.com/blogger.g?blogID=4213799477897003979" name="__DdeLink__3587_1291045037"></a>In the example the IncrementTask class extends the
<b>java.util.concurrent.</b><b>RecursiveAction </b>class, this task
implements its logic int the <b>compute()</b> method, it increments
the value of the elements of an array of integers. But it only
increments 10 elements per task, if the size of the array is bigger
than that, it creates two subtasks and executes them through the
<b>invo</b><b>k</b><b>eAll()</b> method of the RecursiveAction class.
In this way the tasks are calling recursively.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>RecursiveAction</b> class extends the ForkJoinTask class, it
has the invokeAll() method which executes subtasks and waits for its
finalization before continuing, while it is waiting for the subtasks
to end, the worker thread takes another task and excutes it.
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The Fork/Join framework provides another class to return a value from
a task, the <b>java.util.concurrent.</b><b>RecursiveTask</b> this
class behaves just like the RecursiveAction class but its compute()
method returns a value.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<div style="margin-bottom: 0in;">
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class SumTask extends RecursiveTask <<b>Integer</b>> {
private int [] array;
private int first;
private int last;
public SumTask(int[] array, int first, int last) {
this.array = array;
this.first = first;
this.last = last;
}
protected <b>Integer</b> compute() {
int sum = 0;
if (last - first < 10) {
<b>sum = add();</b>
System.out.println("Completed from "+first+", to: "+last);
} else {
int middle = (last + first) / 2;
System.out.println("Pending tasks: " + getQueuedTaskCount());
SumTask st1 = new SumTask(array, first, middle + 1);
SumTask st2 = new SumTask(array, middle + 1, last);
<b>invokeAll(st1, st2);</b>
try {
<b> sum += st1.get(); </b>
<b> sum += st2.get(); </b>
} catch (Exception ex) {
ex.printStackTrace();
}
}
<b>return sum; </b>
}
private Integer add() {
int sum = 0;
for (int i = first; i < last; i++) {
sum += array[i];
}
return sum;
}
}
......................
int array [] = new int [100];
Random random = new Random();
for (int i=0; i<array.length; i++) {
array[i] = random.nextInt(100);
}
System.out.print("Array: {");
for (int i=0; i<array.length; i++) {
System.out.print(array[i] + ", ");
}
System.out.print(" }");
SumTask task = new SumTask(array, 0, array.length);
ForkJoinPool pool = new ForkJoinPool();
pool.execute(task);
do {
System.out.println("Threads active: " + pool.getActiveThreadCount());
try {
TimeUnit.MILLISECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (!task.isDone());
pool.shutdown();
if (task.isCompletedNormally()) {
System.out.println("The process has completed normally");
}
try {
System.out.print("Array sum is:" + <b>task.get()</b>);
} catch (Exception ex) {
ex.printStackTrace();;
}
......................
</code></pre>
</div>
<br />
<div style="margin-bottom: 0in;">
In the example the SumTask class extends the RecursiveTask class with
Integer as its type, the SumTask will add all the elements of an
array. But it only adds 10 elements per task, if the size of the
array is bigger than that, then it creates two subtasks and executes
them through the <b>invo</b><b>k</b><b>eAll()</b> method of the
RecursiveTask class just as the previous example, but in contrast to
the previos example each task returns the sum of the 10 elements, and
if subtasks were created then adds the result of the subtasks.
</div>
<div style="margin-bottom: 0in;">
The value from the subtasks is obtained with the <b>get()</b> method from the
Future interface.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Until now all the tasks have been executed synchronously, when a task
calls the invokeAll() method it waits until the tasks sent to execute
through this method finish, with this the work-stealing algorithm is
implemented, assigning a new task to the worker when the task is
waiting.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Tasks also can be executed asynchronous with the <b>for</b><b>k</b><b>()</b>
and <b>join()</b> methods of the ForkJoinTask calss, the fork()
method executes asynchronously a subtask continuing with the
execution of the task, and the join() method waits for the result of
the subtask.
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Using this mechanism the work-stealing algorithm can not be
implemented since the task continues executing when creates a
subtask.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<div style="margin-bottom: 0in;">
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class SumTaskAsync extends RecursiveTask <Integer> {
private int [] array;
private int first;
private int last;
public SumTaskAsync(int[] array, int first, int last) {
this.array = array;
this.first = first;
this.last = last;
}
protected Integer compute() {
int sum = 0;
if (last - first < 10) {
sum = add();
System.out.println("Completed from "+first+", to: "+last);
} else {
int middle = (last + first) / 2;
System.out.println("Pending tasks: " + getQueuedTaskCount());
SumTask st1 = new SumTask(array, first, middle + 1);
SumTask st2 = new SumTask(array, middle + 1, last);
<b>st1.fork();</b>
<b>st2.fork();//Continues with execution</b>
<b>sum += st1.join();//Waits for the result </b>
<b>sum += st2.join();</b>
}
return sum;
}
private Integer add() {
int sum = 0;
for (int i = first; i < last; i++) {
sum += array[i];
}
return sum;
}
}
</code></pre>
</div>
<br />
<div style="margin-bottom: 0in;">
In the example the SumTaskAsync executes its subtasks asynchronous
using the fork() and join() methods.<br />
<br />
<a href="http://jlunaquiroga.blogspot.com/2013/06/java-concurrency-part-7.html">Go to part 7</a></div>
Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com3tag:blogger.com,1999:blog-4213799477897003979.post-57968017073551466152013-05-26T14:58:00.001-07:002014-03-27T11:21:19.529-07:00Java Concurrency Part 5This is the fifth part of the tutorial, and this link goes to the previous post <a href="http://jlunaquiroga.blogspot.com/2013/05/java-concurrency-part-4.html">java concurrency part 4</a><br />
<br />
<div style="margin-bottom: 0in;">
<b>Executor
Framework</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
When a program that runs many concurrent tasks, all the code related
to the threads has to be implemented, create a thread object per
task, execute the thread, obtain its results, and so on. </div>
<div style="margin-bottom: 0in;">
This can
bring some problems such as manage not efficiently the resources of
the computer and affect the performance of the application.
</div>
<div style="margin-bottom: 0in;">
For large applications a better approach is needed and the executor
framework can help with this.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The Executor Framework separates the task of thread creation, its
execution and management, it encapsulates functionality and it
improves the performance using a pool of threads.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The way the executor framework works is really simple, it only
requires instances of Runnable or Callable objects and it takes care
of the rest.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>java.util.concurrent.Executors</b> is a utility class for
create pools, factories and services for the executor framework.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">public class Server {
<b>private ThreadPoolExecutor executor;</b>
public Server() {
<b>executor = (ThreadPoolExecutor)Executors.newCachedThreadPool();//Creates the executor object or a thread pool</b>
}
public void executeTask(Task task) {
<b>executor.execute(task);//executes a task</b>
}
public void endServer() {
<b>executor.shutdown();// This method shuts down the executor</b>
}
}
public class Task implements Runnable {
private String name;
public Task(String name) {
this.name = name;
}
public void run() {
System.out.println(Thread.currentThread().getName() + ", created on: " + new Date());
try {
TimeUnit.SECONDS.sleep((long) (Math.random() * 10));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ", finished on: " + new Date());
}
}
...........
Server server = new Server();
for (int i = 0; i < 10; i++) {
Task task = new Task("Task " + i);
server.executeTask(task);
}
server.endServer();
...........
</code></pre>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
In the previous example the Executors class created a
<b>java.util.concurrent.</b><b>ThreadPoolExecutor</b> object, this
class is an implementation of <b>java.util.concurrent.ExecutorService</b>
interface. Although ThreadPoolExecutor can be created directly using
its constructors, it is recommended to use the Executors class.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The ThreadPoolExecutor uses the execute() method to execute a
Runnable or Callable. It has other methods as getPoolSize(),
getCompleteTaskCount() to get the state of the pool.</div>
<div style="margin-bottom: 0in;">
The ThreadPoolExecutor has to be terminated explicitly by calling
the endServer() method, otherwise it won't end and the program will
never finish.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
To avoid to overload the application and provoke a poor performance,
the Executors class has the method <b>newFixedThreadPool(int
nThreads)</b> which creates a fixed-size thread executor.This executor has a maximum number of threads indicated by the
parameter nThreads,and as the java api says “At any point, at most
nThreads threads will be active processing tasks. If additional tasks
are submitted when all threads are active, they will wait in the
queue until a thread is available. If any thread terminates due to a
failure during execution prior to shutdown, a new one will take its
place if needed to execute subsequent tasks”.<br />
<br />
Example:</div>
</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> ......
public Server() {
executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
}
......
</code></pre>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the example the executor is created with a maximum of 5 threads at
a time, this means if more than 5 tasks are send to execute only 5
will and the remaining will be blocked until there is a free thread
to process them.</div>
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
<b>Tasks that
return a value</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The executor framework can run tasks that return a value, this is
another advantage of using this framework. For this mechanism the
<b>java.util.concurrent.Callable</b> interface is used, instead of
having a run() it offers a call() method, which returns any type of
object that is specified in the generic form:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
public interface Callable<V> {</div>
<div style="margin-bottom: 0in;">
V call() throws Exception;</div>
<div style="margin-bottom: 0in;">
}</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
The ExecutorService has the <b>submit()</b> method which accepts
objects of type Callable and executes them, this method returns an
object of the type <b>java.util.concurrent.Future</b>, the Future
interface has methods to obtain the result generated by the Callable
object.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class MultiplyCalculator implements Callable<Integer> {
private int operator1;
private int operator2;
public MultiplyCalculator(int operator1, int operator2) {
this.operator1 = operator1;
this.operator2 = operator2;
}
public Integer call() throws Exception {
return operator1 * operator2;
}
}
..........
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);//Maximum 2 threads at a time
<b>List<Future<Integer>> resultList = new ArrayList<Future<Integer>>(); </b>
for (int i = 0; i < 10; i++) {
MultiplyCalculator calculator = new MultiplyCalculator((int)(Math.random()*10), (int)(Math.random()*10));
Future<Integer> result = executor.submit(calculator);
resultList.add(result);
}
while (<b>executor.getCompletedTaskCount()</b> < resultList.size()) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}//Waits for the tasks to complete
for (int i = 0; i < resultList.size(); i++) {
Future<Integer> result = resultList.get(i);
try {
System.out.println("The result from the task "+i+ " is:" + <b>result.get()</b>);
} catch (Exception e) {
e.printStackTrace();
}
}
..........
</code></pre>
<div style="margin-bottom: 0in;">
<br /></div>
</div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the previous example, the Callable objects that perform a multiply
operation are sent to the executor using the submit() method, the
program waits until all the tasks are finished verifying the
getCompletedTaskCount() method of the executor, once they are done
the results of the operations are obtained with the get() method of
the Future object.</div>
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
The ExecutorService has the <b>invokeAny(</b><b>tasks</b><b>)</b>
method which receives a Collection of tasks then it executes them and
<b>returns the result of the firs task that finishes</b> without
throwing an Exception, tasks that have not completed are cancelled.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
An example where this method could be used is for look up services,
an application that wants to look up a database connection in
different servers, the first task that finds the service available is
the one that is going to be used, the other tasks are ignored.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The previous example implemented with the invokeAny() method would
look like this:</div>
</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> .................
ExecutorService executor = (ExecutorService) Executors.newCachedThreadPool();
List<MultiplyCalculator> taskList = new ArrayList<MultiplyCalculator>();
for (int i = 0; i < 10; i++) {
MultiplyCalculator calculator = new MultiplyCalculator((int)(Math.random()*10), (int)(Math.random()*10));
taskList.add(calculator);
}
try {
<b>Integer result = executor.invokeAny(taskList); </b>
System.out.println("The result from the first task in finish is:" + result);
} catch (Exception e) {e.printStackTrace();}
// Shutdown the Executor
executor.shutdown();
.............
</code></pre>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
The ExecutorService has another mechanism for running multiple tasks
and process the result of all tasks, the <b>invokeA</b><b>ll</b><b>(</b><b>tasks</b><b>)</b>
method receives a Collection of tasks, executes them and returns a
List of Future objects.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> ExecutorService executor = (ExecutorService) Executors.newCachedThreadPool();
List<MultiplyCalculator> taskList = new ArrayList<MultiplyCalculator>();
for (int i = 0; i < 10; i++) {
MultiplyCalculator calculator = new MultiplyCalculator((int)(Math.random()*10), (int)(Math.random()*10));
taskList.add(calculator);
}
<b>List<Future<Integer>> resultList = null; </b>
try {
<b>resultList = executor.invokeAll(taskList); </b>
} catch (Exception e) {e.printStackTrace();}
executor.shutdown();
for (int i = 0; i < resultList.size(); i++) {
Future<Integer> result = resultList.get(i);
try {
System.out.println("The result from the task "+i+ " is:" + result.get());
} catch (Exception e) {
e.printStackTrace();
}
}
</code></pre>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the example instead of sending each task to the executor with the
submit() method, all the tasks are grouped in a list and send them to
execute through the invokeAll() method.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>Schedule Tasks</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The Executors utility class can create a pool that schedules tasks after a given delay, or executes them periodically. This pool
implements the <b>java.util.concurrent.ScheduledExecutorService</b>
interface.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<div style="margin-bottom: 0in;">
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> ScheduledExecutorService executor=
(ScheduledExecutorService)Executors.<b>newScheduledThreadPool(1); </b>
List<Future<Integer>> resultList = new ArrayList<Future<Integer>>();
for (int i=0; i<5; i++) {
MultiplyCalculator calculator = new MultiplyCalculator((int)(Math.random()*10), (int)(Math.random()*10));
Future future<Integer> =<b> executor.schedule(calculator,i+1 , TimeUnit.SECONDS); </b>
resultList.add(future);
}
executor.shutdown();
// Waits for the finalization of the executor
try {
executor.<b>awaitTermination(1, TimeUnit.DAYS); </b>
} catch (InterruptedException e) {
e.printStackTrace();
}
..............
</code></pre>
</div>
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
In the example a scheduled pool is created with a pool size of 1,
then each thread is scheduled using the <b>s</b><b>c</b><b>h</b><b>e</b><b>dule()</b>
method, this method receives as parameters the task to execute, the
period of time to wait before the execution and unit of time.</div>
<div style="margin-bottom: 0in;">
The executor uses the <b>awaitTermination()</b> method which blocks
until all tasks have completed or a timeout occurs.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<b>Rejected tasks</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
If a task is send to the executor between the shutdown() and the end
of its execution, the task is rejected. The executor provides a
mechanism to manage this, it just requires an instance of an object
that implements the java.util.concurrent.RejectedExecutionHandler
interface.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<div style="margin-bottom: 0in;">
<br />
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class RejectedTaskController implements RejectedExecutionHandler {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println("The task has been rejected");
}
}
........
RejectedTaskController controller = new RejectedTaskController();
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
executor.setRejectedExecutionHandler(controller)
........
</code></pre>
</div>
<br />
<div style="margin-bottom: 0in;">
When a task is rejected the <b>rejecedExecution()</b> method of the
RejectedExecutionHandler instance is called.<br />
<br />
<a href="http://jlunaquiroga.blogspot.com/2013/06/java-concurrency-part-6.html">Go to part 6</a></div>
Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com0tag:blogger.com,1999:blog-4213799477897003979.post-11121093138587781372013-05-19T13:42:00.005-07:002014-03-27T11:21:27.905-07:00Java Concurrency Part 4This is the fourth part of the tutorial, and this link goes to the previous post <a href="http://jlunaquiroga.blogspot.com/2013/05/java-concurrency-part-3.html">java concurrency part 3</a><br />
<br />
<div style="margin-bottom: 0in;">
<b>Thread Deadlock</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Deadlock happen when two threads are blocked waiting for an object's
lock that each thread posses. Neither can run until the other gives
up its lock, so they will wait forever or blocked indefinitely.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class Deadlock extends Thread {
Resource a;
Resource b;
public Deadlock(Resource a, Resource b,String name) {
super(name);
this.a = a;
this.b = b;
}
public void run(){
synchronized(a) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(b) {
}
System.out.println("Thread " + this.getName() + " has ended");
}
}
}
..........
Resource a = new Resource();
Resource b = new Resource();
Deadlock d1 = new Deadlock(a, b, "one");
Deadlock d2 = new Deadlock(b, a, "two");
d1.start();
d2.start();
..........
</code></pre>
<div style="margin-bottom: 0in;">
<br /></div>
In the previous example no message is print to console because the threads
never reached the System.out.println() sentence, both threads stay
forever waiting in the second synchronized() sentence.<br />
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
What happens is that the first thread “d1” acquires the “a”
Resource lock and the second thread “d2” acquires the “b”
resource lock, then both threads sleep for 10 seconds, the sleeping time is for
giving time to each thread to run and acquire the lock, then after
waking up the deadlock situation is set, each thread will try to get
the resource the other thread posses, “d1” will try to acquire “b”
and “d2” will try to acquire “a”.</div>
<br />
<div style="margin-bottom: 0in;">
One way to avoid the deadlock situation is to use Locks and obtain
the lock using tryLock() method</div>
<br />
<div style="margin-bottom: 0in;">
<b>Thread
interaction</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Threads can communicate to other threads about their status of an
event. The Java API provides two ways to enable this communication.</div>
<div style="margin-bottom: 0in;">
</div>
<ol>
<li><div style="margin-bottom: 0in;">
The helper methods (<b>wait()</b>, <b>notify()</b>, <b>notifyAll()</b>)
<b>of the Object class</b>.</div>
</li>
<li><div style="margin-bottom: 0in;">
The <b>java.util.concurrent.locks.</b><b>Condition </b>interface.</div>
</li>
</ol>
<div style="margin-bottom: 0in;">
Using these mechanisms a thread can put itself into a state of
waiting until some other thread wakes it if there is a reason to come
back from the waiting state.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
A thread has to call the wait(), notify(), notifyAll() on an object
from a synchronized context or an <b>IllegalMonitorStateException</b>
will arise. The thread must synchronize the instance of the
object in which is calling the helper methods.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class Calculator extends Thread {
private <b>Operation op;</b>
public void run() {
<b>synchronize(op) { </b>
<b>op.wait(); </b>
<b>} </b>
}
}
</code></pre>
<br />
There is an overloaded version of wait that waits for an amount of
time, so the thread waits until it is notified or the specified time
elapsed.<br />
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
When the <b>wait()</b> method is invoked on an object, the thread
executing that code <b>gives up the the object's lock</b>, however
when <b>notify()</b> or <b>notifyAll()</b> are invoked on an object
the thread <b>doesn't give up the lock</b>, the lock is released
until the synchronized code where the notify() or notifyAll() are
used completes.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
A common example of thread interaction is the consumer-producer, in
this type program two threads interact sending messages between them
through a “monitor”. The producer thread as its name says
generates messages for the consumer, on the other hand the consumer
thread waits for the messages
</div>
<div style="margin-bottom: 0in;">
generated by the producer.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
Example:</div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class MessageBox {
private String message;
private boolean empty = true;
public synchronized String take() {
//Wait until message is available.
while(empty){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
empty=true;
notifyAll();
return message;
}
public synchronized void put(String message){
//Wait until message has been retrieved.
while(!empty) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
empty = false;
this.message = message;
notifyAll();
}
}
public class Producer extends Thread {
private MessageBox mb;
public Producer(MessageBox mb) {
this.mb = mb;
}
public void run() {
String [] messages = {"Hello", "world", "end"};
for (String msg:messages) {
mb.put(msg);
}
}
}
public class Consumer extends Thread {
private MessageBox mb;
public Consumer(MessageBox mb) {
this.mb = mb;
}
public void run() {
String message = "";
while (!message.equalsIgnoreCase("end")) {
message = mb.take();
System.out.print(message + " ");
}
}
}
..............
MessageBox mb = new MessageBox();
Consumer consumer = new Consumer(mb);
Producer producer = new Producer(mb);
consumer.start();
producer.start();
..............
</code></pre>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
In the pevious example the MessageBox class acts as a monitor, if you don't
know what a monitor is check this
<a href="http://en.wikipedia.org/wiki/Monitor_(synchronization)">http://en.wikipedia.org/wiki/Monitor_(synchronization)</a>,
this class makes the consumer to wait if there is no message to read
and notifies it when a message arrive. It is the same for the
producer, it makes it to wait if producer wants to send a message and
the last message set hasn't been read and notifies it when the
message has s been read.<br />
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
So, the MessageBox through its methods wait(), notify(), notifyAll()
makes easier the interaction between the consumer and producer
threads, it is important to notice that this methods are used with
condition loops, this way is safer to use this methods and avoid
deadlock situations.</div>
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
The <b>java.util.concurrent.locks.Condition</b> interface provides
similar functionality to the helper methods of the Object class.
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Conditions are associated with locks, the conditions allow threads to
have control of a lock and check whether a condition is true or not
and, if it's false, suspends the thread until another thread wakes
them up.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The java API says this about the Condition interface: Condition factors out the Object monitor methods (wait, notify and
notifyAll) into distinct objects to give the effect of having
multiple wait-sets per object, by combining them with the use of
arbitrary Lock implementations. Where a Lock replaces the use of
synchronized methods and statements, a Condition replaces the use of
the Object monitor methods.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
All conditions are associated to a lock and to obtain a Condition
instance for a particular Lock instance use its <b>newCondition()</b>
method.</div>
<br />
<div style="margin-bottom: 0in;">
Lock lock = new ReentrantLock();</div>
<div style="margin-bottom: 0in;">
Condition condition = lock.newCondition();</div>
</div>
<br />
<div style="margin-bottom: 0in;">
Condition interface has the <b>await()</b>, <b>signal()</b>,
<b>signalAll()</b> and its behavior is just the same as the wait(),
notify(), notifyAll() of Object class. These methods must be in a
block of code that begins with a call to the lock() method of a Lock
object and ends with an unlock() method on the same object, or an
<b>IllegalMonitorStateException</b> exception will arise.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> lock.<b>lock()</b>;//Gets the lock
try {
condition.<b>await()</b>;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.<b>unlock()</b>;//releases the lock
}
</code></pre>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
In order to implement the consumer-producer example with conditions,
we only have to change the MessageBox class, the one that acts as
monitor, remove the synchronized keywords for a Lock with a
Condition, and change the helper methods of the Object class for the
ones of the condition.</div>
<br />
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class MessageBox {
private String message;
private boolean empty = true;
private <b>Lock lock = new ReentrantLock(); </b>
private <b>Condition condition = lock.newCondition(); </b>
public String take() {
//Wait until message is available.
<b>lock.lock();</b>
while(empty){
try {
<b>condition.await();</b>
} catch (InterruptedException e) {
e.printStackTrace();
}
}
empty=true;
<b>condition.signalAll(); </b>
<b>lock.unlock(); </b>
return message;
}
public void put(String message){
//Wait until message has been retrieved.
<b>lock.lock();</b>
while(!empty) {
try {
<b>condition.await(); </b>
} catch (InterruptedException e) {
e.printStackTrace();
}
}
empty = false;
this.message = message;
<b> condition.signalAll(); </b>
<b>lock.unlock(); </b>
}
}
</code></pre>
<br />
<div style="margin-bottom: 0in;">
In the example above the await() method of the Condition acts like
the wait() of the Object class and signalAll() acts like the
notifyAll(), and the behavior should be the same.</div>
<br />
<a href="http://jlunaquiroga.blogspot.com/2013/05/java-concurrency-part-5.html">Go to part 5</a>Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com6tag:blogger.com,1999:blog-4213799477897003979.post-2356317716250759332013-05-12T14:58:00.002-07:002014-03-27T11:21:39.660-07:00Java Concurrency Part 3This is the third part of the tutorial, and this link goes to the previous post <a href="http://jlunaquiroga.blogspot.com/2013/05/java-concurrency-part-2.html">java concurrency part 2</a><br />
<br />
<br />
<div style="margin-bottom: 0in;">
A common situation in programs with multiple threads is when two
threads have access or share a single resource like a file, database
connection, an object. This scenario can provoke error situations or
data inconsistency.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
To guarantee that only one thread will execute a critical section,
prevent data inconsistency and errors, synchronizations mechanisms
should be implemented.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
Java provides two basic mechanisms:</div>
<ul>
<li><div style="margin-bottom: 0in;">
The
keyword <b>synchronized</b>.</div>
</li>
<li><div style="margin-bottom: 0in;">
The
<b>java.util.concurrent.locks.Lock</b>
interface and its implementations.</div>
</li>
</ul>
<div style="margin-bottom: 0in;">
Every object in java has a built in lock, that only comes into play
when the object has synchronized some code.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
If one thread has the lock of an object, no other thread can have the
lock until the first thread releases it.</div>
<div style="margin-bottom: 0in;">
A thread can acquire more than one lock.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
Example:</div>
<br />
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">
public class Resource {
public <b>synchronized</b> void lock() {
System.out.println(“Begining, the thread ” + Thread.currentThread().getName() + “has the lock”);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(“Ending, the thread ” + Thread.currentThread().getName() + “has the lock”);
}
}
public class Concurrent extends Thread {
Resource resource;
public Concurrent( Resource resource, String name) {
super(name);
this. resource = resource;
}
public void run(){
resource.lock();
}
}
.....
Resource resource = new Resource();
Concurrent c1 = new Concurrent(resource, “one”);
c1.start();
Concurrent c2 = new Concurrent(resource, “two”);
c2.start();
......
</code></pre>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<div style="margin-bottom: 0in;">
In the previous example two thread access concurrently a resource,
but one thread has to wait to the other to finish using the resource
since the resource is protected using the synchronized keyword, there
is no guarantee which thread will acquire the resource first.
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The messages in console should appear:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Begining, the thread one has the lock</div>
<div style="margin-bottom: 0in;">
Ending, the thread one has the lock</div>
<div style="margin-bottom: 0in;">
Begining, the thread two has the lock</div>
<div style="margin-bottom: 0in;">
Ending, the thread two has the lock</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
or</div>
</div>
<div style="margin-bottom: 0in;">
<br />
<div style="margin-bottom: 0in;">
Begining, the thread two has the lock</div>
<div style="margin-bottom: 0in;">
Ending, the thread two has the lock</div>
<div style="margin-bottom: 0in;">
Begining, the thread one has the lock</div>
<div style="margin-bottom: 0in;">
Ending, the thread one has the lock</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The messages for each thread appear consecutive and are not mix since
each thread doesn't release the lock of the Resource object until it
finishes executing the lock() method.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
If the synchronized keyword is removed from the declaration of the
lock() in the Resource class, the outcome of the program could be
any, an example of the output would be:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Begining, the thread two has the lock</div>
<div style="margin-bottom: 0in;">
Begining, the thread one has the lock</div>
<div style="margin-bottom: 0in;">
Ending, the thread one has the lock</div>
<div style="margin-bottom: 0in;">
Ending, the thread two has the lock</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The synchronized keyword can be applied to an object's instance to
protect access of a block of code instead of a method, it has the
same behavior, the thread who access the block of code tries to
acquire the lock of the object.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
Example:</div>
<br />
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class Resource {
public void lock() {
<b>synchronized</b>(this) {
System.out.println(“Begining, the thread ” + Thread.currentThread().getName() + “has the lock”);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(“Ending, the thread ” + Thread.currentThread().getName() + “has the lock”);
}
}
}
........
</code></pre>
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<br />
<div style="margin-bottom: 0in;">
The other synchronization mechanism provided by java is the <b>Lock</b>
interface and its implementations, according to the java API “Lock
implementations provide more extensive locking operations than can be
obtained using synchronized methods and statements. They allow more
flexible structuring, may have quite different properties, and may
support multiple associated Condition objects”.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Lock interface provides several methods to obtain a lock from an
object with different behaviors.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The following example is the same as the one used above with the
synchronized keyword.</div>
</div>
<div style="margin-bottom: 0in;">
<br />
<div style="margin-bottom: 0in;">
Example:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<pre style="background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class Resource {
<b>Lock lockObject = new ReentrantLock();</b>
public void lock() {
<b>lockObject.lock();//Adquires the lock</b>
System.out.println(“Begining thread ” + Thread.currentThread().getName() + “has the lock”);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(“Ending thread ” + Thread.currentThread().getName() + “has the lock”);
<b>lockObject.unlock();//Releasing the lock</b>
}
}
.......
</code></pre>
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<br />
<div style="margin-bottom: 0in;">
<a href="https://www.blogger.com/blogger.g?blogID=4213799477897003979" name="__DdeLink__2153_1957816534"></a>In the example the ReentrantLock implementation of the Lock interface
was used, but the API provides more implementations with different
behavior each.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
ReentrantLock has another constructor which accepts a boolean
parameter known as the fair parameter, and if it is false indicates
that any thread that is waiting for the lock will receive it, but if
it is true
</div>
<div style="margin-bottom: 0in;">
indicates that the thread that has been waiting for the mos time for
the lock will receive it.
</div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
Lock lock = new ReentrantLock(<b>true</b>);//fair set to true </div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
The <b>lock()</b> method tries to acquire the lock of the lock
object, if another thread has the lock of the object, the thread
waits until the thread that has the lock releases it.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
When a thread finishes using a lock should invoke <b>unlock()</b>
method to release the lock so other threads can access the lock.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The Lock interface has the <b>tryLock()</b> method, and it is similar to the lock() methd,
but this method doesn't block waiting for a lock as lock() does, it
returns a boolean value indicating if the lock was acquire or not,
returns true if the lock was free and was acquired by the current
thread, and false otherwise.</div>
<div style="margin-bottom: 0in;">
This method should be used inside an if() condition, if the lock is
obtained a block of code is executed.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
If (lockObject.tryLock()) {</div>
<div style="margin-bottom: 0in;">
.........</div>
<div style="margin-bottom: 0in;">
}</div>
<br />
<div style="margin-bottom: 0in;">
<a href="http://jlunaquiroga.blogspot.com/2013/05/java-concurrency-part-4.html">Go to part 4</a></div>
</div>
<br />
<br />
<br />Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com0tag:blogger.com,1999:blog-4213799477897003979.post-62854978516533762522013-05-05T15:31:00.001-07:002014-03-27T11:21:47.344-07:00Java Concurrency Part 2Here it is the part 2 from my original post: <a href="http://jlunaquiroga.blogspot.com/2013/04/java-concurrency-part-1.html">java-concurrency part-1</a><br />
<br />
<br />
<div style="margin-bottom: 0in;">
<b>Thread's priority </b>
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
All threads have a priority value
between 1 and 10. In most cases, the running thread will have the
same priority than the highest priority of the threads in the pool.</div>
<div style="margin-bottom: 0in;">
If some threads have the same priority,
it is the scheduler who decides which thread executes.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
By default a thread gets its priority
from the thread of execution who created it, but it can be changed
through the <b>setPriority(int)</b> method, this method can throw an
IllegalArgumentException if the value set is not between 1 and
10.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The static <b>yield</b><b>()</b> method of the Thread class indicates
to the JVM that the current thread can leave the CPU and go to the runnable state allowing other threads with the same or higher
priority to run. The JVM does not guarantee that this behavior.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
<b>Thread sleep</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The static <b>sleep(long)</b> method of the Thread class causes the
current thread to stop executing for<b> at least </b>the specified
sleep duration in milliseconds indicated by the parameter.</div>
<div style="margin-bottom: 0in;">
When sleeping time ends the JVM assigns CPU time to the sleeping
thread, it continues in the next instruction after the sleep() method
call.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
Example:</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
public class Calculator extends Thread {</div>
<ol>
<div style="margin-bottom: 0in;">
public void run() {</div>
<ol>
<div style="margin-bottom: 0in;">
System.out.println(“Thread
running:” + this.getName() + “, started at:” + <br />
Calendar.getInstance().getTimeInMillis());</div>
</ol>
</ol>
<div style="margin-bottom: 0in;">
try {
</div>
<div style="margin-bottom: 0in;">
<b>Thread.sleep(5000);</b></div>
<div style="margin-bottom: 0in;">
} catch (InterruptedException
e) {</div>
<div style="margin-bottom: 0in;">
e.printStackTrace();</div>
<div style="margin-bottom: 0in;">
}</div>
<ol>
<ol>
<div style="margin-bottom: 0in;">
System.out.println(“Thread
running:” + this.getName() + “, finished at:” +<br />
Calendar.getInstance().getTimeInMillis());</div>
</ol>
<div style="margin-bottom: 0in;">
}</div>
<div style="margin-bottom: 0in;">
}</div>
</ol>
<br />
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
The messages in the console should have a time difference of at least
of 5 seconds.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
<b>Exceptions</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The <b>InterruptedException</b> is thrown be some methods related
with the java concurrency API, to indicate that the thread has been
interrupted.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
If
you don't know what is an checked or unchecked exception are, then go to this
link
<b><a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html">http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html</a></b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Checked exceptions thrown inside the run() method of a Thread Object
should be catch and treated, because the run() method in the Runnable
interface doesn't declare any throws clause.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Unchecked exceptions thrown inside the run() method of a Thread
Object don't require to catch them and must of the time cause the
program to exit. For this type of exceptions Java provides a way to
catch and treat the unchecked exceptions thrown in a Thread object to
avoid the program ending.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<br />
<br />
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
The steps to implement this are:</div>
<div style="margin-bottom: 0in;">
</div>
<ol>
<li>Create a class that implements Thread.UncaughtExceptionHandler.</li>
<li>Set the exception handler to the Thread Object.</li>
</ol>
<br />
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example</div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
public class ExceptionHandler implements UncaughtExceptionHandler {</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
public void uncaughtException(Thread t, Throwable e) {</div>
<div style="margin-bottom: 0in;">
System.out.println("An exception has been captured");
</div>
<div style="margin-bottom: 0in;">
e.printStackTrace(System.out);</div>
<div style="margin-bottom: 0in;">
System.out.println("Thread status: " +
t.getState());</div>
<div style="margin-bottom: 0in;">
}</div>
<div style="margin-bottom: 0in;">
}</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
public class Calculator implements Thread {</div>
<div style="margin-bottom: 0in;">
public void run() {</div>
<div style="margin-bottom: 0in;">
throw new RuntimeException(“Exception thrown”);</div>
<div style="margin-bottom: 0in;">
}</div>
<div style="margin-bottom: 0in;">
}</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
..........</div>
<div style="margin-bottom: 0in;">
Calculator calculator = new Calculator();</div>
<div style="margin-bottom: 0in;">
<a href="https://www.blogger.com/blogger.g?blogID=4213799477897003979" name="__DdeLink__257_152192966611"></a> calculator.setUncaughtExceptionHandler(new ExceptionHandler());</div>
<div style="margin-bottom: 0in;">
<a href="https://www.blogger.com/blogger.g?blogID=4213799477897003979" name="__DdeLink__505_747045706"></a><a href="https://www.blogger.com/blogger.g?blogID=4213799477897003979" name="__DdeLink__257_15219296661"></a> calculator.start();</div>
<div style="margin-bottom: 0in;">
..........</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The console should print the messages from the exception handler.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
Thread class has another method for handle uncaught exceptions, it is
the static method <b>setDefaultUncaughtExceptionHandler()</b>, this
methods sets an exception handler for all Threads in the application.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
</div>
<div style="margin-bottom: 0in;">
<b>Factory of
threads</b></div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The factory pattern is a creational pattern whose mission is to
create objects. This pattern provide some
</div>
<div style="margin-bottom: 0in;">
advantages such as ease to change the way objects are created, limit
the creation of resources, and so on.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
The interface <b>java.util.concurrent.ThreadFactory</b> provides a
way to implement a Thread object factory. It only has the <b>newThread()</b>
method and it receives a Runnable object as a parameter and returns
a Thread object.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
Example
</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
public class Factory implements ThreadFactory {</div>
<div style="margin-bottom: 0in;">
private int counter = 1;</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
public Thread newThread(Runnable r) {</div>
<div style="margin-bottom: 0in;">
Thread t=new Thread(r, "Thread: " +counter);</div>
<div style="margin-bottom: 0in;">
counter++;</div>
<div style="margin-bottom: 0in;">
return t;</div>
<div style="margin-bottom: 0in;">
}</div>
<div style="margin-bottom: 0in;">
}</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
public
class Calculator implements
Runnable
{</div>
<div style="margin-bottom: 0in;">
public
void run() {</div>
<div style="margin-bottom: 0in;">
.....</div>
<div style="margin-bottom: 0in;">
}</div>
<div style="margin-bottom: 0in;">
}</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
....</div>
<div style="margin-bottom: 0in;">
<a href="https://www.blogger.com/blogger.g?blogID=4213799477897003979" name="__DdeLink__634_283375085"></a> Factory factory=new Factory();</div>
<div style="margin-bottom: 0in;">
Calculator calculator = new Calculator ();</div>
<div style="margin-bottom: 0in;">
for (int i=0; i<10; i++){</div>
<div style="margin-bottom: 0in;">
Thread thread=<b>factory.newThread(calculator);</b></div>
<div style="margin-bottom: 0in;">
thread.start();</div>
<div style="margin-bottom: 0in;">
}</div>
<div style="margin-bottom: 0in;">
.....</div>
<div style="margin-bottom: 0in;">
<br /></div>
<div style="margin-bottom: 0in;">
At the end of the for loop 10 threads have been created and started.</div>
<div style="margin-bottom: 0in;">
<br /></div>
<br />
<a href="http://jlunaquiroga.blogspot.com/2013/05/java-concurrency-part-3.html">Go to part 3</a><br />
<br />
<br />Anonymoushttp://www.blogger.com/profile/08290643904561387397noreply@blogger.com0