Java 7 features

J

Joshua Cranmer

(Yes, I realize that I am about to potentially unleash strong opinions.)

Recently, I was looking around online and came across this (partial) list
of new Java 7 features. What I want to know is what support/disapproval
people have of these options:

@ Closures
@ Strings in switch statements
@ Operator overloading for BigDecimal
@ Language-level XML support
@ Reified generics
@ Superpackages
@ Removing checked exceptions

Personally, I am in support of items 2 and 5; indifferent on 3, 4, and 6;
and against items 1 and 7.
 
S

Stefan Ram

Joshua Cranmer said:
@ Closures

A lot depends on the details of how this is done.
@ Strings in switch statements

Does not really matter to me, because I rarely
come across this.
@ Operator overloading for BigDecimal

If such an extension of the syntax would be tied to a specific
class (BigDecimal), it would be ugly.

As a general language feature, it's nice to have.
@ Language-level XML support

Should not be tied to fixed classes or an implementation
or even XML. Whenever source code encounters

x = <...>

a plugable handler should be called by the compiler to convert
the "<...>" part to a Java expression. The XML-handler by Sun
would be the default.

By this, S-expressions could be embedded as well.
@ Reified generics

Now that I've written all those FAQs explaining type erasure
they want to devaluate them!!
@ Superpackages

I have not yet fully grasped this concept.
@ Removing checked exceptions

Indeed, a major part of my library code just consist
of wrapping them in RuntimeExceptions. So this would
help.

What is missing?

I want Derby (the SQL database that is part of the JDK) to
become a part of the JRE. It would help to have a default
database without any further installation.

Simplifications for common cases:

CLASS x = new CLASS( ... )

It should be allowed to abbreviate this to something
shorter like:

CLASS x = new( ... )

Similar

INTERFACE x = new( ... )

What is this? I imagine that every interface might specify
a default implemenation. For example, for java.util.List,
this would be java.util.ArrayList. Then

java.util.List<String> x = new();

would mean the same as

java.util.List<String> x = new java.util.ArrayList<String>();

Also, consider:

if( x instanceof A ){ A a =( A )x; ... }
else if( x instanceof B ){ B a =( B )x; ... }
else if( x instanceof C ){ C a =( C )x; ... }

Forget for a moment that »instanceof« is a code smell.
Sometimes it's needed.

This could be written as

if( x instanceof A ){ ... }
else if( x instanceof B ){ ... }
else if( x instanceof C ){ ... }

if the compiler would keep track of the fact that x
in the first block is now known to have the type of A,
so that no further cast is required. (At least for
an identifier »x« with »final« this should hold.)
 
T

Tom Hawtin

Joshua said:
@ Closures

But we already have (minimal) closures. I think it would be much more
sensible to improve what we already have, rather than to duplicate. It's
probably unlikely to get in before Java 1.8 anyway.
@ Strings in switch statements

Not too fussed. It'll make switches on strings clearer, but perhaps will
encourage poor code.
@ Operator overloading for BigDecimal

BigDecimal and BigInteger are hideous to use at the moment. The overflow
semantics of primitive integers are not something that I think should be
in a high level language. I'd prefer general operator overloading of
sensible operators.
@ Language-level XML support

Evil and unnecessary. A lot like much of XML.
@ Reified generics

This could have made sense in 1.5. But I don't think this is really on
given the situation we have got ourselves into.
@ Superpackages

Good. I guess packages provide what is necessary from superpackages, but
we tend to write libraries and applications in more than one package.
@ Removing checked exceptions

I like static type checking.

Tom Hawtin
 
G

Guest

Joshua said:
(Yes, I realize that I am about to potentially unleash strong opinions.)

Recently, I was looking around online and came across this (partial) list
of new Java 7 features. What I want to know is what support/disapproval
people have of these options:

