Tuesday 27 November 2012

RateLimiter - limit amount of actions per seconds

Next useful utility from Guava library

A rate limiter. Conceptually, a rate limiter distributes permits at a configurable rate. Each acquire() blocks if necessary until a permit is available, and then takes it. Once acquired, permits need not be released.

Rate limiters are often used to restrict the rate at which some physical or logical resource is accessed. This is in contrast to Semaphore which restricts the number of concurrent accesses instead of the rate.

You can read more in guava javadoc:
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/RateLimiter.html

Saturday 17 November 2012

Java Random thread save

Examples:
ThreadLocalRandom.current().nextInt()
ThreadLocalRandom.current().nextDouble()
...

TimeUnit class

If you want your java program to wait for defined time amount use class TimeUnit. It is more clean than using Thread.sleep.
Examples:
TimeUnit.NANOSECONDS.sleep(10)
TimeUnit.SECONDS.sleep(10)

Sunday 4 November 2012

Guava light cache

If you have a need to declare a small cache which have to be cleared periodically you can easily do it using Guava Cache.
We have to define loader that will load cache element and a period after which it will throw an item away. And then next read will use a loader to load an element into cache again. We can also define a cache in the way it will throw away an item if it was not read for a period of time.
Here is an example:
private LoadingCache<String, MyClass> cache;
CacheLoader<String, MyClass> loader = new CacheLoader<String, MyClass> () {
      public MyClass load(String key) throws Exception {
        return ourService.get(key);
      }
    };
cache = CacheBuilder.newBuilder().
        expireAfterWrite(1, TimeUnit.MINUTES).
        build(loader);

More about this subject here: http://code.google.com/p/guava-libraries/wiki/CachesExplained

Defining Mockito mock bean from Spring xml definition

You can define a spring bean in spring xml context that will be a Mockito mock of a given type:

  

But if you want to inject that bean by type, you have to define it as a Proxy of given interface:

    
      
        
      
    
    
      com.example.Repository