Sunday, December 13, 2020

JVM Crashes

Case Study - I gonna write a true story that happened on a company which I work for.

I got a task: Crash Hunting

Me: Who Crash?

QA: The system.

Me: What does it mean?

QA: The application stop working.

QA: before several changes, there wasn't any crash. after the changes, the system crash.

Me: OK, let me check.

Other developer: we look at the log files, we didn't find anything.

Me: The JVM crashed.


With that say, we need to make a research to understand 3 W's: Why there was a crash; Where the crash occurred; What causing the crash.

My first thought was: there are several reasons Why the JVM crashed, so we need to classify it.
In order to classify the reason we need an information. A log files is a pretty good place to get an information. 

But, as the other developer said: "we look at the log files, we didn't find anything".
I was wondering, what are the meaning of those log files? this is the application log files (The business logic log files).

If the JVM was crashed => application has crashed => there is no active process that can write to those log files. 

My next thought was, we need to look for the JVM log file in order to classify the crash, over there we will see a snapshot of the state of the machine and the JVM process at the time of the crash.
As stated at Oracle troubleshooting guide,
When a fatal error occurs, an error log is created with information and the state obtained at the time of the fatal error.
In order for this file to be created we need to configure when the JVM crash log will be created. we can configure it as part of the VM Options: 

-XX:ErrorFile=/var/log/java/java_error%p.log

We add it, reproduce the crash and the file created.
When we opened the file we noticed the following:


#
# A fatal error has been detected by the Java Runtime Environment:
#
#  Internal Error (sharedRuntime.cpp:834), pid=75034, tid=140148337530624
#  fatal error: exception happened outside interpreter, nmethods and vtable stubs at pc 0x00007f791eb2a80f
#
# JRE version: Java(TM) SE Runtime Environment (8.0_45-b14) (build 1.8.0_45-b14)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.45-b02 mixed mode linux-amd64 compressed oops)
# Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
#

---------------  T H R E A D  ---------------

Current thread (0x00007f7728029800):  JavaThread "nioEventLoopGroup-2-10" [_thread_in_Java, id=77330, stack(0x00007f76d3cfd000,0x00007f76d3dfe000)]