@ Closures
@ Strings in switch statements
@ Operator overloading for BigDecimal
@ Language-level XML support
@ Reified generics
@ Superpackages
@ Removing checked exceptions

Personally, I am in support of items 2 and 5; indifferent on 3, 4, and 6;
and against items 1 and 7.

for: 2, 3, 5
against: 1, 4, 7
neutral: 6

Arne
 
T

Twisted

(Yes, I realize that I am about to potentially unleash strong opinions.)

Recently, I was looking around online and came across this (partial) list
of new Java 7 features. What I want to know is what support/disapproval
people have of these options:

@ Closures

Depends. Syntactic sugar to make anonymous inner classes easier to
use: for. Dropping the "final" requirement on referenced local
variables: for. A simple anonymous lambda function ability that
results in first class objects with the ability to compute and return
values: for (this could be had in the form of an appropriate generic
interface and easier anonymous inner classes). Anything really ugly or
hairy: against. Otherwise neutral.
@ Strings in switch statements

I'd really like to see either switch statements deprecated, switch
statements made enum-only, or switch statements made into syntactic
sugar for ANY lengthy if-elseif-elseif-elseif-else chains.
@ Operator overloading for BigDecimal

Either none or for any custom class, please, or better yet, require
declaring the operators in an interface, and then binary operators
work when both argument types implement a common interface specifying
that operator, and are type errors otherwise.
@ Language-level XML support

Bleh. Either skip it or put language-level metalanguage capabilities
in, where you get a construct to declare parsers that use a context-
free-grammar in bison format to define a translation from some syntax
to Java, and you can then use a construct like "import MyLanguage
{ code in my language }" which is translated into Java if the compiler
can resolve the MyLanguage parser definition (a new package level
thing to go with classes, interfaces, and enums). This simple thing
adds no new keywords (by overloading "import") and lets you use almost
anything in your language (except }, and it should treat Java comments
as comments). No doubt there'd be a bazillion XML parser definitions
out there before you could blink anyway.
@ Reified generics

That depends on how they work. Run-time availability of type parameter
info? If you can make it fly without being too ugly or baroque.
Numeric parameters? That might be nice for fixed-size-vector classes
and things of that nature.
@ Superpackages

Whatever that means. If it means treating package names as a proper
hierarchy, so that (as is already implied, but untrue)
com.mysite.mystuff.foo.Bar automatically sees com.mysite.mystuff.Quux
and you can tidily import Bar into Quux as "import foo.Bar" or
"import .foo.Bar" ... sure.
@ Removing checked exceptions

Are they out of their cotton-picking MINDS?!

P.S. a URL with more in depth explanations of what exactly is being
proposed would be handy about now.
 
H

Hendrik Maryns

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Joshua Cranmer schreef:
(Yes, I realize that I am about to potentially unleash strong opinions.)

Recently, I was looking around online and came across this (partial) list
of new Java 7 features. What I want to know is what support/disapproval
people have of these options:

@ Closures
@ Strings in switch statements
@ Operator overloading for BigDecimal
@ Language-level XML support
@ Reified generics
@ Superpackages
@ Removing checked exceptions

The only thing that I definitely support is the last one, but probably
in the unusual way: indeed, get rid of checked exceptions, by making
*all* exceptions checked.
For the skeptic: it can be done, see how Eiffel handles it.

Oh, and who the hell needs switch statements?

H.
- --
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGihdue+7xMGD3itQRAkToAJwKeYQOXChNjF8ReCbZPAmG2q7JDgCdHjjB
IvSmnQUS/PID5fx4pTvlIEc=
=gwOO
-----END PGP SIGNATURE-----
 
J

julien.robinson2

Small comment...

I'd really like to see either switch statements deprecated, switch
statements made enum-only, or switch statements made into syntactic
sugar for ANY lengthy if-elseif-elseif-elseif-else chains.

I used switch statements much more in C++ than now in Java. Mainly
because, whereas Java has introduced a discrepancy between == and
equals(), switch only applies to ==.

