NPE while autoboxing in Java - java

I have the following piece of code:
map = db_.treeMapCreate(validMapName_)
.keySerializer(Serializer.LONG)
.valueSerializer(Serializer.LONG)
.make(); //mapDB
protected void onTaskCompletion(TaskInfo task)
{
long startBlk = task.blkId;
long count = task.count;
for (int i=0; i < count; ++i)
{
long blk = startBlk + i;
Long oldVal = map.get(blk); //NPE here
...
...
}
}
How is it possible to get an NPE while autoboxing? I can understand getting an NPE on unboxing i.e. if I had:
long oldVal = map.get(blk)
then that can throw an NPE.
Edit: Map isn't null. To be more specific, inside the BTreeMap code of mapDB, this line gets executed:
if(key==null) throw new NullPointerException();
In case someone wants to take a look: BtreeMap of mapDB
Line: 1024
Partial stacktrace:
java.lang.NullPointerException
at org.mapdb.BTreeMap.get(BTreeMap.java:1024)
at org.mapdb.BTreeMap.get(BTreeMap.java:1013)
at com.service.onTaskCompletion(TaskHandler.java:312)
I'm unable to reproduce it so I cannot give a minimal, verifiable example.
I have tried to run it so that I perform a get() for a key that doesn't exist, and it DOESN'T give an NPE.

I think the problem is that you are looking at the wrong version of the BTreeMap code. If you go back to the previous commit of this class, line 1024 is not:
if(key==null) throw new NullPointerException();
but:
while(!A.isLeaf()) {...}
where A is set by:
BNode A = engine.get(current, nodeSerializer);
This makes much more sense. Basically, null is returned from engine.get. How that is possible is beyond my understanding, but this could very well be a bug of mapdb itself.

