Translate

четвер, 31 березня 2011 р.

Многопоточность в Java: ExecutorService


В Java 5 было добавлено много вещей для организации многопоточности и особенно касаемо организации параллельного доступа. В этой и последующих статьях мы пройдемся по некоторыми из них.


ExecutorService


До Java 5 для организации работы с несколькими потоками приходилось использовать сторонние имплеменации пулинга или писать свой. С появлением ExecutorService такая необходимость отпала.

ExecutorService исполняет асинхронный код в одном или нескольких потоках. Создание инстанса ExecutorService'а делается либо вручную через конкретные имплементации (ScheduledThreadPoolExecutor илиThreadPoolExecutor), но проще будет использовать фабрики класса Executors. Например, если надо создать пул с 2мя потоками, то делается это так:
ExecutorService service = Executors.newFixedThreadPool(2);

Если требуется использовать кэширующий пул потоков, который создает потоки по мере необходимости, но переиспользует неактивные потоки (и подчищает потоки, которые были неактивные некоторое время), то это задается следующим образом:
ExecutorService service = Executors.newCachedThreadPool();

Теперь небольшой пример. Допустим, надо запустить какой-нибудь код асинхронно 10 раз. Основываясь на вышесказанном, код будет выглядеть так:
ExecutorService service = Executors.newCachedThreadPool();
for(int i = 0; i < 10; i++) {
 service.submit(new Runnable() {
  public void run() {
   // snip... piece of code
  }
 });
}

Метод submit также возвращает объект Future, который содержит информацию о статусе исполнения переданного Runnable или Callable (который может возвращать значение). Из него можно узнать выполнился ли переданный код успешно, или он еще выполняется. Вызов метода get на объекте Futureвозвратит значение, который возвращает Callable (или null, если используется Runnable). Метод имеет 2 checked-исключения: InterruptedException, который бросается, когда выполнение прервано через методinterrupt(), или ExecutionException если код в Runnable или Callable бросил RuntimeException, что решает проблему поддержки исключений между потоками.

ScheduledExecutorService


Иногда требуется выполнение кода асихронно и периодически или требуется выполнить код через некоторое время, тогда на помощь приходит ScheduledExecutorService. Он позволяет поставить код выполняться в одном или нескольких потоках и сконфигурировать интервал или время, на которое выполненение будет отложено. Интервалом может быть время между двумя последовательными запусками или время между окончанием одного выполнения и началом другого. Методы ScheduledExecutorServiceвозвращают ScheduledFuture, который также содержит значение отсрочки для выполнения ScheduledFuture.

Например, если требуется отложить выполнение на 5 секунд, потребуется следующий код:
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable() { ... }, 5, TimeUnit.SECONDS);

Если требуется назначить выполнение каждую секунду:
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(new Runnable() { ... }, 0, 1, TimeUnit.SECONDS);

И, наконец, если требуется назначить выполнение кода с промежутком 1 секунда между выполнениями:
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleWithFixedDelay(new Runnable() { ... }, 0, 1, TimeUnit.SECONDS);

Взято звідси 

PRO:PM для true PM'ів


У рамках руху «de:coded» за підтримки ELEKS Software оголошується конкурс під назвою "PRO:PM", присвячений темі управління IT проектами. Командам буде даватись практичне завдання - проект, який необхідно повністю змоделювати, чітно описати та презентувати перед журі. Презентація кейсів відбудеться на всеукраїнському IT фестивалі «de:coded» (сам фест проходитиме у Львові 6-8 травня). Але не все так просто, як здається на перший погляд :)

1.       Для участі у конкурсі буде відібрано 6 команд по 3 людини;
2.       Для них найкращі project manager’и компанії ELEKS попередньо проведуть лекції з управління проектами;
3.       В Вас з’явиться нагода поспілкуватись з професіоналами своєї справи та дізнатись на які підводні камені вони натрапляють щодня;
4.       В Вас зможе з’явитися нагода продовжити свій розвиток, як PM’а в компанії ELEKS;
5.       Команда-переможець отримає можливість продовжити навчання в сфері управління проектами, що буде оплачуватись компанією ELEKS;
6.       Дедлайн на подачу – 4 квітня.

Взяти участь в проекті може кожен. Для цього необхідно заповнити командну або індивідуальнуаплікаційну форму та надіслати резюме на propm@decoded.org.ua.

Зацікавило? Читайте детальніше на сторінці конкурсу.

Взято звідси


пʼятницю, 25 березня 2011 р.

10-та, ювілейна, зустріч JUG of Lviv


Всім привіт
Наступна зустріч буде ювілейна для групи
Хотілось би зробити щось незвичайне ))
Отож приймаються пропозиції та варіанти
Щоб ви хотіли бачити
Як завжди чекаю листи на нашу скриньку jug.lviv.@gmail.com

