Monthly Archives: August 2018

Java Memory Management

One topic that I have always been curious, is java memory management. How JVM allocates the memory to different objects and frees up the memory when needed? In this post, I will talk about Java Heap Memory and Stack Memory. Heap and Stack are the memories that JVM allocates as per the application requirements.

Java Heap Space

The most basic question that arises during this discussion, is how do you define both of these memories. So I will start with Java Heap Space. When JVM starts, it creates Java Heap Space and it is used by the application till the time the application is running. Java runtime uses heap space to allocate memory to objects and JRE classes.

The heap size is adjusted according to when the application runs. When the heap gets full, garbage collection takes place. During garbage collection, objects that are not being used, get cleaned, in-process making space for new objects.

Java Stack Memory

Stack memory is like a RAM, used by an executing thread for method-specific values or operations. Most of the values or operations in the stack are short-lived. It can also contain references to objects that reside in heap.

Whenever a method is invoked, a block is allocated in the stack for a method to hold local variables. The block gets cleared once the method finishes execution.

From these earlier definitions, it is clear that Stack memory is smaller in size compared to heap space.

Stack Memory and Heap Space

Differences between Heap space and Stack memory

  1. Heap memory is used by the entire application while the stack is used by execution thread only.
  2. When an object is created, it is stored in heap space, while the reference for that object is stored in stack memory.
  3. Since stack memory is thread-specific, it can’t be accessed by multiple threads or other threads than the one thread that created it. Heap space is global.
  4. Heap space is available till the time application is running, stack memory is short-lived.
  5. JVM can throw errors if both memories are full or the application doesn’t have either of memory remaining to continue running the application. StackOverfFowError if JVM is out of stack memory. If the application stops running provided there is no memory to store objects, it will throw OutOfMemoryError: Java Heap Space Error.

Conclusion

In this post, I discussed the differences between Java heap space and stack memory as part of Java memory management.

References

  1. Stack vs Heap
  2. Understanding memory management

 

HTTP Security Headers – XFrame Options and Content Security Policies

Have you ever traced an HTTP request in a browser or fiddler? You must have seen these HTTP security headers in the request or response header?

X-Frame-Options SAMEORIGIN

OR

Content-Security-Policy:frame-ancestors 'none'

Do you know what are these headers about? In this post, I will show why we use these headers. These security headers often come up when you are rendering an application within iframes.  Conclusively, these headers are important if you are loading applications with an iframe inside the main iframe.

Why are these headers required?

These headers help in avoiding clickjacking attacks. You can read more about clickjacking here. To defend against clickjacking, we implement frame-breaking using two methods.

   1. X-Frame-Options –

This header is used in response header to indicate whether or not a browser can be allowed to render a web page in a <frame> or <iframe>.

Possible values for this header:

  1. DENY – The recommended value for X-Frame-Options and it prevents any domain to frame the content.
  2. SAMEORIGIN – This allows only the current site to frame the content.
  3. ALLOW-FROM URI – This allows the specified URI to frame the content.

   2. Content-Security-Policy –

Similarly, X-Frame-Options is used by the browser to allow to render a page in a frame or iframe, the same way Content-Security-Policy header is used. Accordingly, some browsers support X-Frame-Options and some Content-Security-Policy. Nevertheless, one key feature between these two headers (X-Frame-Options and Content-Security-Policy) is that Content-Security-Policy can allow the listing of multiple domains to load the content from.

Possible values for this header are:

  • Content-Security-Policy: frame-ancestors ‘none’ – This prevents any domain to render the content.
  • Content-Security-Policy: frame-ancestors ‘self’ – This only allows the current site to frame the content.
  • Option of Content-Security-Policy: frame-ancestors ‘self’, ‘*.betterjavacode.com’, ‘https://www.mytest.com’ – This allows the current site, any subdomain of betterjavacode.com or the web page at www.mytest.com to load the page. Single quotes are important here.

Spring-Security

Likewise, Spring-security offers a feature to enable the X-Frame-Options and Content-Security-Policy directive.

http.headers().frameOptions().disable();

http.headers().frameOptions().sameOrigin();

Conclusion

In conclusion, I showed why and how to use HTTP security headers X-Frame-Options and Content-Security-Policy. Hence, if you enjoyed this post, subscribe to my blog here. You can find more details about X-Frame-Options and Content-Security-Policy headers on this page.

References

  1. Clickjacking cheat sheet – Clickjacking
  2. Clickjacking – Clickjacking-2

 

