Meta tags:
description= An explanation of value-based classes in Java 8. Why do they exist? What are their limitations? How (not) to use them?;
keywords= value-based classes;
Headings (most frequently used words):
value, based, classes, exist, identity, side, vbi, background, characteristics, limitations, findbugs, reflection, why, do, they, what, state, type, boxes, declaration, use, reference, comparison, serialization, of, locking, on, hash, code,
Text of the page (most frequently used words):
the (96), value (73), and (64), based (52), java (52), classes (42), are (36), identity (35), this (33), that (29), types (24), with (21), not (20), instances (19), state (19), which (19), for (19), will (18), #limitations (17), project (16), they (16), have (15), their (15), object (14), reference (14), about (13), code (13), but (12), all (12), other (12), class (12), you (11), can (11), like (11), use (10), being (10), why (10), from (10), optional (10), boxes (10), what (10), exist (10), these (9), instance (9), serialization (9), when (8), equal (8), findbugs (7), them (7), vbi (7), its (7), must (7), should (7), there (7), though (7), equality (7), might (7), declaration (6), now (6), also (6), rule (6), let (6), two (6), any (6), side (6), equals (6), important (6), some (6), type (6), integer (6), new (6), future (6), post (6), reflection (5), your (5), hash (5), references (5), note (5), how (5), one (5), above (5), jvm (5), string (5), even (5), int (5), junit (5), meaningful (4), rules (4), well (4), see (4), jdk (4), cases (4), free (4), locking (4), make (4), explanation (4), look (4), list (4), may (4), documentation (4), because (4), break (4), valhalla (4), time (4), requirements (4), most (4), considered (4), same (4), another (4), while (4), different (4), follow (4), would (4), performance (4), characteristics (4), community (4), license (3), github (3), define (3), both (3), were (3), implement (3), site (3), out (3), get (3), know (3), help (3), doesn (3), own (3), marked (3), uses (3), primitive (3), via (3), non (3), serializable (3), straight (3), operation (3), comparison (3), could (3), sensitive (3), wrapped (3), talks (3), regard (3), precise (3), ish (3), those (3), immutable (3), was (3), operations (3), such (3), between (3), contain (3), first (3), kind (3), without (3), going (3), means (3), only (3), consider (3), example (3), point (3), then (3), interchangeable (3), implemented (3), unclear (3), similar (3), primitives (3), likely (3), switch (3), existing (3), year (3), works (3), background (3), share (3), next (3), pioneer (3), demos (3), streams (3), core (3), clean (3), privacy (2), rss (2), stackoverflow (2), twitch (2), youtube (2), discord (2), mastodon (2), bluesky (2), seen (2), changes (2), coming (2), limited (2), discussed (2), detail (2), soon (2), done (2), sure (2), ready (2), decided (2), feature (2), don (2), since (2), deleted (2), request (2), course (2), user (2), created (2), comments (2), violations (2), removed (2), recreated (2), guaranteed (2), sense (2), calls (2), headers (2), field (2), desirable (2), forward (2), today (2), makes (2), less (2), missing (2), examples (2), closer (2), short (2), produce (2), distinguish (2), values (2), whether (2), indirectly (2), synchronization (2), interesting (2), chrono (2), through (2), effect (2), variable (2), final (2), meaning (2), change (2), instead (2), methods (2), solely (2), lock (2), mutable (2), formatting (2), mine (2), hence (2), into (2), javadoc (2), has (2), does (2), ignore (2), introduced (2), very (2), character (2), identical (2), part (2), fully (2), behave (2), determined (2), comparing (2), think (2), talking (2), neither (2), localtime (2), here (2), case (2), recreate (2), assume (2), guarantee (2), looks (2), still (2), say (2), words (2), benefits (2), preceded (2), relation (2), boxed (2), unboxed (2), relationship (2), brian (2), goetz (2), 2015 (2), found (2), source (2), already (2), present (2), believe (2), active (2), various (2), platforms (2), watch (2), space (2), notified (2), publish (2), content (2), libfx (2), record (2), args (2), var (2), turn (2), tools (2), techniques (2), records (2), panama (2), loom (2), leyden (2), amber (2), patterns (2), pattern (2), matching (2), ramp (2), migration (2), meta (2), maven (2), libraries (2), lambda (2), javafx (2), basics (2), j_ms (2), generics (2), dop (2), deprecation (2), libs (2), collections (2), architecture (2), tags (2), javascript (2), contact, imprint, precursor, possibilities, creates, plan, properly, written, finally, roll, around, curious, wanting, contribute, set, try, myself, asking, takes, long, fault, talk, cheap, join, put, clone, progress, pull, good, mean, tool, keeps, overstepping, wouldn, really, helpful, heavy, ask, ticket, covers, uphold, annotation, highlighting, improving, upon, explanations, greatly, appreciated, key, identityhashmap, argument, identityhashcode, system, required, constant, over, lifetime, constancy, developers, notifyall, notify, wait, synchronized, block, header, access, monitor, direct, writeobject, objectoutputstream, transient, definition, seems, promises, conflict, notion, current, implementation, traversing, graph, regarded, avoided, obviously, distinguishes, considering, distinguished, listed, violating, made, come, included, concrete, each, stands, program, unpredictable, results, attempts, directly, appeal, hashing, mechanism, again, breaks, similarly, below, thread, mailing, number, addresses, concerns, depends, interpretation, way, read, include, typical, variables, murkily, motivated, technical, design, reasons, transfered, obvious, freely, substitutable, interchanging, according, computation, method, invocation, visible, behavior, accessible, constructors, instantiated, factory, committment, returned, intrinsic, implementations, computed, tostring, hashcode, objects, numbering, ground, separated, stated, used, built, accordingly, leniency, defining, fit, expected, implications, purely, artificial, thing, anything, wrong, dramatically, planned, adds, more, difficult, explain, deeper, overly, strict, given, problematic, necessarily, somewhat, construed, counterintuitive, force, strictly, interpreted, including, itself, actually, sequence, wrap, sequences, functions, determines, fields, whose, regular, trickier, depend, vale, generally, exchanged, refer, implementing, implication, replacing, discernible, best, integers, programmer, passed, differently, remove, thus, destroying, pass, treat, described, won, begin, just, corresponding, merely, destroy, individual, term, context, constantly, modified, always, appropriately, defined, freed, tracking, lead, substantial, improvements, additionally, compiler, silently, improve, exactly, switching, back, forth, removing, later, recreating, forbids, mechanisms, applied, said, continue, quote, exact, properties, interact, imposed, latter, derived, desired, clear, suffice, establish, call, jan, disclaimers, arrived, day, hand, probably, hopelessly, polluted, gobs, ceased, lockable, despite, practice, boxing, sounds, after, prototypes, backwards, compatibility, retroactively, invalidate, contravene, double, addition, safe, bases, meant, guava, complete, official, listing, thaibuddhistdate, minguadate, japanesedate, hijrahdate, zoneoffset, zoneid, zoneddatetime, yearmonth, period, offsettime, offsetdatetime, monthday, localdatetime, localdate, instant, duration, optionalint, optionallong, optionaldouble, util, became, apparent, specified, documented, designed, add, codes, gross, simplification, idea, interfaces, central, characteristic, handled, puts, his, introductory, article, little, wrote, version, write, weeks, definitely, covered, seem, pointless, aren, yourself, tuned, stay, quick, before, detailing, impatient, jump, closes, able, got, small, stating, includes, link, easily, overlooked, subtle, ways, releases, prevent, wanted, cover, mentioned, bits, articles, toc, table, contents, lic, artist, dev, src, slides, upcoming, past, schedule, recordings, virtual, threads, vector, structured, concurrency, lilliput, galahad, babylon, openjdk, conversation, book, club, videos, jms, newsletter, blog, posts, testing, rant, jigsaw, jdeps, impulse, default, lang, review, better, enabled, nipafx,
Text of the page (random words):
javafx junit 5 junit pioneer lambda libraries maven meta migration on ramp openjdk optional pattern matching patterns performance project amber project babylon project galahad project leyden project lilliput project loom project panama project valhalla records reflection serialization streams structured concurrency switch techniques tools turn of the year var vector virtual threads recordings streams schedule code demos demos demos junit pioneer record args libfx talks my talks past upcoming slides about about me license privacy 2015 02 15 value based classes post java 8 java next project valhalla an explanation of value based classes in java 8 why do they exist what are their limitations how not to use them src source dev artist lic license value based classes table of contents background why do they exist what value based classes exist characteristics identity state value type boxes limitations declaration side use side reference comparison serialization of vbi locking on a vbi identity hash code findbugs reflection share follow share this post with your community i m active on various platforms watch this space or follow me there to get notified when i publish new content toc background why do they exist what value based classes exist characteristics identity state value type boxes limitations declaration side use side reference comparison serialization of vbi locking on a vbi identity hash code findbugs reflection s f share this post with your community i m active on various platforms watch this space or follow me there to get notified when i publish new content in java 8 some classes got a small note in javadoc stating they are value based classes this includes a link to a short explanation and some limitations about what not to do with them this is easily overlooked and if you do that it will likely break your code in subtle ways in future java releases to prevent that i wanted to cover value based classes in their own post even though i already mentioned the most important bits in other articles this post first looks at why value based classes exist and why their use is limited before detailing those limitations if you re impatient jump here it closes with a note on findbugs which will soon be able to help you out background let s have a quick look at why value based classes were introduced and which exist in the jdk why do they exist a future version of java will most likely contain value types i will write about them in the coming weeks so stay tuned and will present them in some detail and while they definitely have benefits these are not covered in the present post which might make the limitations seem pointless believe me they aren t or don t believe me and see for yourself for now let s see what little i already wrote about value types the gross simplification of that idea is that the user can define a new kind of type different from classes and interfaces their central characteristic is that they will not be handled by reference like classes but by value like primitives or as brian goetz puts it in his introductory article state of the values codes like a class works like an int it is important to add that value types will be immutable as primitive types are today in java 8 value types are preceded by value based classes their precise relation in the future is unclear but it could be similar to that of boxed and unboxed primitives e g integer and int the relationship of existing types with future value types became apparent when optional was designed this was also when the limitations of value based classes were specified and documented what value based classes exist these are all the classes i found in the jdk to be marked as value based java util optional optionaldouble optionallong optionalint java time duration instant localdate localdatetime localtime monthday offsetdatetime offsettime period year yearmonth zoneddatetime zoneid zoneoffset java time chrono hijrahdate japanesedate minguadate thaibuddhistdate i can not guarantee that this list is complete as i found no official source listing them all in addition there are non jdk classes which should be considered value based but do not say so an example is guava s optional it is also safe to assume that most code bases will contain classes which are meant to be value based it is interesting to note that the existing boxing classes like integer double and the like are not marked as being value based while it sounds desirable to do so after all they are the prototypes for this kind of classes this would break backwards compatibility because it would retroactively invalidate all uses which contravene the new limitations optional is new and the disclaimers arrived on day 1 integer on the other hand is probably hopelessly polluted and i am sure that it would break gobs of important code if integer ceased to be lockable despite what we may think of such a practice brian goetz jan 6 2015 formatting mine still they are very similar so let s call them value ish characteristics at this point it is unclear how value types will be implemented what their exact properties will be and how they will interact with value based classes hence the limitations imposed on the latter are not based on existing requirements but derived from some desired characteristics of value types it is by no means clear whether these limitations suffice to establish a relationship with value types in the future that being said let s continue with the quote from above in java 8 value types are preceded by value based classes their precise relation in the future is unclear but it could be similar to that of boxed and unboxed primitives e g integer and int additionally the compiler will likely be free to silently switch between the two to improve performance exactly that switching back and forth i e removing and later recreating a reference also forbids identity based mechanisms to be applied to value based classes implemented like this the jvm is freed from tracking the identity of value based instances which can lead to substantial performance improvements and other benefits identity the term identity is important in this context so let s have a closer look consider a mutable object which constantly changes its state like a list being modified even though the object always looks different we would still say it s the same object so we distinguish between an object s state and its identity in java state equality is determined with equals if appropriately implemented and identity equality by comparing references in other words an object s identity is defined by its reference now assume the jvm will treat value types and value based classes as described above in that case neither will have a meaningful identity value types won t have one to begin with just like an int doesn t and the corresponding value based classes are merely boxes for value types which the jvm is free to destroy and recreate at will so while there are of course references to individual boxes there is no guarantee at all about how they boxes will exist this means that even though a programmer might look at the code and follow an instance of a value based class being passed here and there the jvm might behave differently it might remove the reference thus destroying the object s identity and pass it as a value type in case of an identity sensitive operation it might then recreate a new reference with regard to identity it is best to think of value based classes like of integers talking about different instances of 3 the int makes no sense and neither does talking about different instances of 11 42 pm the localtime state if instances of value based classes have no identity their equality can only be determined by comparing their state which is done by implementing equals this has the important implication that two instances with equal state must be fully interchangeable meaning replacing one such instance with another must not have any discernible effect this indirectly determines what should be considered part of a value based instance s state all fields whose type is a primitive or another value based class can be part of it because they are also fully interchangeable all 3 s and 11 42 pm s behave the same regular classes are trickier as operations might depend on their identity a vale based instance can not generally be exchanged for another if they both refer to equal but non identical instances as an example consider locking on a string which is then wrapped in an optional at some other point another string is created with the same character sequence and also wrapped then these two optional s are not interchangeable because even though both wrap equal character sequences those string instances are not identical and one functions as a lock while the other one doesn t strictly interpreted this means that instead of including the state of a reference field in its own state a value based class must only consider the reference itself in the example above the optional s should only be considered equal if they actually point to the same string this may be overly strict though as the given as well as other problematic examples are necessarily somewhat construed and it is very counterintuitive to force value based classes to ignore the state of value ish classes like string and integer value type boxes being planned as boxes for value types adds some more requirements these are difficult to explain without going deeper into value types so i m not going to do that now limitations first it is important to note that in java 8 all the limitations are purely artificial the jvm does not know the first thing about this kind of classes and you can ignore all of the rules without anything going wrong for now but this might change dramatically when value types are introduced as we have seen above instances of value based classes have no guaranteed identity less leniency in defining equality and should fit the expected requirements of boxes for value types this has two implications the class must be built accordingly instances of the class must not be used for identity based operations this is the ground for the limitations stated in the javadoc and they can hence be separated into limitations for the declaration of the class and the use of its instances declaration side straight from the documentation numbering and formatting mine instances of a value based class are final and immutable though may contain references to mutable objects have implementations of equals hashcode and tostring which are computed solely from the instance s state and not from its identity or the state of any other object or variable make no use of identity sensitive operations such as reference equality between instances identity hash code of instances or synchronization on an instances s intrinsic lock are considered equal solely based on equals not based on reference equality do not have accessible constructors but are instead instantiated through factory methods which make no committment as to the identity of returned instances are freely substitutable when equal meaning that interchanging any two instances x and y that are equal according to equals in any computation or method invocation should produce no visible change in behavior with what was discussed above most of these rules are obvious rule 1 is motivated by value based classes being boxes for value types for technical and design reasons those must be final and immutable and these requirements are transfered to their boxes rule 2 murkily addresses the concerns about how to define the state of a value based class the rule s precise effect depends on the interpretation of the instance s state and any other variable one way to read it is to include value ish classes in the state and regard typical reference types as other variables number 3 through 6 regard the missing identity it is interesting to note that optional breaks rule 2 because it calls equals on the wrapped value similarly all value based classes from java time and java time chrono break rule 3 by being serializable which is an identity based operation see below this thread on the valhalla mailing list talks about this use side again from the documentation a program may produce unpredictable results if it attempts to distinguish two references to equal values of a value based class whether directly via reference equality or indirectly via an appeal to synchronization identity hashing serialization or any other identity sensitive mechanism considering the missing identity it is straight forward that references should not be distinguished there is no explanation though why the listed examples are violating that rule so let s have a closer look i made a list of all violations i could come up with and included a short explanation and concrete cases for each vbi stands for instance of value based class reference comparison this obviously distinguishes instances based on their identity serialization of vbi it is desirable to make value types serializable and a meaningful definition for that seems straight forward but as it is today serialization makes promises about object identity which conflict with the notion of identity less value based classes in its current implementation serialization also uses object identity when traversing the object graph so for now it must be regarded as an identity based operation which should be avoided cases non transient field in serializable class direct serialization via objectoutputstream writeobject locking on a vbi uses the object header to access the instance s monitor headers of value based classes are free to be removed and recreated and primitive value types have no headers cases use in synchronized block calls to object wait object notify or object notifyall identity hash code this hash code is required to be constant over an instance s lifetime with instances of value based classes being free to be removed and recreated constancy can not be guaranteed in a sense which is meaningful to developers cases argument to system identityhashcode key in an identityhashmap comments highlighting other violations or improving upon the explanations are greatly appreciated findbugs of course it is good to know all this but this doesn t mean a tool which keeps you from overstepping the rules wouldn t be really helpful being a heavy user of findbugs i decided to ask the project to implement this and created a feature request this ticket covers the use site limitations and will help you uphold them for the jdk s as well as your own value based classes marked with an annotation being curious about findbugs and wanting to contribute i decided to set out and try to implement it myself so if you re asking why it takes so long to get that feature ready now you know it s my fault but talk is cheap so why don t you join me and help out i put a findbugs clone up on github since deleted and you can see the progress in this pull...
|