What I would suggest is a new switch, so that we have "switch" and
"switch-equals"

switch: runs through all cases comparing with the operator "==". May
accept null, and probably useless for strings.
"switch (x) {case y:..." should be exactly the same behavior as "if (x
== y)..."
(I *think* that's the one we have... just goes to show how much I use
it!)

switch-equals:
uses "equals()" to test each case. Requires passing an object (or uses
auto-boxing?).
It could not accept null pointers, even though I would favor:
"switch (x) {case y:" should be exactly the same behavior as
"y.equals(x)"
so that x may be null
If ever some y is null, throw NullPointerException of course. :)
and if x is null, of course it switches to default.

Problem is: what if there's y1 and y2 and both are equal? Simply
precise that only the first match will be acted upon.

This may be ugly, but I agree that:
* switch, as is it, is not very consistent with Java thinking, because
of the "equals" method
* because of this, it is not very much used (at least that's what
people around here are saying)
* making special cases for types is probably to be avoided (as much as
possible of course).

All this said with the ignorance of a non-expert programmer... :)
JR
 
R

Roedy Green

@ Closures
Not keen. I think this will needlessly make code hard to understand by
the general programmer.
@ Strings in switch statements
Not as big as deal as it once was now there are enums. The feature
will encourage inefficient code. I would like instead RANGES of ints
and enums that generate better code and code easier to maintain than
you would do manually. This is a relatively trivial extension,
requiring no JVM change. See
http://mindprod.com/projects/caserange.html for what I a would like.
@ Operator overloading for BigDecimal
fine. This can probably be done without a JVM change.
@ Language-level XML support
I detest XML. So oppose this on general principles. I want XML to
die. This will just encourage it. see
http://mindprod.com/jgloss/xml.html
for my reasons for wanting to stamp out XML. I have the same disgust
for XML I have for grossly overweight gluttons and people enjoy
deliberate waste. Perhaps if it is done in a representation
independent way, XML can quietly be replaced without anyone noticing.
@ Reified generics
I don't know what that means. Reify means to regard or treat (an
abstraction) as if it had concrete or material existence. Does this
mean tossing out type erasure? Generics are an embarrassment to the
language. I personally would like to start from scratch and see if
they can be made 10 time times simpler and wart-free.
@ Superpackages
Probably just paying attention to the dots in package names. For ant
bundling it would be nice to just have to specify one name to grab
everything related.
@ Removing checked exceptions
NO. That will just lead to sloppy code. Java is not PHP.
 
R

Roedy Green

Oh, and who the hell needs switch statements?

I use them all the time, nearly always with enums.

There are three ways of doing a computation. You can write a switch to
collect the 25 enums in three groups. This is much easier code that
calling a method in each enum. You can see the big picture. It is
easier to maintain and proofread.

See http://mindprod.com/projects/scid.html
for my proposal to have your cake and eat it too -- view code either
way.

The other place I use them is in writing finite state automata. One
nice feature of Java is if you leave out the default, it will warn you
if you have failed to mention one of the possibilities as a case
label.
 
T

timjowers

(Yes, I realize that I am about to potentially unleash strong opinions.)

Recently, I was looking around online and came across this (partial) list
of new Java 7 features. What I want to know is what support/disapproval
people have of these options:

@ Closures
@ Strings in switch statements
@ Operator overloading for BigDecimal
@ Language-level XML support
@ Reified generics
@ Superpackages
@ Removing checked exceptions