Where are we?

Hold on to it. This is going to be a rant about what I am thinking about ideas to post, but also an update about the web application Social KPI.

I am working on a few ideas that I would like to write about. But I am not sure. Lately I have been working on microservice architecture project and that had helped me to design Social KPI application. I would like to hear from my followers if they are interested in any particular topic that I should cover. Currently most of the interests are around Spring boot and microservices. That is too specific, but also equally too big of a topic to cover. I have covered bits and pieces of Spring boot.

Here are a few ideas that I have in mind that I would like to post about:

  1. Spring boot in android applications.
  2. How to use Spring boot and deploy in cloud infrastructure
  3. What is chaos engineering?
  4. Android application and details
  5. Microservices and Service-to-Service authentication
  6. Udemy course for Spring boot and microservices.

Please leave a comment if you want me to cover something new.

Where are we with Social KPI application?

So last, I posted about this application was back in May Twitter Client. After that there had been some progress as I did figure out how to use social login for authentication purposes, but it had not been added in the application. I will be reviving the work on this project and will try to contribute daily for 30-60 minutes. As part of my planning process, I will add here the tasks that need to be finished:

  1. Add Social login UI for the application
  2. Add UI Pages for displaying Social KPI reports and user navigation
  3. Connecting front-end to back-end REST APIs through clients.
  4. Use of Jasper reports for graphical reports.

These are the 4 big stories I am planning to finish by the end of October. Once I have all the code completed, I will launch the application through Heroku.

 

 

 

How to use Streams API

Java 8 added a new feature called Streams. Streams represent a sequence of objects from a source. In this post, I show how to use Streams API.

Previously, using collections API, we would have a collection of objects and then a developer would process this collection to manipulate further to query. With Streams feature, the developer will not have to do any processing operation over the collection of objects.

Streams

Firstly, streams provide a set of elements in a sequential manner. It provides a number of APIs for aggregate operation. Streams take Arrays, Collections, or I/O sources as an input.

How Streams Work

A stream represents a sequence of elements. Stream operations are either intermediate or terminal. Intermediate operations return streams to process further while terminal operations return either void or non-stream results.

List<String> myList =
    Arrays.asList("test1", "sameresult", "netresult", "grossprofit", "test2");

myList
    .stream()
    .filter(s -> s.startsWith("test"))
    .map(String::toUpperCase)
    .sorted()
    .forEach(System.out::println);

As shown above, filter, map, sorted are intermediate operations and forEach is a terminal operation. Javadocs provide the list of all operations on streams.

Most stream operations accept some kind of lambda expression parameter, a functional interface specifying the behavior of the operation.

Instead of using collections, you can also use Stream.Of() operation to create a stream from a bunch of objects.

Intermediate operations have a characteristic of laziness. To look at this, let’s check the example below:

Stream.of("n1", "n2", "n3", "n4", "n5")
    .filter(s -> {
        System.out.println("filter: " + s);
        return true;
    });

It will not print anything on the console. Intermediate operations will work only when there are terminal operations.

Once you call a terminal operation on streams, streams can not be reused.

Operations on Streams

Streams API offers aggregate operations that offer flexibility in using streams. I will show an example here about how to use streams

List<String> listOfStrings = new ArrayList<>();
listOfStrings.add("one");
listOfStrings.add("two");
listOfStrings.add("three");
listOfStrings.add("");
listOfStrings.add("four");

List<String> listOfNotEmptyStrings = listOfStrings.streams().filter(str -> !str.isEmpty()).collect(Collectors.toList());

In the example shown above, I have list of strings that I filter to get only a list containing non-empty strings.

Streams also offer forEach operation which can be used to iterate over the elements of the stream.

Collect is a terminal operation that can transform the elements of a stream into a different kind of result. Example – a List, Map, or a Set.

Map is an operation that allows us to transform objects of a stream into another type of object.

Reduce operation combines all elements of the stream into a single result.

ParallelStreams

Streams also offer something called ParallelStreams . Basically all operations performed over ParallelStreams ,are performed in parallel. Depending on your usage, use these streams carefully as they can cause concurrency issues.

Example – listOfStrings.parallelStream()

ParallelStreams can be used to improve the runtime performance on a large set of input elements.

Conclusion

In this post, I showed how to use Streams API in Java 8. Streams make it handy in many cases where we have a list of objects and we are processing these objects. If you enjoyed this post, subscribe to my blog here.