середу, 16 березня 2011 р.

Відео дев'ятої зустрічі JUG


Викладаю обіцяне відео девятої зустрічі
Велике спасибі Зенику
Ну і як завжди чекаю на ваші відгуки



понеділок, 14 березня 2011 р.

Smartly load your properties




Strive for disk location-independent code nirvana

August 8, 2003
QWhat is the best strategy for loading property and configuration files in Java?
AWhen you think about how to load an external resource in Java, several options immediately come to mind: files, classpath resources, and URLs. Although all of them eventually get the job done, experience shows that classpath resources and URLs are by far the most flexible and user-friendly options.
In general, a configuration file can have an arbitrarily complex structure (e.g., an XML schema definition file). But for simplicity, I assume below that we're dealing with a flat list of name-value pairs (the familiar .properties format). There's no reason, however, why you can't apply the ideas shown below in other situations, as long as the resource in question is constructed from an InputStream.

Evil java.io.File

Using good old files (via FileInputStreamFileReader, and RandomAccessFile) is simple enough and certainly the obvious route to consider for anyone without a Java background. But it is the worst option in terms of ease of Java application deployment. Using absolute filenames in your code is not the way to write portable and disk position-independent code. Using relative filenames seems like a better alternative, but remember that they are resolved relative to the JVM's current directory. This directory setting depends on the details of the JVM's launch process, which can be obfuscated by startup shell scripts, etc. Determining the setting places an unfair amount of configuration burden on the eventual user (and in some cases, an unjustified amount of trust in the user's abilities). And in other contexts (such an Enterprise JavaBeans (EJB)/Web application server), neither you nor the user has much control over the JVM's current directory in the first place.
An ideal Java module is something you add to the classpath, and it's ready to go. Think EJB jars, Web applications packaged in.war files, and other similarly convenient deployment strategies. java.io.File is the least platform-independent area of Java. Unless you absolutely must use them, just say no to files.

Classpath resources

Having dispensed with the above diatribe, let's talk about a better option: loading resources through classloaders. This is much better because classloaders essentially act as a layer of abstraction between a resource name and its actual location on disk (or elsewhere).
Let's say you need to load a classpath resource that corresponds to a some/pkg/resource.properties file. I use classpath resource to mean something that's packaged in one of the application jars or added to the classpath before the application launches. You can add to the classpath via the -classpath JVM option each time the application starts or by placing the file in the \classes directory once and for all. The key point is that deploying a classpath resource is similar to deploying a compiled Java class, and therein lies the convenience.
You can get at some/pkg/resource.properties programmatically from your Java code in several ways. First, try:
ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
  Class.getResourceAsStream ("/some/pkg/resource.properties");
  ResourceBundle.getBundle ("some.pkg.resource");


Additionally, if the code is in a class within a some.pkg Java package, then the following works as well:
Class.getResourceAsStream ("resource.properties");


Note the subtle differences in parameter formatting for these methods. All getResourceAsStream() methods use slashes to separate package name segments, and the resource name includes the file extension. Compare that with resource bundles where the resource name looks more like a Java identifier, with dots separating package name segments (the .properties extension is implied here). Of course, that is because a resource bundle does not have to be backed by a .properties file: it can be a class, for a example.
To slightly complicate the picture, java.lang.Class's getResourceAsStream() instance method can perform package-relative resource searches (which can be handy as well, see "Got Resources?"). To distinguish between relative and absolute resource names, Class.getResourceAsStream() uses leading slashes for absolute names. In general, there's no need to use this method if you are not planning to use package-relative resource naming in code.
It is easy to get mixed up in these small behavioral differences for ClassLoader.getResourceAsStream(),Class.getResourceAsStream(), and ResourceBundle.getBundle(). The following table summarizes the salient points to help you remember:
Behavioral differences
MethodParameter formatLookup failure behaviorUsage example
ClassLoader.
getResourceAsStream()
"/"-separated names; no leading "/" (all names are absolute)Silent (returns null)this.getClass().getClassLoader()
.getResourceAsStream
("some/pkg/resource.properties")
Class.
getResourceAsStream()
"/"-separated names; leading "/" indicates absolute names; all other names are relative to the class's packageSilent (returns null)this.getClass()
.getResourceAsStream
("resource.properties")
ResourceBundle.
getBundle()
"."-separated names; all names are absolute;.propertiessuffix is impliedThrows unchecked
java.util.MissingResourceException
ResourceBundle.getBundle
("some.pkg.resource")


From data streams to java.util.Properties

You might have noticed that some previously mentioned methods are half measures only: they return InputStreams and nothing resembling a list of name-value pairs. Fortunately, loading data into such a list (which can be an instance ofjava.util.Properties) is easy enough. Because you will find yourself doing this over and over again, it makes sense to create a couple of helper methods for this purpose.
The small behavioral difference among Java's built-in methods for classpath resource loading can also be a nuisance, especially if some resource names were hardcoded but you now want to switch to another load method. It makes sense to abstract away little things like whether slashes or dots are used as name separators, etc. Without further ado, here's my PropertyLoaderAPI that you might find useful (available with this article's download):
public abstract class PropertyLoader
{
    /**
     * Looks up a resource named 'name' in the classpath. The resource must map
     * to a file with .properties extention. The name is assumed to be absolute
     * and can use either "/" or "." for package segment separation with an
     * optional leading "/" and optional ".properties" suffix. Thus, the
     * following names refer to the same resource:
     * 
* some.pkg.Resource
     * some.pkg.Resource.properties
     * some/pkg/Resource
     * some/pkg/Resource.properties
     * /some/pkg/Resource
     * /some/pkg/Resource.properties
     * 
* * @param name classpath resource name [may not be null] * @param loader classloader through which to load the resource [null * is equivalent to the application loader] * * @return resource converted to java.util.Properties [may be null if the * resource was not found and THROW_ON_LOAD_FAILURE is false] * @throws IllegalArgumentException if the resource was not found and * THROW_ON_LOAD_FAILURE is true */ public static Properties loadProperties (String name, ClassLoader loader) { if (name == null) throw new IllegalArgumentException ("null input: name"); if (name.startsWith ("/")) name = name.substring (1); if (name.endsWith (SUFFIX)) name = name.substring (0, name.length () - SUFFIX.length ()); Properties result = null; InputStream in = null; try { if (loader == null) loader = ClassLoader.getSystemClassLoader (); if (LOAD_AS_RESOURCE_BUNDLE) { name = name.replace ('/', '.'); // Throws MissingResourceException on lookup failures: final ResourceBundle rb = ResourceBundle.getBundle (name, Locale.getDefault (), loader); result = new Properties (); for (Enumeration keys = rb.getKeys (); keys.hasMoreElements ();) { final String key = (String) keys.nextElement (); final String value = rb.getString (key); result.put (key, value); } } else { name = name.replace ('.', '/'); if (! name.endsWith (SUFFIX)) name = name.concat (SUFFIX); // Returns null on lookup failures: in = loader.getResourceAsStream (name); if (in != null) { result = new Properties (); result.load (in); // Can throw IOException } } } catch (Exception e) { result = null; } finally { if (in != null) try { in.close (); } catch (Throwable ignore) {} } if (THROW_ON_LOAD_FAILURE && (result == null)) { throw new IllegalArgumentException ("could not load [" + name + "]"+ " as " + (LOAD_AS_RESOURCE_BUNDLE ? "a resource bundle" : "a classloader resource")); } return result; } /** * A convenience overload of {@link #loadProperties(String, ClassLoader)} * that uses the current thread's context classloader. */ public static Properties loadProperties (final String name) { return loadProperties (name, Thread.currentThread ().getContextClassLoader ()); } private static final boolean THROW_ON_LOAD_FAILURE = true; private static final boolean LOAD_AS_RESOURCE_BUNDLE = false; private static final String SUFFIX = ".properties"; } // End of class


The Javadoc comment for the loadProperties() method shows that the method's input requirements are quite relaxed: it accepts a resource name formatted according to any of the native method's schemes (except for package-relative names possible with Class.getResourceAsStream()) and normalizes it internally to do the right thing.
The shorter loadProperties() convenience method decides which classloader to use for loading the resource. The solution shown is reasonable but not perfect; you might consider using techniques described in "Find a Way Out of the ClassLoader Maze" instead.
Note that two conditional compilation constants control loadProperties() behavior, and you can tune them to suit your tastes:
  • THROW_ON_LOAD_FAILURE selects whether loadProperties() throws an exception or merely returns null when it can't find the resource
  • LOAD_AS_RESOURCE_BUNDLE selects whether the resource is searched as a resource bundle or as a generic classpath resource


Setting LOAD_AS_RESOURCE_BUNDLE to true isn't advantageous unless you want to benefit from localization support built intojava.util.ResourceBundle. Also, Java internally caches resource bundles, so you can avoid repeated disk file reads for the same resource name.

More things to come

I intentionally omitted an interesting classpath resource loading method, ClassLoader.getResources(). Despite its infrequent use, ClassLoader.getResources() allows for some very intriguing options in designing highly customizable and easily configurable applications.
I didn't discuss ClassLoader.getResources() in this article because it's worthy of a dedicated article. As it happens, this method goes hand in hand with the remaining way to acquire resources: java.net.URLs. You can use these as even more general-purpose resource descriptors than classpath resource name strings. Look for more details in the next Java Q&Ainstallment.

About the author

Vladimir Roubtsov has programmed in a variety of languages for more than 13 years, including Java since 1995. Currently, he develops enterprise software as a senior engineer for Trilogy in Austin, Texas.Read more about Core Java in JavaWorld's Core Java section.



This story appeared on JavaWorld at
http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html


четвер, 10 березня 2011 р.

Wallaby від Adobe


Восени Adobe  презентувала нову технологію для конвертування Flash в HTML5 під назвою Wallaby. На сайті можна почитати їхні Release Notes. Тепер Wallaby  можна скачати на Adobe Labs

неділю, 6 березня 2011 р.

How to create gwt maven project?


How to create gwt maven project? Easy! Just run

mvn archetype:generate -DarchetypeRepository=repo1.maven.org -DarchetypeGroupId=org.codehaus.mojo -DarchetypeArtifactId=gwt-maven-plugin -DarchetypeVersion=2.1.0-1

This maven plugin generates project based on GWT version 2.1.0  If you prefer to use version 2.2.0, just replace version in pom.xml. Then the following compilation error will occur

java.lang.NoClassDefFoundError: com/google/gwt/core/ext/GeneratorExt
[INFO] at java.lang.ClassLoader.defineClass1(Native Method)
[INFO] at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
[INFO] at java.lang.ClassLoader.defineClass(ClassLoader.java:616)

You should add dependency on gwt-dev.jar

<dependency>
        <groupId>com.google.gwt</groupId>
        <artifactId>gwt-dev</artifactId>
        <version>2.2.0</version>
        <type>jar</type>
        <scope>compile</scope>
</dependency>
By maven-googlewebtoolkit2-plugin

суботу, 5 березня 2011 р.

Maven Multi-Module Quickstart



Recently I’ve had lots of questions about how to create multi-module projects, so when I discovered this technique, I thought I’d write this up. This technique exploits a little known feature of the archetype:create plugin, and the Maven site archetype to kickstart your project. Creating a multi-module project has many benefits, one of them being the ability to build every artifact in a project with one simple “mvn compile” command. Another benefit is that if you are using either the maven eclipse:eclipse plugin or the idea:idea plugin, you can enter this command at the root of the project and it will generate all of the project files for all of the contained modules.

First generate the top level project using the maven-archetype-site-simple archetype using the following command,
mvn archetype:create
 -DgroupId=[Java:the project's group id]
 -DartifactId=[Java:the project's artifact id]
 -DarchetypeArtifactId=maven-archetype-site-simple
this will generate a Maven project with the following directory structure.
Maven Site Simple Folder
The project that is generated is the minimum project setup to generate site documentation. The index.apt file is the main index page for the site, and is written in the Almost Plain Text format, which is a wiki like format. You can also generate a more complete site project using the maven-archetype-site archetype like this,
mvn archetype:create
 -DgroupId=[Java:the project's group id]
 -DartifactId=[Java:the project's artifact id]
 -DarchetypeArtifactId=maven-archetype-site
this will generate the following project structure.
Maven Site Folder Structure
After you have generated the site project, edit the pom.xml created from the site archetype plugin. Make sure the the packaging type is set to “pom” like the following.
1<project>
2    <modelversion>4.0.0modelversion>
3    <groupid>com.pillartechnologygroupid>
4    <artifactid>sampleProjectartifactid>
5    <version>1.0-SNAPSHOTversion>
6<packaging>pompackaging>
7...
8project>
By setting the packaging type to “pom”, any projects you generate from the root of the project directory will insert itself into the project by creating an entry into the modules section of the pom.xml for the site. In the root directory of your project that you created above, type in the following command,
mvn archetype:create
 -DgroupId=[Java:the module's group id]
 -DartifactId=[Java:the module's artifact id]
if you now edit the pom.xml for the main project, you should see an entry towards the bottom of the file like the following.
1...
2<modules>
3    <module>sampleModulemodule>
4modules>
5...
взято звідси

 можна також скористатись командою

1
mvn archetype:generate
тоді в інтерактивному діалозі потрібно вибрати потрібний айтем
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Choose archetype:
1: remote -> docbkx-quickstart-archetype (-)
2: remote -> gquery-archetype (-)
3: remote -> gquery-plugin-archetype (-)
...
205: remote -> pom-root (Root project archetype for
creating multi module projects)
...
306: remote -> trails-secure-archetype (-)
307: remote -> tynamo-archetype (-)
308: remote -> wicket-scala-archetype (Basic setup for a
project that combines Scala and Wicket,
        depending on the Wicket-Scala project. 
Includes an example Specs
        test.)
309: remote -> circumflex-archetype (-)
Choose a number: 82:

в даному випадку для батьківського багатомодульного проекту це 205 елемент ну і далі по аналогії створюємо дочірні модулі