Personally, I am in support of items 2 and 5; indifferent on 3, 4, and 6;
and against items 1 and 7.
FWIW:
@ Closures
Don't care. Have no problem passing classes and referencing needed
methods.
@ Strings in switch statements
Don't care. I can type fairly fast. I kinda agree with the other posts
that an OO language should handle constructs in an OO way rather than
implementing special cases.
@ Operator overloading for BigDecimal
Yes. Lack of operator overloading is just irritating to anyone who
used this heavily elsewhere. Operator overloading makes for much more
readable code.
@ Language-level XML support
Don't care. Sounds like an unholy mess.
@ Reified generics
Also don't know what this is/Don't care. If my bugs are due to type
casting of array elements then I have bigger problems than the version
of my programming language.
@ Superpackages
Don't know. Would have liked for the CLASSPATH problem to never have
been created. It is the same as the lib/DLL hell and include path
problems of yesteryear. If Superpackages fixes that then yes. I
haven't studied but guess it is like Maven with net-based JAR linking.
@ Removing checked exceptions
No because it sounds like a pain to change code and coding style.

One thing I would like to see is very tight integration with Linux.
With Linux being Open Source then Sun could feasibly write a kernel
module and maybe speed up the JVM on Linux I would guess.

I also think some more focus needs to be made on cross-JVM versions
and cross-version compiles. Some 80% of the Java code base runs in
Java 1.4 from what I heard at a JUG presentation. I think the big
challenge for Java is to get people/companies to move forward.

I'm very glad Sun is continuing to innovate.
 
O

Oliver Wong

Stefan Ram said:
Also, consider:

if( x instanceof A ){ A a =( A )x; ... }
else if( x instanceof B ){ B a =( B )x; ... }
else if( x instanceof C ){ C a =( C )x; ... }

Forget for a moment that »instanceof« is a code smell.
Sometimes it's needed.

This could be written as

if( x instanceof A ){ ... }
else if( x instanceof B ){ ... }
else if( x instanceof C ){ ... }

if the compiler would keep track of the fact that x
in the first block is now known to have the type of A,
so that no further cast is required. (At least for
an identifier »x« with »final« this should hold.)

I don't think this change is doable while remaining backwards
compatible. If methods are called on x and those methods are overloaded
and overridden, for example, this change would change which methods
actually gets called at runtime.

- Oliver
 
O

Oliver Wong

I used switch statements much more in C++ than now in Java. Mainly
because, whereas Java has introduced a discrepancy between == and
equals(), switch only applies to ==.

What I would suggest is a new switch, so that we have "switch" and
"switch-equals"

switch: runs through all cases comparing with the operator "==". May
accept null, and probably useless for strings.
"switch (x) {case y:..." should be exactly the same behavior as "if (x
== y)..."
(I *think* that's the one we have... just goes to show how much I use
it!)

Yes, I think that's an accurate mental model of how the switch
statement works
switch-equals:
uses "equals()" to test each case. Requires passing an object (or uses
auto-boxing?).
It could not accept null pointers, even though I would favor:
"switch (x) {case y:" should be exactly the same behavior as
"y.equals(x)"
so that x may be null
If ever some y is null, throw NullPointerException of course. :)
and if x is null, of course it switches to default.

How about adding a new case statement for nulls, and leaving default
to their original semantics?

switchequals (x) {
case y:
doThis();
break;
case z:
doThat();
break;
null:
doSomethingElse();
break;
default:
giveUp();
break;
}

is syntatic sugar for:

if (null == x) {
doSomethingElse();
} else if (y.equals(x)) {
doThis();
} else if (z.equals(x)) {
doThat();
} else {
giveUp();
}

and

switchequals (x) {
case y:
doThis();
break;
case z:
doThat();
break;
default:
giveUp();
break;
}

is syntatic sugar for:

if (null == x) {
giveUp();
} else if (y.equals(x)) {
doThis();
} else if (z.equals(x)) {
doThat();
} else {
giveUp();
}

Note that the compiler was smart enough to do whatever was necessary to
avoid NullPointerException.

While we're at it, how about changing the switch statement so that
statements after a case-label MUST end in either "break;" or
"fallthrough;" (or "continue;", if you want to avoid creating a new
keyword). So the following would no longer be legal code:

