Skip to main content

Posts

Showing posts from 2015

Which thread executes CompletableFuture's tasks and callbacks?

CompletableFuture is still a relatively fresh concept, despite being introduced almost two years ago (!) in March 2014 with Java 8. But maybe it's good that this class is not so well known since it can be easily abused, especially with regards to threads and thread pools that are involved along the way. This article aims to describe how threads are used with CompletableFuture.

Running tasks This is the fundamental part of the API. There is a convenient supplyAsync() method that is similar to ExecutorService.submit(), but returning CompletableFuture:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try (InputStream is = new URL("http://www.nurkiewicz.com").openStream()) { log.info("Downloading"); return IOUtils.toString(is, StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } }); The problem is, supply…

GeeCON programming contest answers

During this year's GeeCON and GeeCON Prague my company 4FinanceIT was giving away some gifts for people who correctly answered a couple of programming questions. Quite a few people asked about correct answers. Since I happened to write these tasks along with sample answers, let's share them publicly then:
1. Which of the following will not work as expected in multi-threaded environment (choose one)? new LongAccumulator(Math::min, Integer.MAX_VALUE); //a) new LongAccumulator(Math::max, Integer.MIN_VALUE); //b) new LongAccumulator(Math::addExact, 0); //c) new LongAccumulator(Math::subtractExact, 0) //d) Answer d) - according to JavaDoc: this class is only applicable to functions for which the order of accumulation does not matter Let's say you are accumulating 1 and 2. The result can be 0 - 1 - 2 but also (0 - 1) - (0 - 2) or (0 - 2) - (0 - 1).
See also: How LongAccumulator and DoubleAccumulator classes work?
2. Implement the following function:static &…

Spock VW: writing custom Spock framework extensions

Spock framework has multiple built-in extensions that support many core features like @Ignore and @Timeout annotations. But more importantly developers are encouraged to write their own extensions. For example SpringExtension nicely integrates Spock with Spring framework. Writing custom extensions is not very well documented. In this article we will write very simple extension. It is not a comprehensive guide but just a funny showcase.

Introducing Spock VW extension In some engineering branches[1] rigorous tests must pass only when external audit is looking. In programming this would be a continuous integration server. Spock VW extension makes sure all tests pass on CI server, even if they fail on developers machine or on production. The idea is heavily inspired by phpunit-vw. Let's take this simple, completely made up test that can't possibly succeed:

@Unroll class EmissionsSpec extends Specification { def 'nitrogen oxide emission (#emission) in #model must not exceed…

Displaying progress of Spring application startup in web browser

When you restart your enterprise application, what do your clients see when they open the web browser?

They see nothing, server doesn't respond yet so web browser displays ERR_CONNECTION_REFUSED

Web proxy (if any) in front of your application notices that it's down and display "friendly" error message

The website takes forever to load - it accepted socket connection and HTTP request but waits with response until application actually boots up

Your application is scaled out so that other nodes quickly pick up requests and no one notices (and session is replicated anyway)

...or the application is so fast to start that no one notices any disruption (hey, plain Spring Boot Hello world app takes less than 3 seconds from hitting java -jar ... [Enter] to start serving requests). BTW check out SPR-8767: Parallel bean initialization during startup.

It's definitely better to be in situation 4. and 5., but in this article we'll cover more robust handling of situations 1.…

Dependency injection: syntax sugar over function composition

Quoting Dependency Injection Demystified:

"Dependency Injection" is a 25-dollar term for a 5-cent concept.

*James Shore, 22 Mar, 2006

Dependency injection, as much as it is important when writing testable, composable and well-structured applications, means nothing more than having objects with constructors. In this article I want to show you how dependency injection is basically just a syntax sugar that hides function currying and composition. Don't worry, we'll go very slowly trying to explain why these two concepts are very much a like.

Setters, annotations and constructors Spring bean or EJB is a Java object. However if you look closely most beans are actually stateless after creation. Calling methods on Spring bean rarely modifies the state of that bean. Most of the time beans are just convenient namespaces for a bunch of procedures working in similar context. We don't modify the state of CustomerService when calling invoice(), we merely delegate to anoth…

Server-sent events with RxJava and SseEmitter

Spring framework 4.2 GA is almost released, let's look at some new features it provides. The one that got my attention is a simple new class SseEmitter - an abstraction over sever-sent events easily used in Spring MVC controllers. SSE is a technology that allows you to stream data from server to the browser within one HTTP connection in one direction. It sounds like a subset of what websockets can do. However since it's a much simpler protocol, it may be used when full-duplex is not necessary, e.g. pushing stock price changes in real-time or showing progress of long-running process. This is going to be our example.

Imagine we have a virtual coin miner with the following API:

public interface CoinMiner { BigDecimal mine() { //... } } Every time we call mine() we have to wait few seconds and we get around 1 coin in return (on average). If we want to mine multiple coins, we have to call this method multiple times:

@RestController public class MiningController { …

Notes after GOTO Amsterdam

Few weeks ago I attended GOTO Amsterdam conference. Beautiful venue, great food but most importantly, couple of interesting talks that caught my attention. Out of two days and five to six tracks I want to comment couple of sessions.

"Challenges in Implementing MicroServices" by Fred George Yet another microservices talk, you might say. But this one was slightly more in-depth and practical. [Slides are available], let me comment slide 10, copied here:

Summary principles of MicroServicesVery, very smallTeam size of one to develop/maintainLoosely coupled (including flow)Multiple versions acceptable (encouraged?)Self-monitoring of each servicePublish interesting "stuff" (w/o explicit requirements)"Application" seems to be a poor conceptualization I don't quite buy the "micro-" or even "nano-" services trend. The service shouldn't be as small as possible, it should encapsulate business component, typically bounded context. If it'…

RESTful considered harmful

I don't like RESTful principles and APIs. In recent years it is seen as universal protocol for inter-process communication, especially in distributed systems. However I see many deficiencies of REST and there are alternatives that work well for certain use cases. Obviously there is no one size fits all, I just want to emphasize that REST architecture is flawed in a number of ways.
Bloated, human readable format that demands extra compression The de facto standard format for REST is JSON. At least it's way better than SOAP with its XML and envelopes. Either lots of network bandwidth is wasted (can be an issue with mobile devices or large data centers) or CPU is spent on compression and decompression. A lovely quote:
[the] internet is running in debug mode source It's a serious issue, ask high-frequency traders how hard parsing text-based FIX is. There are plenty of well-established binary protocols that are both easy to parse and use little memory, e.g. Protocol buffers, Av…

Consuming java.util.concurrent.BlockingQueue as rx.Observable

Classical producer-consumer pattern is relatively simple in Java since we have java.util.concurrent.BlockingQueue. To avoid busy waiting and error-prone manual locking we simply take advantage of put() and take(). They both block if queue is full or empty respectively. All we need is a bunch of threads sharing reference to the same queue: some producing and others consuming. And of course the queue has to have a limited capacity, otherwise we will soon run out of memory in case of producers outperforming consumers. Greg Young couldn't emphasize enough this rule during Devoxx Poland:

Never, ever create an unbounded queue

Producer-consumer using BlockingQueue Here is a simplest example. First we need a producer that puts objects in a shared queue:

import lombok.Value; import lombok.extern.slf4j.Slf4j; @Slf4j @Value class Producer implements Runnable { private final BlockingQueue<User> queue; @Override public void run() { try { while (!Thread.currentThread().is…

Writing a download server. Part VI: Describe what you send (Content-type, et.al.)

As far as HTTP is concerned, what client is downloading is just a bunch of bytes. However client would really like to know how to interpret these bytes. Is it an image? Or maybe a ZIP file? The last part of this series describes how to give a hint to the client what she downloads.

Set Content-type response header Content type describes MIME type of resource being returned. This header instructs web browser how to treat stream of bytes flowing from the download server. Without this header browser is clueless of what it actually received and simply displays content as if it was a text file. Needless to say binary PDF (see screenshot above), image or video displayed like a text file doesn't look good. The hardest part is to actually obtain media type somehow. Luckily Java itself has a tool for guessing media type based on extension and/or contents of the resource:

import com.google.common.net.MediaType; import java.io.*; import java.time.Instant; public class FileSystemPointer imple…