<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>RasterGrid Blog &#187; Java</title>
	<atom:link href="http://rastergrid.com/blog/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://rastergrid.com/blog</link>
	<description>A technical blog from Daniel Rákos (aka aqnuep)</description>
	<lastBuildDate>Fri, 24 Feb 2012 03:23:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Just released my first Android game</title>
		<link>http://rastergrid.com/blog/2011/03/just-released-my-first-android-game/</link>
		<comments>http://rastergrid.com/blog/2011/03/just-released-my-first-android-game/#comments</comments>
		<pubDate>Mon, 14 Mar 2011 10:46:31 +0000</pubDate>
		<dc:creator>Daniel Rákos</dc:creator>
				<category><![CDATA[Games]]></category>
		<category><![CDATA[AndEngine]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[Android Market]]></category>
		<category><![CDATA[Box2D]]></category>
		<category><![CDATA[button]]></category>
		<category><![CDATA[football]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[market]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[soccer]]></category>
		<category><![CDATA[store]]></category>

		<guid isPermaLink="false">http://rastergrid.com/blog/?p=564</guid>
		<description><![CDATA[I am happy to announce that I&#8217;ve just published my first mobile game on the Android Market. I have experimented with creating games earlier, especially targeting the PC platform, however I never accomplished to release such one due to lack of resources, especially in the domain of artwork. Hence I turned to mobile platforms as]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Frastergrid.com%252Fblog%252F2011%252F03%252Fjust-released-my-first-android-game%252F%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Just%20released%20my%20first%20Android%20game%22%20%7D);"></div>
<p><img class="alignleft" src="http://www.rastergrid.com/blog/wp-content/uploads/2011/03/pocket-soccer-promo-graph.png" alt="" width="180" height="120" /> I am happy to announce that I&#8217;ve just published my first mobile game on the Android Market. I have experimented with creating games earlier, especially targeting the PC platform, however I never accomplished to release such one due to lack of resources, especially in the domain of artwork. Hence I turned to mobile platforms as there even a one-man-show game can bring loads of fun time to the players. So here we are now: after loads of abandoned PC projects, here I have my first published game called &#8220;Pocket Soccer&#8221;.</p>
<p><span id="more-564"></span>The game itself is a reinterpretation of a classic board game called button football that is very popular in my home country. The key difference is that the game does not contain the many rules like the original one to provide a smoother and more fast-paced game-play. Each player has three buttons that they control by grabbing and throwing them in the desired direction. If one manages to push the soccer ball into the opposite player&#8217;s goal then he or she gets one point. The first one to reach ten points wins the match.</p>
<p>The game is turn based so each player has five seconds to move with one of his/her buttons. While, in my opinion, the game is more fun in two-player mode when two buddies can play against each other on the same device, the game also features a pretty smart AI with three difficulty levels. But that&#8217;s enough talk, maybe some screenshots say more:</p>
<div class="wp-caption aligncenter" style="width: 610px"><img src="http://www.rastergrid.com/blog/wp-content/uploads/2011/03/pocket-soccer-screenshot1.jpg" alt="" width="600" height="360" /><p class="wp-caption-text">Starting lineup in a match between Spain and Portugal.</p></div>
<p>Besides the possibility to choose between more than sixty countries to play with, the game has also other changeable assets like different soccer fields and balls. These also come with different physical properties that slightly change the game-play. While some of these assets come out-of-the-box, some others are only accessible if you unlock them. You can do so by playing and/or winning a number of matches in the various game modes. The prerequisites of each asset can be checked in the appropriate menu and you can also check your current accomplishments by tapping the statistics button in the main menu.</p>
<div class="wp-caption aligncenter" style="width: 610px"><img src="http://www.rastergrid.com/blog/wp-content/uploads/2011/03/pocket-soccer-screenshot2.jpg" alt="" width="600" height="360" /><p class="wp-caption-text">Another match between Peru and Uruguay. The player with Uruguay is about to move.</p></div>
<p>The game should work well on most Android devices. It requires only API level 4 (Android 1.6). I&#8217;ve mainly tested it on my Samsung Galaxy S, which of course runs it smoothly, but I tested it also on other devices like the Motorola Droid, ZTE Blade (San Fransisco) and Samsung Galaxy Spica. The game worked well on the Droid and especially smooth on the Blade, which surprised me a little bit for such a cheap phone. In case of the Spica, it already felt that the phone was not made for gaming, however, at the end I managed to optimize the game enough so that it provides a good user experience on that phone as well.</p>
<div class="wp-caption aligncenter" style="width: 610px"><img src="http://www.rastergrid.com/blog/wp-content/uploads/2011/03/pocket-soccer-menu.jpg" alt="" width="600" height="360" /><p class="wp-caption-text">The main menu. You can scroll left and right to access the additional menu items and you can check your statistics anytime by tapping its icon in the bottom-right corner.</p></div>
<p>I tried to make the game look like the least possible like &#8220;programmer art&#8221; and I home I managed to do so. In order to have a fast time-to-market with my first game, I&#8217;ve chosen to use a game engine framework first, rather than writing my own. Having a lack of native game engines for Android, I settled down with <a title="AndEngine" href="http://www.andengine.org/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.andengine.org/?referer=');">AndEngine</a> as it looked to have a fast learning curve and actually it has (other option was <a title="libgdx" href="http://code.google.com/p/libgdx/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/libgdx/?referer=');">libgdx</a>). While I&#8217;m not a great fan of pre-cooked solutions, AndEngine worked out pretty well with its native <a title="Box2D" href="http://www.box2d.org/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.box2d.org/?referer=');">Box2D</a> accessible over JNI, however, I also had some bad experiences. I will write another post about my development experiences with Android and AndEngine.</p>
<h2>Summary</h2>
<p>To sum it up, I managed to publish my first game and I hope you&#8217;ll like it. The game is ad supported, so you can download it for FREE from the android market:</p>
<p style="text-align: center;"><a href="http://market.android.com/details?id=com.rastergrid.game.pocketsoccer" onclick="pageTracker._trackPageview('/outgoing/market.android.com/details?id=com.rastergrid.game.pocketsoccer&amp;referer=');"><img class="aligncenter" title="http://market.android.com/details?id=com.rastergrid.game.pocketsoccer" src="http://www.rastergrid.com/blog/wp-content/uploads/2011/03/pocket-soccer-qr.png" alt="" width="258" height="258" /></a></p>
<p style="text-align: center;"><a href="http://market.android.com/details?id=com.rastergrid.game.pocketsoccer" onclick="pageTracker._trackPageview('/outgoing/market.android.com/details?id=com.rastergrid.game.pocketsoccer&amp;referer=');"><img class="aligncenter" title="http://market.android.com/details?id=com.rastergrid.game.pocketsoccer" src="http://www.rastergrid.com/blog/wp-content/uploads/2011/03/download-icon.png" alt="" width="258" height="55" /></a></p>

]]></content:encoded>
			<wfw:commentRss>http://rastergrid.com/blog/2011/03/just-released-my-first-android-game/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>Going mobile with OpenGL ES</title>
		<link>http://rastergrid.com/blog/2010/04/going-mobile-with-opengl-es/</link>
		<comments>http://rastergrid.com/blog/2010/04/going-mobile-with-opengl-es/#comments</comments>
		<pubDate>Sun, 18 Apr 2010 16:34:53 +0000</pubDate>
		<dc:creator>Daniel Rákos</dc:creator>
				<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Samples]]></category>
		<category><![CDATA[Telecommunication]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[mobile technology]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[OpenAL]]></category>
		<category><![CDATA[OpenGL]]></category>
		<category><![CDATA[OpenGL ES]]></category>
		<category><![CDATA[phone]]></category>

		<guid isPermaLink="false">http://rastergrid.com/blog/?p=230</guid>
		<description><![CDATA[Many things have changed since the first time the public put their hands on the first mobile phone device as these days the end user rarely makes their choices when buying a mobile equipment based on their telephony capabilities. In fact, nowadays these devices are one of the most popular entertainment platforms out there. The]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Frastergrid.com%252Fblog%252F2010%252F04%252Fgoing-mobile-with-opengl-es%252F%22%2C%20%22shorturl%22%3A%20%22http%3A%2F%2Fbit.ly%2Fa5rKKQ%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Going%20mobile%20with%20OpenGL%20ES%22%20%7D);"></div>
