Translate

Показ дописів із міткою Guava. Показати всі дописи
Показ дописів із міткою Guava. Показати всі дописи

субота, 8 червня 2013 р.

Guava's EventBus - Simple Publisher/Subscriber


Looking over recent additions to Google's Guava Libraries Release 10 I noticed the addition of EventBus. This is a lightweight implementation of a publish-subscribe style messaging system. This is similar to the publish-subscribe model provided by JMS, however the messages remain within the application rather than being broadcast externally.
EventBus allows you to create streams within your program to which objects can subscribe; they will then receive messages published to those streams. Although this inter-object communication is not particularly difficult to recreate using patterns such as singletons, EventBus does provide a particularly simple and lightweight mechanism. Singletons also make having multiple event buses of a single type more difficult, and are hard to test.
As an example I am going to create a simple multi-user chat program using sockets that several people will connect to via telnet. We will simply create an EventBus which will serve as a channel. Any messages that a user sends to the system will be published to all the other users.


пʼятниця, 7 червня 2013 р.

5 Reasons to use Guava


Guava is an open source library containing many classes for Java and written by Google. It's a potentially useful source of miscellaneous utility functions and classes that I'm sure many developers have written themselves before, or maybe just wanted and never had time to write. Here's 5 good reasons to use it!
1. Collection Initializers and Utilities
Generic homogeneous collections are a great feature to have in Java, but sometimes their construction is a bit too verbose, for example:

final Map<String, Map<String, Integer>> lookup = new HashMap<String, Map<String, Integer>>();
Java 7 solves this problem in a really generic way, by allowing a limited form of type inference informally referred to as the Diamond Operator. So we can rewrite the above example as:
final Map<String, Map<String, Integer>> lookup = new HashMap<>();
It's actually already possible to have this kind of inference for non-constructor methods in earlier Java releases, and Guava provides many ready made constructors for existing Java Collections. The above example can be written as:
final Map<String, Map<String, Integer>> lookup = Maps.newHashMap();
Guava also provides many useful utility functions for collections under the Maps, Sets et al. classes. Particular favourites of mine are the Sets.union and Sets.intersection methods that return views on the sets, rather than recomputing the values.