switch(x) {
case 1: //fallthrough
case 2:
doSomething();
}

and instead would need to be written:

switch(x) {
case 1:
continue;
case 2:
doSomething;
break;
}
Problem is: what if there's y1 and y2 and both are equal? Simply
precise that only the first match will be acted upon.

Agreed, as I think this parallels how switch currently works.
This may be ugly, but I agree that:
* switch, as is it, is not very consistent with Java thinking, because
of the "equals" method

Note that switch statements refuse to work on anything except integers
(maybe longs?) and enums. Specifically, they don't work on objects, so the
"equals" method doesn't even come up as an issue yet.

- Oliver
 
O

Oliver Wong

Joshua Cranmer said:
(Yes, I realize that I am about to potentially unleash strong opinions.)

Recently, I was looking around online and came across this (partial)
list
of new Java 7 features. What I want to know is what support/disapproval
people have of these options:

@ Closures

I'm sort of dreading this change, because it means once Java 7's out,
I will no longer consider myself a competent Java programmer. On the other
hand, might be a good opportunity to finally learn what closures are all
about.
@ Strings in switch statements

Fine with me. Strings are already getting special VIP treatment in
Java as it is. Might be worth considering extending this to work with all
objects, as laid out in a post downthread about "switch-equals".
@ Operator overloading for BigDecimal

I thought "No Operator Overloading" was an argument for favoring Java
over C++. The purist in me is already annoyed with the + operator being
overloaded for Strings. This seems like a step in the wrong direction.
@ Language-level XML support
@ Reified generics
@ Superpackages

I'm ignorant and/or apathetic about the above.
@ Removing checked exceptions

I like checked exceptions. I'm part of the crowd that is willing to do
more typing in exchanged for less buggy programs.
Personally, I am in support of items 2 and 5; indifferent on 3, 4, and
6;
and against items 1 and 7.

Would have been nice if you had numbered the items. =P

- Oliver
 
S

Stefan Ram

Oliver Wong said:
If methods are called on x and those methods are overloaded
and overridden, for example, this change would change which methods
actually gets called at runtime.

I believe this only applies to hiding and overloading,
but not to overriding.

The language could be changed, so that - by specification -
all of this is left unchanged. The only modification would be:

If the part »...x...« in

if( x instanceof A ){ ... ...x... ... }

would have created an error message in Java 1.6 and if this
error message would not appear if »x« would be downcast to A,
then such a downcast will silently be assumed by the compiler
and the JVM and be implemented as a no-operation.
 
B

Bjorn Borud

[Roedy Green <[email protected]>]
|
| >@ Closures
| Not keen. I think this will needlessly make code hard to understand by
| the general programmer.

it is one of those things that are very fashionable now and fashions
are not necessarily dictated by what is actually a good idea. I have
seen some really unwieldly code written by people who have a raging
closure fetish -- using them everywhere and for everything. it may be
something you can get used to, but to me, the over-use just makes the
code hard to read and I can't really see the benefit -- other than
giving you the warm feeling of being buzzword compliant and
fashionable

sure, for some things closures are nice, but I only have use for them
occasionally. for the most part I think this is something people who
give lots of presentations at conferences really like and that it'll
eventually pass.

| >@ Language-level XML support
| I detest XML. So oppose this on general principles. I want XML to
| die. This will just encourage it. see
| http://mindprod.com/jgloss/xml.html

the theme appears to be "bloat". which I'd say is a valid reason to
dislike XML, but in many cases, I can live with a bit of bloat. there
are other issues that are far more troubling.

| for my reasons for wanting to stamp out XML. I have the same disgust
| for XML I have for grossly overweight gluttons and people enjoy
| deliberate waste. Perhaps if it is done in a representation
| independent way, XML can quietly be replaced without anyone
| noticing.

