Archive for the ‘Technology’ Category

Spring vs Dagger

Spring contains configurable factory classes called contexts. These contexts can read description (specified in XML, for example) about
creating objects and satisfying dependecies. Finally, your app can obtain instances of objects from context and start using

Dagger requires you to describe if class requires depdendency to be injected via @Inject annotation (right, that’s intruzive).
If dependency is concrete class, then it may be created in default way, and no more work required for it. Otherwise, if you
have to inject an instance of interface, or you need to create injected class in some specific way, then you use special
factory class and annotate it with @Module annotation and annotate each factory method with @Provides annotation. Finally, you
can generate a factory class for any classes which need injected dependency. This class will have factory methods identified
by return types, and they need all necessary @Modules to be supplied.


Spring Dagger
Classes which don’t have dependencies, but on which other classes depend Describe them in XML, init them via values If they require some specific way to create them, then you need a @Provides factory method in some @Module class. Otherwize they will be created automatically
Classes which have dependencies, and on which other classes depend Describe them in XML, inject them with references to other beans If they require some specific way to create them, then you need a @Provides factory method in some @Module class. Otherwize they will be created automatically. In both cases their dependencies will be satisfied
Classes which have dependencies, but which are not needed to be injected See previous These classes will be needed externally, so you need to generate factory methods for them
A way to make it work Load description, call refresh(), obtain objects which you need. All beans will be created and injected in each other in a way which you describe Invoke generated factory methods for objects which you need and supply specific @Module factories to customize the result

Essentials of Java web stack

March 15, 2017 Leave a comment

Jetty 8

1. start.jar is a launcher. Use –help command-line key to list available command-line options.
2. Launcher can start server in the same process (by default), or, if –exec command-line arg is present, as a separate process (if, for example, you need different JVM settings)
3. Launcher is controlled via command-line keys, and by start.ini file from current dir. There is a special command-line key –ini allowing to either specify a different ini file, or to specify a configuration content which is expected from such file
4. Server is customizable. You can specify which modules will be loaded. These are called OPTIONS, and are read from OPTIONS section of start.ini (or specified in –ini command line arg). Example:

java -jar start.jar --ini OPTIONS=Server,websocket etc\jetty.xml

5. To get a list of available modules use –list-options command-line key. It will show which jar files are used by each module.
6. Information produced by –list-options is calculated based on start.config script file which is packed inside start.jar. You can take a look by using –list-config command line key to understand module dependencies. You can override this config file by using –config command line key to completelly change server’s behaviour, but this is rarely needed.
7. There are some modules which just aggregate several other modules. Very good aggregate module is Server, which includes HTTP server, servlet container and deployer
8. Modules may be explicitly configured by XML config scripts which are usually stored in etc/ dir. Application of such configs specified in start.ini
9. To configure Jetty logging, customize existing configuration script etc/jetty-logging.xml, and don’t forget to add it to start.ini
10. Web applications are deployed to webapps dir
11. If you’ve included “resources” module, then directory resources/ is added to classpath (by default start.config script). You can put config files for your application there
12. One of usages of resouces/ dir is for applications which use log4j. If you put file in resources/ dir, then log4j will discover that file and will configure itself based on that file

Jetty 9

1. start.jar is a launcher. Use –help command-line key to list available command-line options
2. Launcher can start server in the same process (by default), or, if –exec command-line arg is present, as a separate process (if, for example, you need different JVM settings)
2. Launcher is controlled via command-line keys, and by start.ini file from current dir. File start.ini is just a set of same keys as for command-line
3. Server is customizable. You can specify which modules will be loaded via –module key. Example:

java -jar start.jar --module=http,deploy

4. To get a list of available modules use –list-modules command-line key. It will show which jar files are used by each module, and will show module dependencies.
5. Information provided by –list-modules is calculated based on module descriptors stored in modules/ directory as .mod files.
6. Each module has a corresponding config in etc/ directory. To check which config corresponds to which module you can use output of –list-modules (property XML) or by looking into .mod file. Configs are implicitly executed if corresponding module is included.
7. Minimal set of modules for working servlet container with auto-deployment support is server,http,deploy.
8. Web applications are deployed to webapps dir (will work in deploy module is enabled)
9. Recommended way to start Jetty 9 is to create a separate base directory for each running instance, which will contain configs, webapps and logs for this instance. This is called jetty.base
10. When running Jetty 9 this instance base dir should be current dir, and path to start.jar should be fully specified:

java -jar path/to/jetty/installation/start.jar

11. You can manually place start.ini into instance base dir, and create sub-dirs log, webapps. But there is a better way: from empty instance base dir run start.jar via full path and use command-line key –add-to-start. Example:

java -jar path/to/jetty/installation/start.jar --add-to-start=http,server,deploy

This will create config files from templates, and all necessary dirs.
12. If you’ve included “resources” module, then directory resources/ is added to classpath. You can put config files for your application there

Difference between Jetty 9 and Jetty 8

1. In Jetty 9, a start.ini file is just a set of command-line keys, so you can live without it. In Jetty 8 value of OPTIONS could be specified only in ini file, so you could live without it if you have specified –ini command-line key had to override this
2. Instead of defining OPTIONS in single config script, each module has it’s own descriptor.

Servlets basics

1. Web applications are packed into .war files (similar to .jar files). Applications contain static files and dynamic logic.
2. Jetty deployer maps content of web app to URL path corresponding to name of .war file. For example, application example.war to URL http://host:80/example/ . It’s called servet URL context path.
2. All dynamic logic should be placed in WEB-INF/ dir inside a .war file. In this dir there should be a classes/ sub-dir for .class files, lib/ sub-dir for .jar files, and web.xml descriptor of web app
3. Descriptor file web.xml describes servlets (they have name and main class) and mappings from url patterns to servlets.
4. Mappings from URL patterns to servlets is done relative from web application URL context path. For example, if in web.xml servlet mainServlet is mapped to URL pattern /main for web application superapp.war,
then such servlet will handle HTTP requests for URL http://host:80/superapp/main
5. Jetty comes with several built-in servlets: DefaultServlet which serves static files, and JSP servlet which handles .jsp files. You can use them in your application.
6. By default, these servlets are already used in your application. This happens because for module “deploy” it’s config script “etc/jetty-deploy.xml” defines property “jetty.deploy.defaultsDescriptorPath” with value “etc/webdefault.xml”.
This webdefault.xml is pre-pended to your web.xml. To switch it off, override property in your config files, for example in start.ini
7. in etc/webdefault.xml servlet DefaultServlet is mapped to “/”
7. Use Maven with war packaging, maven-war-plugin at build stage, maven profiles to specify which content should be included in .war file

Spring MVC

1. Spring comes with servlet called org.springframework.web.servlet.DispatcherServlet. You can have different servlets of this class under several names
2. This servlet will create Spring application content based on XML file. It will search for Spring context descriptor XML file, depending on servlet name, with pattern -context.xml
3. Like with any Spring XML context, you can either specify beans, including controller beans, directly via tags, or via  and
3. To enable MVC annotations like @Controller etc use
4. If you have mapped DispatcherServlet to “/”, but still want static files to be served, use in your context XML following tag: . It will make static requests to be forwarded
from DispatcherServlet to container’s DefaultServlet (if it is included in your web.xml either explicitly or implicitly by Jetty, see above)
5. If your Spring context supports several profiles, then you can specify which Spring profiles are active using web.xml to set context param “”
6. Log examples to see how your RequestHandlerMappings work:

INFO RequestMappingHandlerMapping:534 - Mapped "{[/rest/query],methods=[GET]}" onto public org.springframework.http.ResponseEntity<java.lang.String>
INFO RequestMappingHandlerMapping:534 - Mapped "{[/proxy/**]}" onto public org.springframework.http.ResponseEntity<java.lang.String> com.GenericPurposeProxyController.processRequest(jav

For default servlet handler:

INFO SimpleUrlHandlerMapping:341 - Mapped URL path [/**] onto handler 'org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0'


Categories: Java, Web Tags: , ,

Building OpenJDK 8 for Windows using MSYS

August 3, 2015 Leave a comment

This article will describe how to build OpenJDK 8 on Windows using MSYS. Since the building itself is performed by build scripts, we will focus on two things: installation of necessary libraries and compilers, and fixing build scripts, since they don’t work out of the box. As most of my articles, this one is written for my future self, because I’m sure I’ll get back to this task in future, and I don’t like solving problems I know I’ve solved before and I don’t remember how. Also this article is not a simple list of steps, I’ve tried to explain the reasons behind the actions. Readme file of OpenJDK says that “building the source code for the OpenJDK requires a certain degree of technical expertise”, so let’s make ourselves this expertise by learning while doing.

Getting the source.

The first step is to get the source. OpenJDK developers use Mercurial version control system as a code storage. You can open this URL: in browser to see a list of projects hosted by OpenJDK. The project you need is jdk8. If you click on jdk8, you’ll see a list of repositories which jdk8 consists of. The top one is called jdk8, which makes a full URL: You may wonder why there are two jdk8 directories in the URL? This remained from some old times when there were so called “gate” repositories to which changes were pushed for integration, and once those changes were verified, they were merged into read-only main repositories. So, jdk8/jdk8 is a read-only repository. Gate repositories approach was abandoned, but for OpenJDK 8 the path to read-only repository remains the same. If you are curious, you can read more about OpenJDK Mercurial repositories here.

So, let’s get ourselves this respository. You will need Mercurial tools for this. I like GUI tools, so I’ve downloaded SmartGit/Hg. It took me a while to figure out why there are no Mercurial option when you try to clone a remote repository. To make this work, you need to download and install official Mercurial command-line tools, and then go to settings of SmartGit and point it to hg.exe tool. This will make Mercurial to appear in a list of VCSes. Thus, GUI tools are not a full replacement for command-line tools, they just make life a little easier. If you don’t like GUIs, you can skip them and use command-line Mercurial tools, that’s quite easy. So go ahead and clone a repository to some local directory.

Structure of OpenJDK build

The top repository jdk8/jdk8 contains only build infrastructure, it doesn’t contain any real source code, which is sorted into several additional other repositories. So, from this point we can either download those repositories, or we can do that later, when we will prepare everything. Let’s take a second approach, and start with preparing for a build. Take a look at a repository we just cloned. There are two readme files: a short text file and a bigger HTML file. Both are worth reading. Also there are two directories: common and make, and three scripts. The script named will download all remaining sources using Mercurial command-line tools, and we will postpone this until later. Two remaining scripts are the core of build process.

C is not a Java, there are many aspects of the language which are not defined and compiler-specific, like, for example, size of int value. So C programmers achieve portability by having special cases for compiler-dependent things. This is usually done “on source level”: a compiler-specific information is moved to dedicated header file. So to port a C program to another compiler requires changing compiler-dependent info and recompilation. To simplify this task programs used scripts which probe the compiler they are running on and generate a compiler-dependent header files. By convention these scripts are called configure. And OpenJDK has this script. We need to run it at least once. After that we have to use make tool to build everything, becase we have a script for it, called Makefile. Such two-stage comfigure/make approach is standard in Unix world for open-source software.

Let’s take a look at configure file. It is a unix shell script which prepares a build. It is very small, all it does is executing another configure script, located in common/autoconf. This second configure does a little more, like parsing command-line parameters, of which you can read more in readme.html. The main job is done by big script called So, in order to run these scripts we need some Unix-like environment on Windows. There are two options: Cygwin and MSYS. Both environments are quite similar: each provides a shared library (dll) which implements some set of POSIX functions on Windows, and a set of Unix tools compiled as Windows executables, which rely on that dll. Cygwin is bigger, provides a larger set of POSIX calls and includes more Unix tools, so it’s like a complete unix-like environment. MSYS (which means “minimal system”) supports a smaller set of POSIX calls and provides a set of Unix tools just enough to be able to run typical configure scripts. I like everything minimal, so I prefer MSYS.

Installing MSYS and dealing with configure.

MSYS itself is not an independent project, it is a part of another project called MinGW (Minimalist Gnu for Windows), which is a quite interesting story worth telling. Most of the application programs written in C use standard library, and there are many reasons for that. On Unix systems it’s a convenient and portable way to do system calls. Standard library also includes lots of useful functions, like string manipulation. Since standard library relies on OS services, the OS kernel itself cannot use standard library. Windows provides it’s own set of services for applications, called Win32 API, but their compiler suite provides a standard library for compatibility and convenience. Some standard libraries are tied to specific compilers, but there are independent libraries: newlib, uClibc, dietlibc, mucl. When choosing a standard library one has to consider its features, performance, size, support of particular OS/CPU, and also the licence. For example, using library released with GPL requires you to release your program under GPL. The licence terms may be different depending on how you link against a library. There are two options: static linking (library will be included into executable) and dynamic linking. Licensing terms for dynamic linking are usually less restrictive then for static linking. However, if you choose dynamic linking you should somehow ensure that library is installed on computers where your program will run. So, knowing all this we can now get to MingGW. It is a version of GCC compiler which produces Windows executables dynamically linked with standard library supplied with Microsoft Visual C v 6.0 (msvcrt.dll). The license allows any code to dynamically link against it, and practically this library is present in all Windows systems (used by Microsoft’s own applications), so you don’t need to distribute it yourself. Thus MinGW produces executables which can be released under any license and distributed in a very simple way. Technically MinGW consists of a set of header files for standard library, an import library for mscvrt.dll and a version of GCC which produces Windows executables linked with import library. Later some additional libraries were ported to MinGW and now are provided as a part of it. Also MinGW was extended with include files and import libraries for Windows API, so now you can use it to write native Windows software. MinGW made it easier to port software written in C from Unix to Windows, but that was not enough. Thus MSYS was born, it is an environment for running configure scripts.

OK, back to building OpenJDK. Go to MinGW site and download installer. Run it. It will show a list of packages you can install. You don’t actually need MinGW compilers, since they are not used by OpenJDK built, but I advice you to install them. You’ll definitely need make and autoconf. Also you’ll need basic MSYS, and several specific MSYS packages: bsd cpio, mktemp, zip, unzip.

Now, as you have installed MSYS, you can start it’s shell (bash). You can use your windows paths in a special way, for example “C:\projects\openjdk” should be used as “/c/projects/openjdk”. You can try to run configure script right away. At the beginning this script will check availability of required tools, so if you forgot to install abovementioned cpio, mktemp, zip and unzip, then configure will complain (that’s how I learned that I need them). So here we will encounter a first problem with OpenJDK build environment which requires manual intervention. The script will fail finding cpio.

Learning autoconf

The script will fail finding cpio, since it is called bsdcpio. If you’ll try to track the problem (either by looking at source code or by reading log file) you’ll get to a script To fix our problem, we need to modify this script. However, editing it directly is a wrong way. This script is generated (hence the name) by a tool called autoconf from sources located in OpenJDK folder common/autoconf. So, let’s get there and edit the sources. The actual change should be made in file basics.m4. Replace cpio with bsdcpio.

To generate new you should execute But attempt to do it will fail, will complain that it can’t find autoconf. The reason is simple: autoconf was installed into MinGW location which is not available for MSYS by default. So, you should go to MSYS installation directory and find “etc” directory (on my machine it is located at c:\tools\mingw\msys\1.0\etc). Here you should create a file called fstab which will configure mounting of windows directories to msys filesystem. Take a look at fstab.sample to see how to do it, you may even copy it as fstab and edit it. Your task is to map root MinGW folder as /mingw. To apply changes in fstab you should restart MSYS bash. There is another file in etc called profile, which configures bash. By default this profile will add /mingw/bin into search path. So, if you did everything right, the result of “which autoconf” should be something like “/mingw/bin/autoconf”. Now you can get back and use to generate build script. Do it. Oops, another error.

This time autogen will complain that autoconf 2.69 or higher is required. However, MinGW includes version 2.68. When I encountered this error I’ve decided to try with 2.68, and believe me, it works perfectly fine. So, let’s hack OpenJDK build scripts and fix the required version. It is specified in file Again execute This time it should work. Ignore output about no custom hook found.

We just fixed our first configure-stage error, and there will be more. To simplify troubleshooting, you should take a look at file called config.log, which contains output produced by conifugure script. If this log is not verbose enough, you can start the configure with command-line argument –debug-configure. It will make the script to produce additional log called debug-configure.log which is very verbose.

Installing bootstrap JDK.

Large part of JDK is written in Java,including the compiler. So building JDK requires you to have some bootstrap JDK. I’ve never got any problems installing it. You can even install it into default directory, and at any path, even the one which includes spaces.

Having fun with Microsoft Windows 7 SDK.

MinGW provides a C and C++ compilers for Windows, but the only officially supported by OpenJDK is Microsoft Visual C++ compiler, and we are going to use it. Otherwise configure will complain that it cannot find Visual Studio and quit. If you own Visual Studio, that’s great, and you can skip this part. However, in this article I’ll describe how to use minimalist development tools. So, we will use Microsoft Windows 7 SDK, which includes command-line C and C++ compilers from Visual Studio 2010. And it is free! You should download it from official site of Microsoft. There are web installer and several ISO images: for 32-bit systems, for Itanium and for 64-bit systems (amd-64). During the installation you can select which components to install, and I suggest to keep default settings, which include all necessary libraries and the compiler. If you will encounter some problems during the installation, check installation logs for exact description of the failure. I’ve got an error saying that SDK can’t install redistributable runtime libraries. Even de-selecting these libraries in a list of installed components doesn’t help. This happens because you already have a more recent version of those libraries installed (I had version 10.0.40219, and SDK will install 10.0.30319). It’s a shame for Microsoft to keep such bugs in installer. The only workaround is to uninstall your current redistributable of Microsoft Visual C runtime libraries, then install Windows SDK, and then download and install latest version of runtime library.

Now let’s check if compilers are working. If you will skip this part, you may get nasty errors much later. So, go to “c:\Program files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64” and launch cvtres.exe. If it has started successfully, that’s good. But on some systems it fails with application error. In fact you can skip this error, since it will not manifest at configure stage, but you’ll get strange error messages later on make stage, so let’s fix it now. Careful investigation with Dependency Walker tool shows that cvtres.exe imports a bunch of functions from msvcr100_clr0400.dll, and this dll doesn’t have any exported functions. Actually a version of this library included in SDK is OK, but some update for Microsoft .Net framework overwrites it with no-export version. Nice. In order to fix this, you need to download a patch from Microsoft called Microsoft Visual C++ 2010 Service Pack 1 Compiler Update for the Windows SDK 7.1. It will fix dependency problem for cvtres.exe, it will use another version of runtime dll. Download the update, install it and check that cvtres.exe works.

No, that’s not all. The update we just applied broke another thing. Unbelievable. I’ve created an empty file called ammintrin.h just to get around this annoying thing.

Patching the build scripts

Having Windows SDK will let you get further with configure, but eventually it will fail. That happens because scripts for building OpenJDK 8 using MSYS have errors. These errors were fixed in scripts for OpenJDK 9. The link to fixes could be found in this mail thread. Initial letter from Volker Simonis contains change request, and in subsequent messages Eric Joelsson extended it. Here is a list of changes:

  1. Fix for bsdcpio in basics.m4, which we have already applied
  2. Change in basics_windows.m4, which fixes AC_DEFUN([BASIC_FIXUP_EXECUTABLE_MSYS] problem with configure cannot find set_env.cmd file of Windows SDK
  3. Two fixes in toolchain_windows.m4: one for architecture type, and another with quotes for grep
  4. Fixes in platform.m4 for correct environment value. It’s a supplementary fix for other fixes to work.
  5. Fixes in NativeCompilation.gmk and will help if you’ll have an error during make. Without those fixes you’ll have to clean everything and re-make again from scratch, which takes a lot of time

So we should manually apply those fixes for OpenJDK 8. There are also change in, but you don’t need to apply it. Instead, generate it via autogen.


OpenJDK requires FreeType library. You can build it yourself from sources, I’ve downloaded a pre-built version. However, this pre-build version was strange: it included import library freetype.lib with all functions prefixed with underscore (“_”). To fix this, I’ve created an import library manually from dll using lib tool included in Microsoft Visual C command-line compiler suite (lib.exe /def:freetype6.def). This will produce a file freetype6.lib, which you should rename to freetype.lib, overwriting existing file (I’ve made a backup copy of it called _freetype.lib). You also need to copy freetype6.dll from bin directory in to lib directory and rename it to freetype.dll. And, finally, you need to explicitly specify path to the location where you’ve installed FreeType. A corresponding command-line argument for configure script is called –with-freetype.

Completing the configure

If you’ve done everything right, the configure step will successfully finish. The result will be stored in build directory of OpenJDK. The main item here is specs.gmk. Now you should download modules with source code.


Launch make all. If make hangs edit specs.gmk and set JOBS=1. As a result you’ll get directory called j2sdk-image, that’s your JDK!

Categories: Java, Windows Tags: , , ,

Types and programming languages

June 6, 2013 Leave a comment

Typed program consists of expressions and types. Types are assigned to (or better say “declared for”) expressions by programmer. Programming language has means of declaring basic expressions and constructing complex expressions from parts. Each facility for constructing expressions has a corresponding way of constructing a type of compound expression. Sometimes an attempt to construct a type will produce an error, saying that types of subexpressions are incompatible this way. For example, a facility of function application will produce a type error if first argument is not a function. If a constructed type doesn’t match the type declared by programmer, it is another case of typing error. This is a one side of a types: they are abstract and they provide a way to check a structure of a program.
There is another side of types: they are sets of values. Of course, each value can belong to any number of sets. For example, 5 is a natural, integer and real. So, by looking at the value you cannot say it’s type, since it has many. However, values constitute a special kind of expressions: a trivial expression. It is called trivial because it is trivial to evaluate. So, the phrase “value ‘5’ has a type ‘Integer'” should mean that “I’m talking about trivial expression ‘5’ with type ‘Integer'”. This side of types helps us to predict the set of all possible results of our programs, and also helps runtime system to allocate enough space to store any possible value belonging to the set.

Categories: Technology

The last difference between OpenJDK and Oracle JDK

January 18, 2013 4 comments

Recently I’ve spent a lot of time investigating font rasterization (a great topic which deserves a separate post). Most applications use font engine which is built into graphics library or widget toolkit. Only few cross-platform applications which badly need to provide consistent text layout (Acrobat Reader, for example) are using their own font engines (like Adobe CoolType). Java platform is one of such applications, since it has its own graphics library. If you are curious take a look at this article comparing font engines, including one from Java platform. From publically available information I understood that OpenJDK uses FreeType library. I thought: “That’s great, I have JDK 1.7 installed so this library must be there, let’s take a look”. But I could not find any traces of freetype.dll in JDK. I was puzzled and tried to find some answers in sources of OpenJDK. Imagine my surprize then I’ve found that Oracle JDK still uses proprietary T2K font library (located in jre/bin/t2k.dll)! Both Oracle JDK and OpenJDK are built from the same sources, and linking to external libraries happens in runtime. There is a logic which checks if JDK is running in “OpenJDK” mode or “Oracle JDK” mode, and, depending on that, loads either FreeType or T2K (see I thought: “I was always curious about remaining differences between OpenJDK and Oracle JDK, and eventually I’ve found one!”. An interesting thing is how JDK determines in runtime if it is OpenJDK or Oracle JDK. It checks if there is a file for Lucida font in JRE. A long time ago Sun had lots of complains that “write once run anywhere” promise doesn’t actually hold, especially for look and feel. Different systems had different fonts, and sometimes even fonts with same names had different glyph sizes, leading to inconsistent text layout. To fix this Sun have licensed Lucida font for distribution with JRE and made this font default. This font is absent from OpenJDK distribution, and, as I said, this fact causes JDK to link in runtime with FreeType, and to link with T2K otherwise. I was surprized, since I’ve expected a global configuration flag, something like “isOpenJDK”. I thought: “OK, let’s take a look what other specific hacks other sub-systems use to distinguish between OpenJDK and Oracle JDK”. It turned out that there are no other parts where this difference matters. Font subsystem is a last one. So I was a lucky guy, getting directly into it.

Categories: Java Tags: , ,

“Definitional interpreters” by J. Reynolds

October 3, 2012 Leave a comment

I’ve just completed reading of a famous paper of J. Reynolds “Definitional interpreters for high-order languages”. This paper is so good that I re-read it every two years. First, it has obvious historical value, since it introduced very important concepts for compiler writing and programming language semantics. Even nowdays it is a great tool for undestanding these concepts. It is focused, concise, simple and still very deep (like a half of SICP comressed 10 times). This combination of depth and conciseness is very thought provoking. Each time I read this paper I do two passes. First pass is to strengthen my understanding of overall ideas, and second is for reflections and deep digging. This time I decided to write down the results of second pass. Two years later I’ll do it again and then compare.

The paper is about operational semantics of programming languages. It shows how a meaning of programming language is given by providing an interpreter for this language implemented in another, better understood language, for example an instruction set of some abstract machine. A simple purely applicative high-order language is defined by providing a full operational semantics as a set of rules in spoken language (abstract machine implied). Then author sets a task of implementing an interpreter for that language in that language. Given semantics provides us with understanding of the tool we use and of the thing we make. The purpose of investigation is to get a deep understanding of a nature of high-order functions, and an order of evaluation. There is also a third very important point: a nature of recursion.

As a first step an author provides us with “direct” interpreter, which uses high-order techniques. Unfortunatelly, there is no explanation of how this interpreter is obtained, it is just given. The most striking feature of this  interpreter is that it is meta-cirular, which means that each feature in defined language is implemented directly by the same feature of implementation language. Evaluation of application expression is performed by application, and evaluation of lambda expression produces function. This simplicity is stiking because every reader knows very well that production compilers for programming languages are big and complex. An answer is simple: our interpreter is not conserned with problems of parsing, of code generation and of optimization. However, apparent simplicity is deceaving. Detailed explanations of operational semantics are encoded using high-level techniques, which makes them less explicit and less obvious. The main mystery is an implementation of recursion, which is not revealed since letrec is implemented via letrec.On the over hand, this simple interpreter is a good exercise (or a good example) of a program written in high-level language.

As a second step, this interpreter is defunctionalized, and all high-order functions are removed. Instead, a data structures are provided. This second interpreter is much closer to operational semantics given in the beginning. So, probably a better way to arrange a paper was to start from first-order interpreter and then moving to high-order interpreter. Someone who is familiar with lambda calculus will also note that replacement of high-order functions with data structures is a cheat, because all data structures are syntaxic sugar for lambda terms. Apparent difference is that high-order interpreter produces functions which already contain computations, which are just delayed until a parameter will be supplied. First order interpreter breaks this by adding encode function (which produces a record which is, in fact, a decode function), and by moving computation later just after function which interprets record. I think that this re-arrangement of computations is a most important part.

So, high-order programming style specifies computations which are delayed until all input is available. Delayed computations are two-way abstraction facility: it is opaque for a code which will supply an input, and a delayed computation doesn’t have an access to the code which invokes it, only to supplied parameter. Defunctionalization breaks this abstraction: instead of providing a delayed computation there is an environment captured and computation representation encoded, and the code which supplies an input is now responsible for interpreting that encoded computation. Defunctionalization makes data flow of interpreted program more apparent.

Similar trick with delaying happens with recursion. The most tricky part in explanation is to show that new(e) is the same as e. This happens because instead of packaging environment as function (delayed computation with everything ready except of variable name), an environment contains a syntaxic part of declaration expression, (a “thunk”). Environment now also interpreted by function get(), which unpacks the trunk and evaluates an expression by providing the same enironment which binds name to the trunk. This means that, for example, while evaluating a following expression:

letrec fractal = lambda(x).if x == 0 then 1 else fractal(x – 1)
in fractal(200)

each time when body of lambda encounters a “fractal” name then it first discovers a trunk, then creates a new closure based on it, and then passes a closure into eval function together with same environment, so making of closure from trunk will happen again and again in a loop. This is not very efficient, but simple and clear. More efficient interpreter will use assignment. So, by delaying an evaluation of recursive definition we don’t have to use cyclic records, but somehow recursion is implemented. If get() performs actual evaluation, then recursion in defined language depends on recursion get() -> eval() -> get() -> eval() in defining language. But get() performs simplest evaluation by returning a closure, and actual interpretation of that happens in eval(), so recursion depends on eval() calling itself in a loop. Unlike high-order functions, a recursion not an introduced feature, but meta-circular. After understanding this I immediatelly undestood that this result should be expected. Loops are evaluated by evaluation loop, that’s the only way.

A great thing about second interpreter is that it makes it clear that evaluation is a manipulation on environments, and nothing more. Anyway, programs are closed lambda terms, which are just combinators.

The most difficult part of the paper for me is an introduction of continuations. To understand it, one should first clearly understand a problem. Initially we don’t need an interpreter which allows us flexibly change order of evaluation. We want interpreter which performs some declared evaluation strategy on interpreted program independently on evaluation order of defining language. So all this talk about “serious functions” is not about some abstract functions, but about functions of our interpreter itself. In fact, that we want to do is to make programs which loop forever in case of call-by-value to do it, to loop forever. Yes, we want programs which we expect to not terminate to do it.

After this text was written, I’ve discovered “Definitional Interpreters Revisited” from the same author. Better late then never.

How RMI works

July 17, 2012 Leave a comment

Sometimes the best way to teach someone how to use something is to explain how it works inside. This small explanation on Java RMI was written especially for me so I could quickly restore this knowledge in case I forget.

If you have some object and you want to make it accessible for remote parties, then you have to “export” it into RMI subsystem. RMI will generate some sort of identifier for your object and will store a binding between your object and this identifier inside some storage. When remote party wants to make a call to your object, it will make a connection to your JVM, and will send a protocol message containing object identifier, name of method and parameters in serialized form. RMI subsystem will find an object by identifier, will deserialize parameters and then will perform method invocation by using reflection.

Serialized form of parameters contain their exact class. So even if parameters are declared in method as something abstract, a server first creates instances of their exact class and only then performs upcast. This means that exact classes of parameters should be in server’s classpath.

To perform a communication a remote party should somehow obtain an identifier for exported object. This is solved by making additional lookup. A specific object named “Registry” is bound to some static identifier (let’s call it “1”). This object has his own storage and it allows mapping of other objects to strings. So to obtain a reference to “registered” remote object a client should know a string key which was used during object’s registration. A client  constructs a reference to registry using static identifier “1”, then asks it to return an identifier of registered object.

This double-referencing seems complex. However, it provides some level of protection. Registered objects are “public” and anyone who knows a name can call them. Names by which objects are registered are not secret, and you can query a registry for a list of all names. A method call to a public object may return a remote reference to some “private” object, with randomly generated id which is hard to guess, so it will be available only to method’s caller.

If a server wishes to return a remote reference to an object instead of a serialized copy, then it should export this object to RMI subsystem. The same is true for a client if it provides a callback parameter. UnicastRemoteObject is an object which automatically exports itself in a constructor.

Let’s check if we understand everything by describing a process of registering an object. Registry is often started as a standalone process. If a server wants to register an object, it should first construct a remote interface for registry. Interface itself is known (“java.rmi.Registry”) and located in runtime library. Object identifier is also known, it is static. So server should provide only host and port where RMI registry is running. A server exports his object, then invokes bind() method. RMI understands that argument to remote call was exported, so it sends object identifier and names of classes which are required for remote interface (interface itself, all super-interfaces, all declared parameter classes and all declared return classes). String key is serialized. Now serialized string, identifier of registry object and info about registered object will be sent to registry process. RMI subsystem in registry will create a remote reference with object’s identifier which implements object’s remote interface. Now RMI will locate registry object using registry’s identifier, and will invoke a method bind() to store remote reference together with key. When a client invokes lookup() it connects to registry in a same way as server, and server transfers stored remote reference to client. Now client can connect directly to server and make a call.

The bad thing with RMI is that because of serialization a server should be able to create exact classes of parameter objects, and client should be able to create exact classes of return values. Registry also should know a lot about all registered interfaces. This makes systems build on top of RMI not very flexible. However, there is a way how one side can tell to RMI classloader on the other side about location of classfiles. It is a system property “java.rmi.server.codebase”. To make things easy I’ve written a simple HTTP server which could be deployed in any application which uses RMI, so you will be sure that if it compiles, then it works.

Categories: Java, Technology Tags: ,