The NPE could be due to any of the following:
Map being null
Passing a null value to get method (not the case)
Passing a key to get() that does not exist in MapDB
I am more concerned about number 3 in here because, if you pass a key that does not exist then null is returned and trying to store null in Long oldVal cause the exception (I believing that something as follow happens):
Long l = new Long(null); //NPE
To find one whether it is #3 do the following
//if key don't exist MapDB returns null
if(map.get(blk) != null) { //not null } else { //yes null}
To find out if map is null obviously as pointed out by others, you do as follow
//invoking get on a null can cause NPE too, so another reason
if(map != null) { // not null } else { //yes null}
To support the fact that #3 could be causing the NPE, see this post with a similiar issue.
Looking into the docs for BTreeMap the get(Object) below
public V get(Object key)
Specified by:
get in interface Map<K,V>
Overrides:
get in class AbstractMap<K,V>
Looking at Map and AbstractMap the get(Object key) is specified as follow:
Returns the value to which the specified key is mapped, or null if
this map contains no mapping for the key.
get(Object) of Map<K,V> and AbstractMap<K,V> returns null if no mapping is found. It is also capable of throwing NullPointerException. So #3 could still be the case that there is no entry for the key passed to get method in map.

NPE is because map object is null and you are referring to get() method of null,thereby NPE.
Do check of map for null and you will find your solution.
if(map!=null){
long oldVal = map.get(blk);}
else {
System.out.println("Map is null");
}

I see only one possibility: The variable "map" is null.
Your code sample is incomplete, as you didn't show and where "map" is really initialized.

Related

JOOQ "IN" Query throws null pointer exception

When we try to fetch data with Null values
field(TABLE_NAME.COLUMN_NAME.in(null))
with IN clause
getting null pointer exception.
Maybe because of this.
#Override
public final Condition in(Collection<?> values) {
Field<?>[] fields = new Field[values.size()];
Iterator<?> it = values.iterator();
for (int i = 0; it.hasNext(); i++)
fields[i] = Tools.field(it.next(), this);
return in(fields);
}
In the database, we can provide null in IN clause.
There is an existing "won't fix" issue in jooq https://github.com/jOOQ/jOOQ/issues/3867
There are some alternatives:
check null before IN(Cant do in my case its a really big select statement)
So if I want to make this possible is there any other workaround.
PS: On a similar note "eq" works perfectly fine:
#Override
public final Condition equal(Field<T> field) {
return compare(EQUALS, nullSafe(field, getDataType()));
}
Edit: 'field(TABLE_NAME.COLUMN_NAME.in(null))' here null is a collection.
Your example code doesn't compile:
TABLE_NAME.COLUMN_NAME.in(null)
There are 5 overloads of this in() method in jOOQ 3.14, and as such, you cannot pass the null literal to the in() method. Your real client code may be using a local variable like this:
Collection<?> collection = null;
TABLE_NAME.COLUMN_NAME.in(collection)
There might be a case for when this should behave the same as passing an empty collection, such as Collections.emptyList(), but this isn't what you seem to want. You probably want to pass actual null values inside of that collection, which you can do:
TABLE_NAME.COLUMN_NAME.in(1, null, 2)
But why would you do it? SQL implements three valued logic, meaning that NULL values have no effect in IN predicates, while they have an unintuitive, hardly desired effect in NOT IN predicates (the entire predicate becomes NULL)

Why does using Optional instead of Objects.isNull or obj == null give me advantage?

I want to create method, which will use Optional functionality and return value NodeId.
This value I should extract from Asset object.
In some case I already use some functionality like ifPresent, filter, flatMap. But now I want clearly understand whether can I use Optional with simple methods like in example below, where I need just extract value from another Object
First example supposedly not very nice but however I try to Use Optional:
public Optional<NodeId> findParentNodeIdByAsset(Asset asset) {
Optional<Asset> tmpAsset = Optional.ofNullable(asset);
if(tmpAsset.isEmpty()) {
throw new NullPointerException();
}
return Optional.ofNullable(tmpAsset.get().getParents().iterator().next());
}
In second example I try to write same things but without Optional:
public NodeId tmpFindParentNodeIdByAsset(Asset asset) {
if(Objects.isNull(asset)) {
throw new NullPointerException();
}
return asset.getParents().iterator().next();
}
There's no point to check for null asset or empty tmpAsset if you're going to throw NullPointerException in these cases.
Just write:
public NodeId tmpFindParentNodeIdByAsset(Asset asset) {
return asset.getParents().iterator().next();
}
and the NullPointerException will be thrown if you try to de-reference a null reference.
Now, using an Optional becomes useful if you don't want to throw NullPointerException or if asset is not the only reference that may be null.
For example, suppose that asset.getParents() can also be null, and in case either asset or asset.getParents() are null, you want to return some default value, or an empty Optional.
You can chain multiple map() calls to transform each potentially null reference to the next potentially null reference, and end with either an Optional (as in the example below), a default value or an exception.
public Optional<NodeId> findParentNodeIdByAsset(Asset asset) {
return Optional.ofNullable(asset)
.map(asset -> asset.getParents())
.map(parents -> parents.iterator().next());
}
In addition, it might be safer to check that parents is not empty before trying to obtain the first element of its Iterator.
You aren't exactly using Optional correctly in your first method, it doesn't make much sense to throw a NullPointerException in the method where you're returning Optional. See Eran's answer for proper use.
If you, however, do want to throw a NullPointerException when the input is null, then would use this instead:
public NodeId tmpFindParentNodeIdByAsset(Asset asset) {
Objects.requireNonNull(asset, "asset");
return asset.getParents().iterator().next();
}
By using Optional you ensure the caller being aware of the returned value might be null.
Using Optional makes the code more fluent and improves its readability.
In your case i would indeed use a Optional. For example:
public NodeId tmpFindParentNodeIdByAsset(Asset asset) {
return Optional.ofNullable(asset)
.map(asset -> asset.getParents().iterator().next())
.orElseThrow(UnsupportedOperationException::new)
}
Otherwise if you'd like to return the optional, just remove the orElseThrow(). For each method of getParents(), iterator() or next(), which could possibly return null, you should create a map chain not to fall into a NPE. For example:
public Optional<NodeId> tmpFindParentNodeIdByAsset(Asset asset) {
return Optional.ofNullable(asset)
.map(asset -> asset.getParents())
.map(parents -> parents.iterator().next());
}

Checking if an object is null before converting to String

I have code that is throwing a null pointer exception.
Here is my code:
StringBuilder strName = new StringBuilder(100);
strName.append(someClassObject.getFirstName().getContent().get(0));
strName.append(" ");
strName.append(someClassObject.getLastName().getContent().get(0));
name = strName.toString();
It is throwing a null pointer exception when trying to retrieve the last name at someClassObject.getLastName().getContent().get(0).
My question is, how to proceed with best practice in catching the null pointer.
What I was thinking something similar to this:
String lastName = (String) someClassObject.getLastName().getContent().get(0);
if(lastName == null) {
lastName = "";
LOGGER.warn("Last name is null");
}
strName.append(lastName);
Which I am hesitant since I have to convert the lastName object to a String and then create logic to check if it is null or not.
Or
try {
strName.append(someClassObject.getLastName().getContent().get(0));
} catch(NullPointerException e) {
LOGGER.warn("Last name of the conusmer is null");
}
The exception only occurs when you call a method withing an already null object (you can debug to see which object is the root null).
In case your null is the someClassObject.getLastName()
You could check nullity in java with this oneliner:
String lastName = (someClassObject.getLastName() == null) ? "" : someClassObject.getLastName().getContent().get(0);
All the overloads of StringBuilder.append() are null safe. They append the text null if the input is null. Hence, you must be getting the NPE from any one of the methods in the expression someClassObject.getLastName().getContent().get(0).
If these methods are not null safe, then it is better to check for null before chaining the next method than catching NPE. This way you might have to write some boilerplate code, but execution time will be cheaper. Exceptions are costly, even if they are handled.
The other option is, if possible change the methods getLastName(), getContent(), and get(), to make them null safe - return empty value instead of throwing NPE. In this case you have to think how the other users of these methods will react if you make this change.
You can use Java 8 Optional to check if object is not null at each level of someClassObject
, as follows:
StringBuilder strName = new StringBuilder(100);
Optional<List<String>> option = Optional.of(someClassObject)
.map(SomeClassObject::getLastName).map(LastName::getContent);
if (option.isPresent()) {
strName.append(option.get().get(0));
}
I would recommend to use the ifPresent option instead, removing the need for your if statement.
Something like:
option.ifPresent(e -> strName.append(option.get().get(0)))

Multiple OR conditions in if statements

I have created a method that uses an iterator that iterates through a map and for each pair it evaluates a statement with many OR conditions. If the condition is true, it adds the object of the pair (a Notification object) in a list (anomalies). However, at compilation time, the compiler gives a NullPointerException exception at this method. Based on my investigation, it seems that there is a problem in the if statement, but I can't see why. Can anyone give me an help in this? Thanks!
public List<Notification> getAnomalies(NotificationSearchCriteria notificationSearchCriteria) {
Map<String,Notification> messageList = new HashMap<String,Notification>();
List<Notification> anomalies = new ArrayList<Notification>();
Iterator iterator = messageList.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry pairs = (Map.Entry)iterator.next();
Notification message = (Notification) pairs.getValue();
if(message.getDescription().equals(notificationSearchCriteria.getDescription())||message.getSubjectName().equals(notificationSearchCriteria.getSubjectName())||message.getNotificationSubject().toString().equals(notificationSearchCriteria.getNotificationSubject().toString())||message.getNotificationType().toString().equals(notificationSearchCriteria.getNotificationType().toString())){
anomalies.add(message);
}
}
}
return anomalies;
}
This is most likely caused by one of the methods on message returning null. For example, if message.getDescription() returns null, then message.getDescription().equals(<something>) will throw a NullPointerException, since you can't call additional methods on a null object.
There are several ways to fix this. First off, I recommend inspecting your objects to see which can return a null value and add the appropriate handling code.
More generally, I always recommend calling equals on the variable you know not to be null to avoid these problems. For example
if ("accept".equals(command)) {
// do something
}
is generally better than
if (command.equals("accept")) {
// do something
}
because the second might through an NPE, while the first never will.
I would refactor the message-matching code into the NotificationSearchCriteria class. The if would end up being "if (notificationSearchCriteria.matches(message))". From the names, I am guessing that is NotificationSearchCriteria's only usage; in that sense, it would not increase coupling.
The check-for-null would be performed during NotificationSearchCriteria construction; which would ensure that all fields were non-null. In the matching code, within that class, things would look like:
boolean matches(Notification message) {
if (description.equals(message.getDescription()) || // LHS guaranteed non-null
foo.equals(message.getFoo()) ||
bar.equals(message.getBar()) || // ...
) { return true; }
}
The best way to code is to do null check.
Ideally I would have code like this :
while (iterator.hasNext()) {
Map.Entry pairs = (Map.Entry)iterator.next();
Notification message = (Notification) pairs.getValue();
if(null!=message && null!=message.getDescription() &&
null!=notificationSearchCriteria.getDescription() )
{
//Do your comparioson
}else{
//Handle the NullPointerException error the way you want
}
}