I am somewhat torn on this issue. back when I discovered SGML, I was
very enthusiastic. then when I actually read Goldfarb's book and made
an effort to understand SGML I realized that SGML was pretty pointless
(for a number of reasons which I will not bore you with, but if you
buy me enough beers and insist, I'll give you a long rant using really
colorful language).

then XML came around and I became a bit optimistic again. for a short
while. until I came to the conclusion that XML too was too
complicated for implementors to implement right, so you end up with
endless fiddling to get various implementations to actually talk to
one other.

then there were the various APIs and in the name of all things bright
and shiny, what were the people who made the DOM API thinking of!?
not to mention the people who decided it would be a good idea to turn
the thing into a standard!? someone should get their branding iron
out and make sure these people are flagged as dangerous. (this is as
kindly as I can put it)

of course, eventually there was JDOM -- which wasn't too bad all
things considered. still a bit fiddly, but a big step forward if you
do need to consume or produce XML.

as for the invention and use of "simple" or custom storage formats,
XML does remove some risk of people inventing really, *really* stupid
formats. I did work on a project some years ago where the collective
aversion to XML among the developers led to the decision that we'd
invent our own format -- so someone did. unfortunately he ended up
with something so terrible XML would have been heavenly compared to
it.

in that project I would actually have preferred XML as a way to
serialize structured data.

but then you have the XML-manicas that the Java world is so full of.
the sort of people who think that expressing things in XML rather than
Java code is better. as a friend of mine put it "oh, it was simple
enough to set up -- it just needed a few thousand lines of XML
configuration for the library to work".

the problem isn't really XML as much as it is the idiots it seems to
attract. from all directions.

-Bjørn
 
D

David Gourley

Oliver said:
I like checked exceptions. I'm part of the crowd that is willing to do
more typing in exchanged for less buggy programs.

And another vote for checked exceptions from me. It would be
interesting to know what types of programs the folks who don't like
typed exceptions write (client software vs prototype/modelling SW vs
software with high availability requirements etc.)

In my experience (from dealing in the past with C++ exceptions) this is
one of the things Java currently has right; you can use static analysis
tools to find misuse of checked exceptions (e.g. catch Exception) and
they greatly reduce the number of unexpected thread or process deaths
post deployment.

Dave
 
R

Roedy Green

Yes, I think that's an accurate mental model of how the switch
statement works

There are two JVM instructions to implement a switch. Java's N-way
branch. In the JVM there are two different ways of implementing a
switch, tableswitch and lookupswitch. The efficient tableSwitch is a
jump table used when the switch values are reasonably dense e.g.
numbered 0..N. The less efficient lookupSwitch is a binary search used
when the switch values all all over the map. It thus pays to keep your
switch values dense.
 
T

Twisted

switch: runs through all cases comparing with the operator "==". May
accept null, and probably useless for strings.

Interning the strings makes them viable here.
switch-equals:
uses "equals()" to test each case. Requires passing an object (or uses
auto-boxing?).
It could not accept null pointers, even though I would favor:
"switch (x) {case y:" should be exactly the same behavior as
"y.equals(x)"
so that x may be null
If ever some y is null, throw NullPointerException of course. :)
and if x is null, of course it switches to default.

Why not allow null anywhere? Null is unequal to anything but null,
unless some object's ".equals(null)" returns true for whatever reason.

My own recommendation is to make switch use == on primitive
types, .equals on reference types, and give a warning when floats or
doubles are compared.

switch (primitive) {
case x:
....1
case y:
....2
break;
default:
....3
}

is made syntactic sugar for

if (x == primitive) {
....1
....2
} else if (y == primitive) {
....2
} else {
....3
}

for instance.

With a nonprimitive, you get

switch (object) {
case x:
....1
break;
case null:
....2
break;
default:
....3
}

turning into
if (object == null) {
....2
} else if (object.equals(x)) {
....1
} else {
....3
}

say. (Always the test for == null occurring first, with either the
appropriate case block or the default block's code, followed by any
others.)

