29 August 2019

Java 8 parallel streams pitfall

1.
All parallel streams use a common fork-join thread pool, and if you submit a long-running task, you effectively block all threads in the pool. Consequently, you block all other tasks that are using parallel streams.

2.
The default processing that occurs in such a Stream uses the ForkJoinPool.commonPool(), a Thread Pool shared by the entire application.

3.
This way we essentially force the parallel stream to have a ForkJoin as a parent thread, instead of a regular thread, so ForkJoinPool.commonPool is not used. Hooray!

20 August 2019

Spring MVC AsyncRestTemplate

Simple example to call Async RestTemplate :

https://github.com/devwebcl/async-springmvc-poc

Most important snippet code:

public AsyncRestTemplate asyncRestTemplateFactory() {
 PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();

 connManager.setMaxTotal(maxTotalConnections);
 connManager.setDefaultMaxPerRoute(maxConnectionsPerRoute);
 CloseableHttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();
 HttpComponentsAsyncClientHttpRequestFactory requestAsyncFactory =
 new HttpComponentsAsyncClientHttpRequestFactory();
 requestAsyncFactory.setConnectionRequestTimeout(connectRequestTimeout);
 requestAsyncFactory.setConnectTimeout(connectTimeout);
 requestAsyncFactory.setReadTimeout(readTimeout);
 requestAsyncFactory.setHttpClient(httpClient);

 AsyncRestTemplate art = new AsyncRestTemplate();
 art.setAsyncRequestFactory(requestAsyncFactory);


 //deberia ser inyectado desde DI container
 return new AsyncRestTemplate(requestAsyncFactory);
 }



and



public String callback() throws Exception {

        Map<String, ListenableFuture<ResponseEntity<String>>> futures = new HashMap<>(); //podria ser un Guava Table
        List<String> respuestas = new ArrayList<>();
       

        AsyncFactory af = new AsyncFactory();
        AsyncRestTemplate artf = af.asyncRestTemplateFactory();

        //url a visitar
        String[] url = {"http://google.com", "http://bing.com", "https://stackoverflow.com/", "https://www.infoq.com/", "https://dzone.com/",
                        "https://jakarta.ee/", "https://www.eclipse.org/",  "http://www.noexisto.cl/", "https://spring.io/", "https://github.com/",
                        "https://www.apache.org/"};

       
        //agrego llamadas asincronas
        for(int i=0; i<url.length; i++) {
           
            HttpMethod method = HttpMethod.GET;
            Class<String> responseType = String.class;
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_PLAIN);
            HttpEntity<String> requestEntity = new HttpEntity<>("params", headers);
            //la llave es la misma url (modificable)
           
            // usar DeferredResult ?
            ListenableFuture<ResponseEntity<String>> future = artf.exchange(url[i], method, requestEntity, responseType);
                   

            // es "opcional"
            future.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
                  @Override
                  public void onSuccess(ResponseEntity<String> result) {
                    System.out.println("onSuccess " + result.getHeaders() );
                    //TODO: DeferredResult ?
                  }

                  @Override
                  public void onFailure(Throwable ex) {
                    System.out.println("onFailure!!! " + ex );
                  }
                });
               
             futures.put(url[i], future);
        }

       
        //TODO: borrar !
        // duermo los hilos solo por prueba:
        int segundos_sleep = 2;
        System.out.println("durmiendo por " + segundos_sleep + " segundos...");
        Thread.sleep(segundos_sleep * 1000);

       
        int i=0;
        //voy uno a uno... con Guava SuccessfulAsList seria lo mismo al final ya que quiero cada uno de los responses
        for (Map.Entry<String, ListenableFuture<ResponseEntity<String>>> llave : futures.entrySet()) {
           
            System.out.println((++i)+". -----------------------------------------------------\n");

            System.out.println("key = " + llave.getKey() + ",\n value = " + llave.getValue());
   
            ListenableFuture<ResponseEntity<String>> future = llave.getValue();
            ResponseEntity<String> entity = null;

            try {
           
            entity = future.get(); // blocking en cada uno, pero la respuesta ya puede existir
            } catch (InterruptedException ie) {
                ie.printStackTrace();
                continue;
            } catch (ExecutionException ee) {
                ee.printStackTrace();
                continue;
            }
               
           
            String headers = entity.getHeaders().toString();
           
            if(headers.indexOf("domain=")!=-1)
                System.out.println(headers.substring(headers.indexOf("; domain=")));
            else                
                System.out.println(headers);

            System.out.println(entity.getStatusCode());
            //System.out.println(entity.getBody());
            respuestas.add(entity.getBody().toString());
           
            System.out.println("isDone? " + future.isDone() + "\n");
        }
          

       
        System.out.println("\nfin.");
   

        //return respuestas;
        return "done";
    }

  


