Why does NumberFormat.format throw a NullPointerException?

I just found a very strange NullPointerException . Firstly, I create such a NumberFormat (note that Locale will be Germany by default, I don't know if this helps):

 NumberFormat angleFormat = NumberFormat.getNumberInstance(Locale.UK); angleFormat.setMaximumFractionDigits(5); angleFormat.setMinimumFractionDigits(0); 

Then I tried to format double with it. This is done using a new thread created by Lambda, and angleFormat declared by the method containing Lambda. The code in which Exception is thrown is as follows:

 con.println("D" + moveId + (state.isEnemyInSightOf(e) ? "+" : "-") + angleFormat.format(e.getAngle()) // line 123 - error is here + (state.isMissileInSightOf(e) ? "+" : "-") + angleFormat.format(e.getSight()) + (e.getLastShot() >= 10 || e.getLastShot() <= -1 ? "+" : "-") + angleFormat.format(e.getLives())); 

e.getAngle() returns a double , so it cannot return null. However, I get this exception:

 Exception in thread "Thread-1" java.lang.NullPointerException at java.text.DecimalFormat.fastDoubleFormat(Unknown Source) at java.text.DecimalFormat.fastFormat(Unknown Source) at java.text.NumberFormat.format(Unknown Source) at server.game.Simulator.lambda$0(Simulator.java:123) at server.game.Simulator$$Lambda$3/23162747.run(Unknown Source) at java.lang.Thread.run(Unknown Source) 

I am sure that e not null due to Exception stacktrace, it will a) be thrown one line earlier and b) not on java.text.DecimalFormat.fastDoubleFormat

Why is there a NullPointerException beeing throw sometimes , and sometimes it works without problems? And what does it mean? The error seems to be reproducible, but not very often.

+5
source share
2 answers

From comments: I create threads in a loop, each of which is different from e , but the same NumberFormat

This is apparently the source of the intermittent problems your code is experiencing. According to NumberFormat documentation , the class is not thread safe, so concurrent access must be synchronized from the outside:

Number formats are usually not synchronized. It is recommended that you create separate format instances for each stream. If several threads access the format at the same time, it must be synchronized from the outside.

+4
source

From JavaDoc to DecimalFormat

Synchronization

Decimal formats are usually not synchronized. It is recommended that you create separate format instances for each stream. If several threads access the format at the same time, it must be synchronized from the outside.

By the way, what version of Java is this? I do not see the DecimalFormat.fastFormat() method in the docs for Java 6 or 7.

+1
source

Source: https://habr.com/ru/post/1205302/


All Articles