java.lang.NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I do a condition with a value when it is null and when it is not null.
The time where this value is null I got the java.lang.NullPointerException.
How could I deal with this in order to dismiss this exception?
I need the condition when the value is null and when it is not.
You get a NullPointerException when you try to call a method using a variable that is null. Simple example:
String s = null;
int len = s.length(); // NullPointerException because s is null
So you should check if the variable is null before calling any method on it, for example:
int len;
if (s == null) {
len = 0;
}
else {
len = s.length(); // Safe, s is never null when you get here
}
Note that a NullPointerException is usually easy to solve. Carefully look at the stack trace of the exception; it tells you exactly in which line of your code the exception happens. Check what could be null in that line of code, and check if you're calling a method on something that might be null. Add a check (or prevent that the relevant thing can ever be null in another way).
Simply do a proper check for the value being null. A conditional such as
if (value == null)
will never raise a NullRefePointerException. It's only if you try accessing whatever a null reference points to that you get the exception. So calling methods or accessing other instance members of the object is out of the question.
Use an if to check for the variable not being null and then use an else code block for when it is null.
if (variable != null)
{
// Code when object is not null
}
else
{
// Code when object is null
}
The null pointer is only thrown when you try and use the null value.
For example,
variable.method();
But you should always avoid a situation where a null pointer could occur.
As stated by other posters, if you do not expect the s reference to be null here then fix the bug that causes the reference to be null in the first place. However, if it is valid that the reference could be null, you can also do the following using the ternary operator (Java 5 on)
int len = (s == null) ? 0 : s.length;
Note: the brackets are optional, but they make it a bit more readable in my opinion.
It is a really confusing question, but:
boolean isNull = true;
if (value != null) {
isNull = false;
}

Categories