Stack: [0x00007f76d3cfd000,0x00007f76d3dfe000],  sp=0x00007f76d3dfa4d0,  free space=1013k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
V  [libjvm.so+0xaac99a]  VMError::report_and_die()+0x2ba
V  [libjvm.so+0x4f2de9]  report_fatal(char const*, int, char const*)+0x59
V  [libjvm.so+0x9ab5ba]  SharedRuntime::continuation_for_implicit_exception(JavaThread*, unsigned char*, SharedRuntime::ImplicitExceptionKind)+0x33a
V  [libjvm.so+0x914f1a]  JVM_handle_linux_signal+0x48a
V  [libjvm.so+0x90b493]  signalHandler(int, siginfo*, void*)+0x43
C  [libpthread.so.0+0xf5e0]
J 15905 C2 com.sun.crypto.provider.GCTR.update([BII[BI)I (158 bytes) @ 0x00007f79216aefea [0x00007f79216aeca0+0x34a]


At this file we can see the cpp stack trace which cause the JVM to throw an exception and crash.
It’s a bug that was reported on the JDK – they solve it on the next versions. The suggestion is to upgrade to the latest 8 version. 



To find a bug in Java it's like winning the lottery, it can happen but with very low probability




Saturday, April 11, 2020

Java 14 - New Features - Part 1


JDK 14 was released on March 2020.

With new programming languages and frameworks that pop up like mushrooms after the rain we can see a movement moving towards writing a code will be less tiring and less verbose with a lot more meanings. we can see from COBOL language that first appeared in 1959 that is verbose, uses over 300 reserved words and have statements that is English-like syntax where we heading to. 

Some can say that Java is too verbose and tedious, let's take a simple class for example - Pet class, so you have the name of the class and now you need to implement it, so you may need constructor, equals(), hashcode(), accessors, toString(), etc. So i know that you have an IDE that can generate it for you.


public class Pet {
    private String name;
    private Person owner;

    public Pet(String name, Person owner) {
        this.name = name;
        this.owner = owner;
    }

    @Override    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Pet pet = (Pet) o;
        return Objects.equals(name, pet.name) &&
                Objects.equals(owner, pet.owner);
    }

    @Override    public int hashCode() {
        return Objects.hash(name, owner);
    }

    @Override    public String toString() {
        return "Pet{" +
                "name='" + name + '\'' +
                ", owner=" + owner +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Person getOwner() {
        return owner;
    }

    public void setOwner(Person owner) {
        this.owner = owner;
    }
}


In recent years, JAVA architects and developers have taken steps to make the code less "ceremony", less tedious, less tiring and easier to code.

In this article i will talk about several new features that took place in Java 14.


Text Blocks (Second Preview)


This is a preview language feature in JDK 14.

Imagine you need to write an SQL query, you go to your database design tool, let's say workbench and think, implement and test your query, after doing so you need to copy & past it to your java project (if your application use plain text SQL), And this is where the problem begins. You are not sure about the indentation, you struggle a lot with the quotation marks in each line - it's so annoying.

This is where Text Blocks come to the rescue. Text Blocks introduced in early 2019 and now we can find it in JDK 14 as second Preview with two new escape sequence, \s and \ .
The goals is to simplify, make it easy to express strings that span in several lines and enhance the readability of strings.

Before Text Blocks

"INSERT INTO users " +
"  ( " +
"     first_name " +
"     ,last_name " +
"     ,email " +
"  ) " +
"VALUES " +
"  (  " +
"     :first_name " +
"     ,:last_name " +
"     ,:email " +
"  )  ";

With Text Blocks

"""        
INSERT INTO 
   users 
   ( 
      first_name 
      ,last_name 
      ,email 
   ) 
VALUES 
   (  
      :first_name 
      ,:last_name 
      ,:email 
   )  
""";

surround the string with 3 quotation marks.

\s - this escape can be used for single space and this  escape can be used for newline that its usable for readable texts.

It's not just very helpful for SQL queries string, also helpful for HTML, XML, JSON and every string that usually requires significant editing with escapes and concatenation.

Regarding the compile-time processing - the content is processed by the java compiler in three steps: line termination; incidental white space surrounding the content, is removed; Escape sequences in the content are interpreted.

At run-time, a text block is evaluated to an instance of String, just like a string literal.



Pattern Matching for instanceof (Preview)


This is a preview language feature in JDK 14.

The goal is to extract more from pattern matching for the instanceof operator.

The logic of the following code is to testing if an expression has a certain type or structure, and then conditionally extracting components of its state for further processing.

if (obj instanceof Integer) {
    int num = ((Integer) obj).intValue();
    // use num
}


This part of code is commonly in use and it is tedious. Let's understand what we see here
  1. Test if obj a Integer.
  2. Casting obj to Integer.
  3. Declaration of new local variable - num.

Imagine you can do the 3 above in 1, now with Pattern Matching for instanceof, you can:

if (obj instanceof Integer num) {
    // use num here (num is binding to this block)
} else {
    // can't use num here.
 }

It gives the ability to use easier syntax to extract components of objects.



We are seeing efforts towards easier coding in Java, that trying to keep up with other languages.




Monday, December 9, 2019

Java 13 - Switch Expressions

JDK 13 was released on September, 2019. One of the new feature is: Switch Expressions (Preview)

This is a preview language feature in JDK 13. It's a new feature of the Java SE Platform that is fully implemented and yet impermanent. This may become permanent in a future Java SE Platform.



Java 13 Switch Expression, Example:


java,switch,switch statement,java programming,java tutorial,java switch,switch expression,java switch expressions,java switch case,java switch statement,learn java,java 12 switch expression,java switch example,java13 switch expression,what are java switch expressions,switch in java,java (programming language),java programming tutorial,java tutorial for beginners,java 13 switch,switch statements,switch case java


Notice: You don't have to use breaks statement syntax,



You can just do,



yield - new keyword to return a value from switch expression



Another way,





In order to use preview feature you need to enable it, otherwise you will get the following error:



IntelliJ IDEA v2019.3 support  preview feature




Enable Preview feature - IntelliJ 


Open File => Project Structure. Under Project language level, choose: 13 (Preview) - Switch expressions, text blocks.
























Monday, November 11, 2019

Startup vs Corporate - 10 gold questions

I personally never worked for big tech corporations, but i heard the stories.

Almost every junior developer who finished studies or about to and have the passion to work as a developer want to be at the forefront of innovation. startups are in the front of the media and news geek sites, telling the success stories. But you should always understand where you are going to and what is better for you.

10 gold questions you need to ask yourself, will help you decide what's better for you.
You may find yourself giving different answers at different times in your life.

[writer's advice: read it alone (others may change your answers) and be real with yourself]


1. Do you cherish Life-Work Balance?

For some, it's important to have balance between work and life (they "have life"),  8-to-16 or 10-to-18 it's legitimate and nothing wrong with that. They want to be able to go to the gym or spend time with their friends and family on daily basis or just go to the beach during summer.


2. Can you handle frequent changes?

Startup have changes on daily basis.

Tasks - you can jump between 4 tasks in one day without finish one of them in order to help with some "really important" questions or problems in production.

Projects - constantly changed. You are asked to start reading a requirements (if there are at all) or starting a new project in your Intellij with perfect banner that you just finished design, before you know it the people sitting behind you are already talking about the next project.

Atmosphere - You can find yourself sitting next to 4 different people in one year - because people come and go or you just changed your sits.

Teams - A new fresh developer who start to work for the company become a team leader in one year. New team with a new title will suddenly pop up with new team members.

All the above could change in a big company usually in a larger time span.


3. Do you prefer creation or maintenance? 

To some, creation and building something gives them a lot of satisfaction when it's done and it feels great - gives a lot of motivation to continue and create, adding passion to the work, makes their work meaningful.

For others, maintenance tasks keep coming and coming and never ends. Like Sisyphus that was derived to rolling a huge rock up a mountain. Almost before Sisyphus reached the top, the rock rolls back down and requires Sisyphus to repeat the action. Sisyphus was forever doomed to a futile effort and endless despair - Take out the motivation and make the work meaningless and without purpose.

Many times in large companies there are a lot of legacy code that restrict developers and force them to limited their ideas and capabilities.
Maintenance of existing code can be stable and relaxing for some. But for others it can be really boring after few weeks.

In startups usually every thing needs to be build from scratch and there are a lot of ideas every day.


4. Do you love money, now?

Startups have no fats, they know exactly where their funds are headed. Usually they pay less, but compensate with stock options. What are the odds that your startup will succeed? do you know how much your stock options worth? probably not.


5. Do you need guidance and tools?

Startup have no order guidance to train new employee. You can find yourself in your first day, not sure exactly what to so, you do not have close personal supervision and guidance to assimilate you the best way to the company.You need to invest a lot of energy to get the information you need to get started, this can be manifested even in installing your work-space.

Startup have no tools to give you to become a good manager in the future if you would like to become one.

Big tech corporations usually have neat plan to train new employees. Also have money to invest in you for professional courses and to develop you to become better manager and better developer.


6. Do you need rapid results?

At big tech companies you can wait more than a year for your project or feature go into production environment. Unlike startup which you can see your feature works in the real world much faster, helps you to learn and measure your work.


7. Is impact important to you?

In small workplaces when everything is new, everybody knows everybody.
You know all the managers and employees of the company, sometimes they sit at a table next to you. You can approach and talk to them, you can influence their opinions, decisions and even offer your own new ideas. You can impact on the company's path.

At big tech companies, usually other departments and managers are in other rooms behind doors - creating a state of distance and inaccessibility, hard to influence one another.


8. Do you need a close manager?

Startup usually has bad managements or no managements at all usually they are fresh managers, probably this is the first time they get to manage. They will make a lot of mistakes, like knowledge transfer in a vague way, lack of tasks information, broke promises and so.
They can cause unintentional conflict between people and staff. You are less treated. there is a possibility which a kid will be your manager - he will not understand if you need to go early to help your wife / husband with the kids.


9. Do work of others are right for you?

Big tech companies have a dedicated person for each position, this is not the case for startups. If you are a software engineer, you can find yourself do a DevOps work or even a QA work.


10. Are you a team member?

Are you better in teams or you prefer to work independently?
Some, prefer to work as part of a team. Asking questions, getting answers, testing problems together, sharing information, brainstorming, everyone getting a different piece in the puzzle.
Some, love to work independently. They don't like  that someone interfere with their ideas and work, they can become very nervous if someone touching their code or even saw it.


What's better for you?




JVM Crashes

Case Study - I gonna write a true story that happened on a company which I work for. I got a task: Crash Hunting Me: Who Crash? QA: Th...