<p>Many things have changed since the first time the public put their hands on the first mobile phone device as these days the end user rarely makes their choices when buying a mobile equipment based on their telephony capabilities. In fact, nowadays these devices are one of the most popular entertainment platforms out there. The main problem for application developers is that these platforms tended to be very heterogeneous from point of view of hardware architecture as well as that of API support. Meanwhile things have changed. While the underlying hardware still varies a lot from device to device the work of application developers has been eased by having cross platform mobile operating systems and open standards. In particular OpenGL ES that is an embedded version of the popular graphics API. In this article I would like to talk about some of the big players of the mobile OS industry and about using OpenGL ES for creating impressive mobile applications.</p>
<p><span id="more-230"></span>The first version of the OpenGL ES specification has been released in order to provide a lightweight API for embedded graphics using a well-defined subset of the functionalities provided by the desktop version of OpenGL. While the specification is already out quite for a while, the wide adoption in the industry and the interest of application developers for it became strong only in the recent past. Currently, we have several mobile platforms that are bundled with 3D accelerators and provide a set of features via OpenGL ES that makes developers capable of creating games that weren&#8217;t possible even on desktop platforms about ten years ago.</p>
<h3>Going 3D on mobiles</h3>
<p>Those who know me, know that well that I was always interested in graphics, especially when using it for entertainment purposes. In particular, I was about to develop video games since the first time I&#8217;ve put my hands on a computer. This is no different now as well as now I&#8217;m writing about OpenGL ES and mobile platforms because I got interested in creating games for mobile phones.</p>
<p>As I&#8217;ve already mentioned before, the problem with developing for mobile equipments is the variety of hardware and software platforms that they are built on. As being somebody who is already familiar with desktop OpenGL, having OpenGL ES in the tool-set already eliminates some of the burden that I must face with.</p>
<p>Also when talking about application platform things have also changed a lot. Nowadays, we have just a few big players in the mobile OS industry thus easing the work of the developers. More precisely, if an application developer plans to go mobile and would like to grab the biggest market audience, can limit their efforts on the following platforms:</p>
<ul>
<li><strong>iPhone OS</strong> &#8211; This is the one that drives Apple&#8217;s iPhone mobile devices as well as the iPod Touch. It provides an application platform similar to that Mac developers got used to. It can be said that this platform is the most popular in the industry, especially when dealing with gaming applications.</li>
<li><strong>Android</strong> &#8211; This is the newest player in the field, brought by Google. While it&#8217;s a newbie in the industry it already captured the attention of tons of developers. We can say that currently Android and iPhone are dictating the direction of mobile entertainment.</li>
<li><strong>Symbian OS</strong> &#8211; Symbian has the largest share in most markets worldwide, still not that popular in the mobile gaming industry. It is the operating system running most of today&#8217;s Nokia phones.</li>
<li><strong>Windows Mobile</strong> &#8211; Microsoft&#8217;s product built on Windows CE, the company&#8217;s embedded operating system.</li>
<li><strong>RIM Blackberry OS</strong> &#8211; Operating system primarily designed for the business industry.</li>
</ul>
<p>While most of these mobile operating systems are built on the same design conceptions it is very difficult for the developer to create cross-platform applications for all these platforms as they vary on the language and tool-set support that minimizes the possibilities for code reuse. Unfortunately this is against the one of the most important rule of mobile development as to maximize portability.</p>
<p>It is not 100% true that there is no way to provide optimum portability for all these platforms, but if we choose this direction we are limited to two possibilities: cross-platform Java applications and web-based applications. While these seem to be excellent alternatives to native programming of the platforms, they severely limit the developer in creating applications that fully take advantage of the underlying hardware. This is when OpenGL ES comes into picture as all these platforms have API support thus providing at least some form of code reuse possibility when dealing with entertainment applications.</p>
<p>Now, I would like to continue with talking about the two platforms that I&#8217;m most interested in.</p>
<h3>iPhone OS</h3>
<p>I started to get involved in iPhone game development because one of my friends pushed me to after seeing the great success of his brother-in-law, <a title="zhooley's iPhone applications" href="http://www.zhooley.hu/iphone/" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.zhooley.hu/iphone/?referer=');">zhooley</a> who had some great titles. Currently I don&#8217;t have a Mac yet to develop on, but already read some stuff about iPhone development. This is where the following information come from.</p>
<p>iPhone is currently is the most important platform for mobile application developers. It became such an important factor in the industry thanks to Apple&#8217;s AppStore. Previously there was little to no way for the end users to extend their mobile software base so easily. While this is good for the end user, it is maybe even better for application developers as AppStore provides them quite a large market audience.</p>
<p>The secret why iPhone is an excellent gaming platform lies in the palette of features that the phone hardware and the software frameworks provide. Just to mention the most important ones:</p>
<ul>
<li>Touch screen control with support for multi-touch events capturing the movement of up to five fingers.</li>
<li>Three accelerometers for tracking the spacial movement and direction of the device in all axes.</li>
<li>MVC inspired GUI framework for enhanced productivity.</li>
<li>Support for several industry standard APIs like OpenGL ES, OpenAL and much more.</li>
</ul>
<p>But that&#8217;s enough from the general speaking, let&#8217;s see what&#8217;s about OpenGL ES support on the iPhones&#8230;</p>
<p>As far as I can tell, not being an iPhone owner, the graphics hardware bundled with the mobile comes in form of PowerVR accelerators: MBX and SGX.</p>
<p>The PowerVR MBX has OpenGL ES 1.1 support, that is roughly equivalent to OpenGL 1.5, running a tile-based deferred renderer that is suitable for most 3D applications. That means it has only fixed function capabilities, however that is usually enough for most mobile applications. Also note that it has very limited amount of texture memory of 24MB.</p>
<p>The PowerVR SGX is a more powerful processor that also supports OpenGL ES 2.0, roughly equivalent to OpenGL 2.0, but has optimized fixed function shaders that provide flawless backward compatibility for OpenGL ES 1.1 applications.</p>
<p>The most important thing is still that all iPhones are able to do floating point maths natively and efficiently that is an important factor when dealing with OpenGL applications as the usage of the fixed point types can be quite a burden for developers, especially for those migrating from desktop development.</p>
<p>Additionally, the OpenGL ES implementation on iPhone provides some nice extensions like <a title="GL_OES_framebuffer_object" href="http://www.khronos.org/registry/gles/extensions/OES/OES_framebuffer_object.txt" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.khronos.org/registry/gles/extensions/OES/OES_framebuffer_object.txt?referer=');">GL_OES_framebuffer_object</a>, <a title="GL_OES_compressed_paletted_texture" href="http://www.khronos.org/registry/gles/extensions/OES/OES_compressed_paletted_texture.txt" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.khronos.org/registry/gles/extensions/OES/OES_compressed_paletted_texture.txt?referer=');">GL_OES_compressed_paletted_texture</a> and <a title="GL_OES_point_sprite" href="http://www.khronos.org/registry/gles/extensions/OES/OES_point_sprite.txt" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.khronos.org/registry/gles/extensions/OES/OES_point_sprite.txt?referer=');">GL_OES_point_sprite</a>. Also, thanks to the iPhone simulator that comes with the SDK it is easy to test the application during development without an actual device. Still, one important hint to mention is that the iPhone simulator has different OpenGL ES capabilities than the actual hardwares and also the performance characteristics measured on the simulator should not be taken as valid measurements because the simulator does not really simulate the graphics hardware but only the software platform.</p>
<p>iPhone development is done using the Cocoa API and preferably Objective-C, however C, C++ and Objective-C++ can be also used for development. One just has to interface somehow the Cocoa API and the rest can be done almost in any native programming language. That is one of the key advantages of the iPhone platform that one can develop native applications and no need for Java or web-based solutions.</p>
<p>While iPhone may seem to be a perfect choice for mobile game platform, we should not forget about one big disadvantage of it, in particular that one cannot develop legal iPhone applications without owning a Mac.</p>
<h3>Android</h3>
<p>The Android platform was suggested by one of my workmates who just brought a Droid. That phone is actually a device capable to compete with the iPhone from both features and performance point of view.</p>
<p>Android is the big hit of the last year and my forecast is that it will be one of the most relevant platforms of the upcoming years. Google adopted the idea of Apple and they also created an open market for the softwares that the end user can easily download and install on their devices. This is the AndroidMarket that can easily become a powerful competitor of the AppStore.</p>
<p>While, as I said earlier, the Motorola Droid, as an example, does support about the same feature set that makes the iPhone an excellent gaming platform, this cannot be said about most of the phones running Android on them. This is maybe one of the biggest disadvantages of the Android platform. However, we can take this also as an advantage as it makes it possible for more phones to adopt this operating system.</p>
<p>As the Android operating system is running on various phones from different vendors with different hardware capabilities, there isn&#8217;t too much to talk about the graphics hardware capabilities except that some devices not just don&#8217;t have a graphics accelerator but they also lack of floating point support. This is another disadvantage as it forces developers to stick to fixed point math in their OpenGL ES applications to maximize portability or they have to maintain two different rendering paths.</p>
<p>Originally, Android supported only OpenGL ES 1.0 that is roughly equivalent to OpenGL 1.3. However, since NDK r3 there is also OpenGL ES 2.0 support for Android as well. The feature set here varies much more from both hardware point of view and extension support.</p>
<p>Development for Android is done in Java using a proprietary SDK for accessing the Android API. The SDK comes with a simulator that works fine, except the long initial boot time that I was really surprised about when first trying it out.</p>
<p>One advantage of the SDK that it can be used in virtually any operating system so application developers can work on either Windows, Linux, MacOSX or other platform. There is also a nice Eclipse plugin that makes application development for Android even easier. That&#8217;s why I started with this one.</p>
<p>Just to illustrate how easy to put together some working demo with a good SDK, I&#8217;ve created a simple box rotating app to demonstrate OpenGL ES usage on Android. From installation till having a working application it took no more than two hours. You can find the download links for both the source code and the binary release at the end of the article.</p>
<h3>Why mobile games?</h3>
<p>I am a person who was, is and will be interested in developing computer games. Previously, I was working with desktop platforms and at the time when I was 10 years old it was satisfactory to put together some simple 2D game but not now.</p>
<p>I had always planned to create a state-of-the-art game engine and use it for some game, like most people like me do, but the efforts of one is simply unsatisfactory to compete with the players in the industry out there. Even if I feel the capability to be able to write such an engine but it would take that much time that I simply don&#8217;t have since I am working. Even if I would manage to accomplish it in a year or two then the problem with content creation comes into picture. For an AAA PC game content creation takes several times more than the actual programming and here I even lack the knowledge to achieve it. On the other hand mobile game creation is a much shorter process when you can get to actual results in a matter of weeks that is far better compared to PC game creation.</p>
<p>Also, I would never use third party game engines, except some basic libraries like OpenGL, a physics library and things like that because otherwise I wouldn&#8217;t feel the results being my own creation.</p>
<p>Having game development as a hobby works well during high school and university but it gets quite difficult after you are out there in the world having a job and responsibilities. Maybe I should have been already taking my time before to develop something concrete for PC but, as most fellow hobbyist know, you usually end up having hundreds of unfinished projects.</p>
<p>While I would never forget about desktop platforms and I will actively keep myself up with the evolution of the industry, mobile application development opened another world for me where I can unfold myself.</p>
<h3>HelloAndroid Demo</h3>
<p>Source code: <a href="http://rastergrid.com/blog/wp-content/uploads/2010/04/files/helloandroid_src.zip">helloandroid_src.zip</a><br />
Binary release: <a href="http://rastergrid.com/blog/wp-content/uploads/2010/04/files/HelloAndroid.apk">HelloAndroid.apk</a></p>

]]></content:encoded>
			<wfw:commentRss>http://rastergrid.com/blog/2010/04/going-mobile-with-opengl-es/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Synchronizable objects for C++</title>
		<link>http://rastergrid.com/blog/2010/02/synchronizable-objects-for-c/</link>
		<comments>http://rastergrid.com/blog/2010/02/synchronizable-objects-for-c/#comments</comments>
		<pubDate>Tue, 02 Feb 2010 19:01:56 +0000</pubDate>
		<dc:creator>Daniel Rákos</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Multiprocessing]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Samples]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[lock]]></category>
		<category><![CDATA[macro]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[mutex]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[OpenMP]]></category>
		<category><![CDATA[synchronization]]></category>

		<guid isPermaLink="false">http://rastergrid.com/blog/?p=120</guid>
		<description><![CDATA[Previously I talked about how one can easily take advantage of multiprocessing using OpenMP. Even if the C pragmas introduced by the parallel programming API standard is very straightforward for simple programs, it simply doesn&#8217;t fit nicely in a complex C++ application that is built from the ground with the OOP in mind. To smoothly]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Frastergrid.com%252Fblog%252F2010%252F02%252Fsynchronizable-objects-for-c%252F%22%2C%20%22shorturl%22%3A%20%22http%3A%2F%2Fbit.ly%2FbbpIPT%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Synchronizable%20objects%20for%20C%2B%2B%22%20%7D);"></div>
<p>Previously I talked about how one can easily take advantage of multiprocessing using OpenMP. Even if the C pragmas introduced by the parallel programming API standard is very straightforward for simple programs, it simply doesn&#8217;t fit nicely in a complex C++ application that is built from the ground with the OOP in mind. To smoothly introduce OpenMP into such projects one need higher level constructs that hide the actual implementation details. This is the first article of a series that will try to provide reference implementations of such an abstraction. First, we will start with synchronizable primitives that try to reflect the functionality provided by the &#8220;synchronized&#8221; statement of Java.</p>
<p><span id="more-120"></span>This article is highly inspired by an article written by <a title="A &quot;synchronized&quot; statement for C++ like in Java" href="http://www.codeproject.com/KB/threads/cppsyncstm.aspx" target="_blank" onclick="pageTracker._trackPageview('/outgoing/www.codeproject.com/KB/threads/cppsyncstm.aspx?referer=');">Achilleas Margaritis</a><span style="line-height: normal; -webkit-border-horizontal-spacing: 5px; -webkit-border-vertical-spacing: 5px; font-size: small;"> and is mostly equivalent with his thoughts. My article tries to provide a portable reference implementation of a slightly modified version of the trick presented by Margaritis that uses OpenMP as the multiprocessing API back-end.</span></p>
<h2>Motivation</h2>
<p><span style="line-height: normal; -webkit-border-horizontal-spacing: 5px; -webkit-border-vertical-spacing: 5px; font-size: small;">According to the OO paradigm, classes and consequently objects provide an abstract interface to the underlying internal data or services of the modeled entity or entity class. When it comes to parallel programing we should provide facilities to enable concurrent access to shared resources that are in this case objects. Using plain OpenMP can be satisfactory, however when used extensively the OpenMP pragmas and API function calls introduced can greatly affect the readability and the maintainability of the code. Nevertheless, there can be platforms that use other APIs for handling race conditions. It is obvious that we need to encapsulate these facilities and provide an abstract tool-set instead.</span></p>
<h2>Implementation</h2>
<p><span style="line-height: normal; -webkit-border-horizontal-spacing: 5px; -webkit-border-vertical-spacing: 5px; font-size: small;">The very first building block of such a framework can be a mutex class that provides mutually exclusive access to certain resources. In the world of OpenMP this should look like something similar to the following:</span></p>
<pre class="brush: cpp">class Mutex {
public:
    Mutex() { omp_init_lock(&amp;_mutex); }
    ~Mutex() { omp_destroy_lock(&amp;_mutex); }
    void lock() { omp_set_lock(&amp;_mutex); }
    void unlock() { omp_unset_lock(&amp;_mutex); }
private:
    omp_lock_t _mutex;
};</pre>
<p>This seems already enough for us to make our Java-like &#8220;synchronized&#8221; statement, however we would like to create a framework that makes usage as easy and safe as possible. In order to get closer to this goal we apply the RAII (Resource Acquisition Is Initialization) design pattern to create our lock class:</p>
<pre class="brush: cpp">class Lock {
public:
    Lock(Mutex&amp; mutex) : _mutex(mutex), _release(false) { _mutex.lock(); }
    ~Lock() { _mutex.unlock(); }
    bool operator() const { return !_release; }
    void release() { _release = true; }
private:
    Mutex&amp; _mutex;
    bool _release;
};</pre>
<p>Our goal is to provide an inheritable interface for such objects that needs synchronization. However, this step has to involve severe considerations regarding to the provided interface as we explicitly need to conform to the following requirements:</p>
<ul>
<li>The interface shall not expose the interface of the underlying synchronization primitive, in our case the mutex class methods.</li>
<li>The interface shall be available only to the synchronizable objects but not for the external world as we would like to not just hide the implementation details of our abstract entity but also prevent the users to synchronize our objects as it should be the responsibility of the object itself.</li>
<li>The interface shall expose methods which are less prone to name collision, for convenience.</li>
</ul>
<p>If we take care of the presented conventions we end up with an interface similar to the following:</p>
<pre class="brush: cpp">class Synchronizable: protected Mutex {
protected:
	void enterSyncBlock() { this-&gt;lock(); }
	void exitSyncBlock() { this-&gt;unlock(); }
};</pre>
<p>Now we are almost at the finish line. We just need to inherit this class in order to have the needed facilities for an object that needs synchronization. However, using this interface directly is not the most comfortable and safe. If we would like to have a Java-like &#8220;synchronized&#8221; statement we have to call for additional help. Fortunately, we have our not so well respected C macro language coming to rescue us as we can use it to make some pseudo-language extensions. The simplest way to define our new statement is using the following line:</p>
<pre class="brush: cpp">#define synchronized(obj)  for(Lock obj##_lock = *obj; obj##_lock; obj##_lock.release())</pre>
<p>From now, we can really use object synchronization in C++ as easy as in Java, we just need the following syntax in the method of our shared objects:</p>
<pre class="brush: cpp">synchronized(this) {
    // some code that needs synchronization
}</pre>
<p>Now it is clearly visible how handy the RAII pattern became in our case. Beside that it is now very straightforward to use this statement it provides additional benefits:</p>
<ul>
<li>It makes the code more readable and as a result it is easier to maintain.</li>
<li>No need to call inconveniently named methods and use lock variables.</li>
<li>The synchronized code has it&#8217;s own scope inside the code.</li>
<li>It is exception-safe as the mutex is unlocked upon destruction.</li>
</ul>
<p>Additionally, we can also take advantage of the inherent problem in C++ regarding to multiple inheritance. If we inherit our object from other two synchronized objects then using a simple type casting we can explicitly specify which ancestor we would like to synchronize in a particular block. Also, to ease this we can define our synchronization statement instead of the Java-like one using the following line:</p>
<pre class="brush: cpp">#define synchronized(cls)  for(Lock obj##_lock = *static_cast&lt;cls*&gt;(this); obj##_lock; obj##_lock.release())</pre>
<p>In this case we pass the class name instead of the object pointer <em>this</em>. Using this later construct we can easily specify the correct ancestor that we would like to synchronize in case when we deal with multiple inheritance situations. Personally I prefer the later syntax as it is much more customized for C++ use cases.</p>
<p>As from now we don&#8217;t need a direct interface for entering and exiting our synchronization block we can simplify our synchronizable interface to the following chunk:</p>
<pre class="brush: cpp">class Synchronizable: protected Mutex {
};</pre>
<p>This is enough from now to provide the facilities needed for a synchronization block but still complies to the requirement that we would like to hide the synchronization primitive related details.</p>
<p>Beside this, Jörg came up with the idea today to replace the for loop in our macro with a single if statement. This seems reasonable as we don&#8217;t have to sacrifice any scoping and safety related benefits of our framework. This simplifies our lock class to the following:</p>
<pre class="brush: cpp">class Lock {
public:
    Lock(Mutex&amp; mutex) : _mutex(mutex) { _mutex.lock(); }
    ~Lock() { _mutex.unlock(); }
    bool operator() const { return true; }
private:
    Mutex&amp; _mutex;
};</pre>
<p>This definition of the lock class is satisfactory if we redefine our synchronized macro to use an if statement instead:</p>
<pre class="brush: cpp">/* Java-like synchronized statement */
#define synchronized(obj)  if (Lock obj##_lock = *obj)
/* alternative synchronized statement to support multiple inheritance */
#define synchronized(cls)  if (Lock obj##_lock = *static_cast&lt;cls*&gt;(this))</pre>
<p>Thanks to the useful comments we even managed to further optimize and minimize the support code needed for our new pseudo-language extension.</p>
<h2>Conclusion</h2>
<p>We have seen an example how one can implement an easy to use synchronizable interface for C++. Also, we&#8217;ve provided a concrete implementation that is based on OpenMP. This library is still far from an API that provides all the necessary constructs that one needs for using parallel programming in their C++ projects, however we made our first step and I will recap on the subject in subsequent articles to further extend this framework.</p>
<p>Credits go to Achilleas Margaritis whose article inspired me to write mine and to Jörg for the useful improvement ideas.</p>
<h3>Full source code</h3>
<p><strong>Language:</strong> C++<br />
<strong> Platform:</strong> cross-platform<br />
<strong> Dependency:</strong> OpenMP<br />
<strong> Download link:</strong> <a title="omp_sync.h" href="/blog/wp-content/uploads/2010/02/files/omp_sync.h" target="_blank">omp_sync.h</a><br />
<strong> Comments:</strong> In order to use it as it is, you will need a C++ compiler supporting OpenMP like GCC 4.2 or Visual C++ 2008.</p>

]]></content:encoded>
			<wfw:commentRss>http://rastergrid.com/blog/2010/02/synchronizable-objects-for-c/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Manage code yourself</title>
		<link>http://rastergrid.com/blog/2010/01/manage-code-yourself/</link>
		<comments>http://rastergrid.com/blog/2010/01/manage-code-yourself/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 16:41:25 +0000</pubDate>
		<dc:creator>Daniel Rákos</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[byte code]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://rastergrid.com/blog/?p=10</guid>
		<description><![CDATA[Those who know me know it well that I am not a big fan of languages which produce managed code. In this article I would like to cover the reasons behind my skepticism. Also I would like to dispel the myths around such languages and try to prove them with facts (we will see how]]></description>
			<content:encoded><![CDATA[
<div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em; background: url(data:,%7B%20%22url%22%3A%20%22http%253A%252F%252Frastergrid.com%252Fblog%252F2010%252F01%252Fmanage-code-yourself%252F%22%2C%20%22shorturl%22%3A%20%22http%3A%2F%2Fbit.ly%2F4FH6No%22%2C%20%22style%22%3A%20%22big%22%2C%20%22title%22%3A%20%22Manage%20code%20yourself%22%20%7D);"></div>
<p>Those who know me know it well that I am not a big fan of languages which produce managed code. In this article I would like to cover the reasons behind my skepticism. Also I would like to dispel the myths around such languages and try to prove them with facts (we will see how well I manage to achieve this). If you disagree with me, you&#8217;ll most probably hate me because of making this post but please, respect my personal point of view.</p>
<p><span id="more-10"></span>As I&#8217;ll mostly talk in this post in general about managed code I would like to emphasize that I have worthwhile experience only with Java and have barely used C# and other managed languages so my primary arguments maybe apply directly only to Java but still would like to present my arguments in general as they still apply in some way to all such languages.</p>
<p>Without the intension to insult anybody, I would like to start with a citation from one of my friends, who often says that &#8220;Java is just a pseudo-language&#8221;. Mostly I agree with him and it&#8217;s not just because I have my not so delightful experiences with the language but also because it introduced a brand new way of coding style that is a complete nightmare for an old-school coder like me. As I don&#8217;t want to start another religious war, I&#8217;ll stop my preposterous arguments here as I would like to prove my concerns with facts that nobody can disclaim.</p>
<blockquote><p>&#8220;&#8230; nowadays Java is almost as fast as native code&#8230;&#8221;</p></blockquote>
<p>This used to be a common myth in the last few years. For those who are still arguing by shouting this loud on forums and blogs, I would like to draw their attention to the fact that Java is <strong>still</strong> an interpreted language no matter if the latest JVM versions do some on-the-fly compilation of the code and as such it is inherently slower than any language that generates native code.</p>
<p>As my hobby is computer graphics I have to talk a bit about the case of PC games. Have anybody seen a game fully written in Java or any other interpreter based language that produces state-of-the-art graphics which competes with the best professional games and it also provides the same performance? I think not, and this is not a coincidence.</p>
<p>GPUs are getting more horsepower in a much faster pace than CPUs. That is what resulted in the batch crisis lately. It&#8217;s already happening for several years that the CPU is simply not powerful enough to feed the GPU with enough data in complex real-time rendering situations. There have been already tons of different software and hardware technologies which already targeted this issue a long time ago but as a perfect example that <strong>is</strong> the reason which resulted in the appearance of the completely redesigned DirectX 10 API and which emerged the need for a cleaner architecture for OpenGL as well. That&#8217;s why there are no advanced games written in interpreted languages as they waste those very valuable CPU cycles which would have great benefits otherwise.</p>
<blockquote><p>&#8220;&#8230; Java has a much greater expression power&#8230;&#8221;</p></blockquote>
<p>I tend to agree with this one. As these languages are interpreted by a virtual machine they provide great room for such features that would be impossible or simply very inefficient in a native language. That&#8217;s why one of my favorite programming language is PHP as an example. It is even more flexible then Java, for example, but never forget that PHP never meant to try to replace native languages as instead it is used in a totally different domain.</p>
<p>There are many language features that are not available in native languages but they weren&#8217;t left out unintentionally. Their lack is primarily justified by the fact that most of these features are rather inefficient and they simply not fit in the philosophy of a performance oriented language like C++. However, the most important ones like reflection, delegates and most OOP related facilities are present for example in Delphi, which is one if not the best OOP language that doesn&#8217;t make too much trade of between flexibility and run-time performance. Also, even if most of these features are not present in C++, Objective-C and other popular native languages, they can be made available with a little programming knowledge in the particular language (maybe not just little).</p>
<blockquote><p>&#8220;&#8230; you don&#8217;t have to care about resource deallocation as there is the garbage collector&#8230;&#8221;</p></blockquote>
<p>This is one of the most annoying &#8220;features&#8221; of managed code based languages. I understand that the prevention of memory leaks can have a great impact on development effort, however the unpredictable behavior of garbage collectors is simply unacceptable in certain situations. The issue of lost references has been already addressed in almost all native languages with the use of reference counted objects so I simply don&#8217;t get it why is this still an important feature. For efficient resource management you need much finer control over the time and way how resources are released.</p>
<blockquote><p>&#8220;&#8230; you just have to care about the basics and Java will make you the rest&#8230;&#8221;</p></blockquote>
<p>While I strongly support the idea of COTS, the way how Java and friends interprets this concept is simply unacceptable for me. Sometimes you need to know what is going on under-the-hood. This is basically the same issue like that of the garbage collector. Beside that, according to my personal taste, I don&#8217;t like if the compiler tells me how to do a particular thing. I rather do it in my way and even if I tend to agree that the compile time static analysis what the Java compiler does can be very valuable in some situations, simply denying code generation even in the case of a very minor semantic problem is simply makes me angry.</p>
<blockquote><p>&#8220;&#8230; Java eliminated almost all unsafe features inherited from C++&#8230;&#8221;</p></blockquote>
<p>This is one of the things that hurts me most. While Java really managed to achieve this, it sacrificed flexibility, ease of use and the fun of programming to make this possible. One such removed feature is operator overloading. I love them! As an example a linear algebraic library, which is often used in graphics programming, or the string library is not just makes the coding more natural, it eases the reading of code which is written with these in mind and that greatly effects the maintenance cost of a particular software as the code is read ten times more than modified. Java in this domain seems too verbose for me and it is much harder to read the long method invocation chains, that is not just used to be used by the developers, but is the recommended way how to code in Java.</p>
<p>This post already ran wildly long so I will close the topic for now. As a conclusion, I have to point it out that this article presented the subject from a rather subjective perspective at the end. Sorry for that, I will recap on the topic in a later post where I will try to be more detached and I&#8217;ll present actual use case examples but for now, this is all that came from my heart so please, don&#8217;t be very harsh with me if I was very biased. I hope you enjoyed the article anyway.</p>

]]></content:encoded>
			<wfw:commentRss>http://rastergrid.com/blog/2010/01/manage-code-yourself/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