But I've also got a good suggestion for any operator overloading.

Firstly, binary operators between reference types are allowed if both
compile-time types have a common superclass or implement a common
interface that specifies the corresponding method (including if the
compile-time types of both sides are equal and this type specifies the
appropriate method).

Secondly, operators are then just syntactic sugar as follows:
-x -> x.negate()
x + y -> x.add(y)
x - y -> x.subtract(y)
x * y -> x.multiply(y)
x / y -> x.divide(y)
x += y -> x = x.add(y)
++x -> x = x.increment() (and add this method to BigFoo; it returns a
new instance, representing a value one higher)
x++ -> (t = x, x = x.increment(), t)
--x and x-- analogously with a decrement() method
x ~= y -> x.equals(y) (a whole new operator; if ~= allowed for
primitive types it behaves the same as == for these)
!x (maybe allow as shorthand for x == null)
(various bitwise operators should correspond to their BigInteger
methods)

A key thing is that the implied method is always invoked on the left-
hand operand, with the right-hand operand (if any) as method argument.
This means that operators would be polymorphic only on the first
argument. Using double-dispatching or other patterns when implementing
your add, subtract, multiply, etc. methods in your own class hierarchy
would be able to give the benefits of bilateral polymorphism, of
course.

It would be desirable to be able to set a thread-local MathContext for
BigDecimal calculations and scope it somehow. I'd suggest a more
general "environment" or "context" mechanism built on a (hopefully
speeded-up!) threadlocal mechanism, whereby you can use code like

do switch (threadlocal: expression) { ... stuff ... }

(which overloads, unambiguously, existing keywords) to:
* Save the current value of the thread local somewhere
* Change it to "expression".
* Stuff
* Restore the old value of the thread local

It would be syntactic sugar for:

Object t3dsfgr838 = someThreadLocal.get();
someThreadLocal.set(expression);
try {
stuff
} finally {
someThreadLocal.set(t3dsfgr838);
}

where the temporary's name is guaranteed not to otherwise exist in
this scope.

There should then of course be built-in thread locals for some stuff
(such as math context to use for the forms of BigDecimal methods that
don't take an explicit one, and which overloaded + and the like would
use). Switching on a particular math context for a block of
calculations is then easy and natural:

do switch (Math.mathContext: myMathContext) {
someBigDecimal = someOther + yetAnother;
someBigDecimal *= 4; // Should accept mixed primitive/reference
// types IF the reference type has a valueOf(foo) method
// matching the primitive to use for promotion!
someMoreCalculations();
}

And of course ThreadLocal should be made a) faster to access (at least
to just read) and b) generic (so with a ThreadLocal<String>, you would
not have to cast theThreadLocal.get() to String, etc.; why was this
done promptly for WeakReference et. al. but not ThreadLocal? Arrrgh!)
 
S

Stefan Ram

Roedy Green said:
There are two JVM instructions to implement a switch. Java's N-way
branch. In the JVM there are two different ways of implementing a
switch, tableswitch and lookupswitch. The efficient tableSwitch is a
jump table used when the switch values are reasonably dense e.g.
numbered 0..N. The less efficient lookupSwitch is a binary search used
when the switch values all all over the map. It thus pays to keep your
switch values dense.

Still, they might be implemented by if-sequences.
As Ralf Ullrich recently quoted:

»Figure 5 shows that Java dense switches (tableswitches),
when used to implement dynamic dispatch, result in
performance very similar to that of virtual calls on the
IBM JVM, revealing an implementation based on jump tables.

In the HotSpot Client JVM however, both on Pentium III and
UltraSparc III (gures 7 and 8), tableswitch es behave
exactly like if sequences, which indicates an actual
implementation based on sequences of conditional branches.
Table switches are therefore unreliable in terms of
performance across JVMs.«

The source according to Ralf is:

»Evaluation of Control Structures for Dynamic Dispatch in Java«