19 August 2019

Hungarian algorithm

When there are rows/columns, where each row is a job and each row is a worker.

We need to find the lowest cost to pair (row, column):


Job 1 Job 2 Job 3
Worker 1
2 3 3
Worker 2
3 2 3
Worker 3
3 3 2

Solution: 2, 2, 2 = 6


19 July 2019

Service migration

Co-exist different endpoints for migration purposes. It will be good to apply: Strangler Pattern: Service Migration Strategy.


UPDATE1 (14.04.2021): There are other writings from Fowler about the approach of this strategy (different names, with some minor changes).

https://www.martinfowler.com/bliki/ParallelChange.html (The API expand-contract pattern)

https://martinfowler.com/articles/consumerDrivenContracts.html

 


01 July 2019

Continuous: Integration --> Delivery --> Deployment

Continuous integration:  The concept here is to have multiple devs on a project to keep the main branch of the repo to the most current form of the source code, so each dev can check out or pull from the latest code to avoid conflicts.

Continuous integration puts a great emphasis on testing automation to check that the application is not broken whenever new commits are integrated into the main branch.

Continuous Delivery is a small build cycle with short sprints…
Where the aim is to keep the code in a deployable state at any given time. This does not mean the code or project is 100% complete, but the feature sets that are available are vetted, tested, debugged and ready to deploy, although you may not deploy at that moment.  The focus and key here are to keep the code base at a deployable state.

Continuous delivery is an extension of continuous integration to make sure that you can release new changes to your customers quickly in a sustainable way.

Continuous Deployment, every change that is made is automatically deployed to production.
Continuous deployment goes one step further than continuous delivery.

https://stackify.com/continuous-delivery-vs-continuous-deployment-vs-continuous-integration/
https://www.atlassian.com/continuous-delivery/principles/continuous-integration-vs-delivery-vs-deployment

19 June 2019

Contention RollingFileManager.checkRollover()

Contention at: org.apache.logging.log4j.core.appender.rolling.RollingFileManager.checkRollover()

This is a problem with high concurrency, and it works as designed. The file system (I/O) doesn't have  enough performance as required.

The synchronized makes BLOCKED some Java monitor when trying to acquire the resource.
 
/**
 * Determines if a rollover should occur.
 * @param event The LogEvent.
 */
public synchronized void checkRollover(final LogEvent event) {
    if (triggeringPolicy.isTriggeringEvent(event)) {
        rollover();
    }
}

The solution as mentioned above is to move to Async logging.
https://logging.apache.org/log4j/2.x/manual/async.html

JMC Events

From the Event Types tab, look at the color of each event.

Yellow represents Java Monitor Wait events.
The yellow part is when threads are waiting for an object. This often means that the thread is idle, perhaps waiting for a task.

Red represents the Java Monitor Blocked events or synchronization events. If your Java application's important threads spend a lot of time being blocked, then that means that a critical section of the application is single threaded, which is a bottleneck.

Blue represents the Socket Reads and Socket Writes events. Again, if the Java application spends a lot of time waiting for sockets, then the main bottleneck may be in the network or with the other machines that the application communicates.


https://docs.oracle.com/javase/10/troubleshoot/troubleshoot-performance-issues-using-jfr.htm

http://java-performance.info/oracle-java-mission-control-overview/#more-921

Blog Archive

Disclaimer

Qux