http://www.cs.mcgill.ca/research/techreports/reports/01/SOCS.01.13.ps.gz

I just wrote a benchmark, which showed if-sequences to be
actually faster than switches for the special case tested.

import static java.lang.System.nanoTime;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.out;
import static java.lang.System.gc;
import static java.lang.Thread.sleep;

public class Main
{ public static void main( final java.lang.String[] args )
throws java.lang.Throwable
{ int randomizer =( int )( currentTimeMillis() / 947 ); int i1; int i2;
int r0; int r1;
int s;
long d0; long d1; long d2;
long t0, t1, t2, t3, t4, t5;
out.printf
( "Benchmark running - " +
"Please minimize activity of other processes.%n" );
sleep( 3000 );
double a = 0.; double c = 0.;
out.printf
( "The columns" + "%n" +
" Identification number of the outermost iteration" + "%n" +
" Runtime of \"if\" divided by runtime of \"switch\"" + "%n" +
" Average of the preceding column" + "%n" );
for( long l = 0;; ++l )
{ r0 = 0; r1 = 0; s = 0;
d0 = 0; d1 = 0; d2 = 0;
gc();
Thread.sleep( 1000 );
final long n = 100000000L;
{ { t4 = nanoTime();
randomizer +=( int )(( t4 / 7907 )% 611953 );
for( long i = 0; i < n; ++i )
{ randomizer = randomizer * 1103515245 + 12345;
final int random =( randomizer / 65536 )% 10;
s += random; }
t5 = nanoTime();
d2 +=( t5 - t4 ); }
{ t0 = nanoTime();
for( long i = 0; i < n; ++i )
{ randomizer = randomizer * 1103515245 + 12345;
final int random =( randomizer / 65536 )% 10;
{ if( random == 0 )r0 = 20418437;
else if( random == 1 )r0 = 94704581;
else if( random == 2 )r0 = 45898144;
else if( random == 3 )r0 = 49094059;
else if( random == 4 )r0 = 77416885;
else if( random == 5 )r0 = 91322469;
else if( random == 6 )r0 = 40218964;
else if( random == 7 )r0 = 93641667;
else if( random == 8 )r0 = 29822916;
else r0 = 625909; }
s += r0; }
t1 = nanoTime();
d0 +=( t1 - t0 ); }
{ t4 = nanoTime();
for( long i = 0; i < n; ++i )
{ randomizer = randomizer * 1103515245 + 12345;
final int random =( randomizer / 65536 )% 10;
s += random; }
t5 = nanoTime();
d2 +=( t5 - t4 ); }
{ t2 = nanoTime();
for( long i = 0; i < n; ++i )
{ randomizer = randomizer * 1103515245 + 12345;
final int random =( randomizer / 65536 )% 10;
switch( random )
{ case 0: r1 = 16336774; break;
case 1: r1 = 62881795; break;
case 2: r1 = 27998504; break;
case 3: r1 = 9612956; break;
case 4: r1 = 25592297; break;
case 5: r1 = 77114095; break;
case 6: r1 = 23554325; break;
case 7: r1 = 55380051; break;
case 8: r1 = 47971513; break;
default: r1 = 41100793; }
s += r1; }
t3 = nanoTime();
d1 +=( t3 - t2 ); }}
final double q =( d0 - d2 / 2.0 )/( d1 - d2 / 2.0 );
a += q;
out.printf( "%6d; %6.02f; %6.02f%n", l, q, a /( l + 1 ), s ); }}}

/*

Benchmark running - Please minimize activity of other processes.
The columns
Identification number of the outermost iteration
Runtime of "if" divided by runtime of "switch"
Average of the preceding column

0; 0,73; 0,73
1; 0,93; 0,83
2; 0,93; 0,87
3; 0,93; 0,88
4; 0,93; 0,89
5; 0,93; 0,90
6; 0,93; 0,90

*/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top