Should the primitive wrappers be lazy Flyweights?

Following on from a discussion earlier today, which observed that autoboxing currently creates new wrappers:
Integer i = 7;
//currently expands to
Integer i = new Integer(7);
//but we probably want it to become
Integer i = Integer.valueOf(7);This got me thinking about this discussion I saw recently:
http://www.cafeaulait.org/oldnews/news2004March16.html
And that made me think about caching and and the Flyweight design pattern [GangOfFour]
Here's the JavaDoc for Integer.valueOf(int):
* Returns a <tt>Integer</tt> instance representing the specified
* <tt>int</tt> value.
* If a new <tt>Integer</tt> instance is not required, this method
* should generally be used in preference to the constructor
* {@link #Integer(int)}, as this method is likely to to yield
* significantly better space and time performance by cacheing
* frequently requested values.
* @param i a int value.
* @return a <tt>Integer</tt> instance representing <tt>i</tt>.
* @since 1.5
public static Integer valueOf(int i) ;
Unfortunately, this method currently just does:
new Integer(i) !
Is the plan to introduce the use of caching here? And if so will autoboxing use it?
Consider this code:
Integer a = 7;
Integer b = 7;
a.equals(b); // TRUE
a == b; // FALSE with the current autoboxing implementationIf you were to do caching for wrappers, and autoboxing were to use valueOf(), then the second comparison would yield "true".
Thinking that through, one obviously can't change the fact that Integer's constructor is public, so it would always be possible to create new Integers that failed the reference equality test.
Integer is not Cloneable but it is Serializatable, so you'd have to implement readResolve().
I don't know if it would be acceptable to have the old Integer.valueOf(String) method return a cached Integer... probably...
Finally, you'd probably want to support an Integer.intern() method, similar to String.intern() so people can resolve Integers they receive from libraries, should they wish to do so.
Naturally everything I've said about Integer can be applied to the other wrapper classes too.
So is any of this stuff planned? The comments on Integer.valueOf(int) seem to suggest that it is, but some insight would be nice.

We're always being told to use 'new' instead of object
pooling, because object creation/deletion is so fast
these days. Supposedly also one day the JVM will be
able to create stack instead of heap objects (under
suitable circumstances), so 'new' will be almost
costless, whereas pooling would be almost impossible
for the JVM to optimize away.I understand what you mean, and I agree with it for most uses. It somewhat misses the point in this instance.
If one goes around creating 'new' objects then '==' must necessarily return 'false' when they are compared. This is not useful behaviour in this case, in particular because Integer and the other wrapper classes are immutable. It defies expectations that two Integer's that are both '7' are not ==.
The real reason I say you missed the point is because the aim of this object pool is not to improve performance, its to get a different behaviour for autoboxed Integers. As such, while saying "it may be faster to create new objects" is an interesting observation, unless you can devise a way to allocate new objects and preserve reference equality, its not really relevant to the question I was trying to ask.
If you do want to think about performance though, here's some thoughts:
I'm not sure whether you'd ever need to garbage collect the cached Integer instances. I'd guess that you could, because you could use weak references in the cache and let the Integer instances be collected once no more code needs them. In pratice a small working set of Integers (and Doubles, Longs etc) would probably always exist because they would be being used by the VM. It would probably even be worthwhile to determine what this working set is, and preload it as a part of the new startup image optimization.
You might simply decide never to cleanup cached Integers. It might work better to just keep them around for the next time someone uses them. My guess would be some large perctentage of the commonly used Integers fall in a range close to zero (+/- 128?), so why not always have these on-hand in the cache? Perhaps high numbers are rarely used, and would be weak references, but low numbers would be strong references and would never be collected?
One would need to measure and tune to really be sure.
If it turns out that 99% of the Integer objects ever allocated are already loaded in the cache, then all you ever pay is the lookup cost. You would never allocate them and never have to garbage collect them. And that's likely to be faster than making them with 'new' no matter how fast the allocator & collector get. You can't beat simply doing no work on the collection side of things!

Similar Messages

  • Cannot invoke toString on the primitive type int

    im trying to make a sudoku puzzle but having trouble with the arrays, ive got two arrays
    int [][] actual = new int [9][9];
        String [][] possible = new String [9][9];part of my code im trying to generate a sudoku board, this is the part of the error in
    public void possVals(int col, int row)
              if(possible[col][row].equals(""))
                   str = "123456789";
              else str = possible[col][row];
              for(r = 1; r < 9; r++)
                   if(actual[col][r] != 0)
                        str = str.Replace(actual[col][r].toString(), "");
              }could some one tell me how to fix my error of 'cannot invoke toString on the primitive type int' please

    ajp_08 wrote:
    could some one tell me how to fix my error of 'cannot invoke toString on the primitive type int' pleaseBut you can do like this
    int i = 12345;
    String s = Integer.toString(12345);So, the following should work
    str = str.Replace(Integer.toString(actual[col][r]), "");Good luck!
    Edited by: A.J.Bharanidharan on Nov 17, 2009 6:06 PM

  • Comparing primitive wrappers

    I guess everyone who played around with autoboxing ran into the problem that comparing primitive wrappers does not compare values but object references.
    This is annoing since java 1.0 but the issue becomes much worse with autoboxing. You can now freely intermix Integer and int without compile time error, so the chance that you compare Integer references while you mean to compare int values has increased.
    Example
    int getOneValue() ...
    Integer getAnotherValue() ...
    // and somewhere else
    if (getOneValue() == getAnotherValue()) ...
    This will work as expected long as at least one function returns an int (thanks to auto unboxing). If you change both functions to return Integer this will still compile, but it won't work anymore.
    I know that this cannot be changed for backward compatibility reasons but it would be VERY helpful if we could get some kind of workaround.
    For example an annotation to tell the compiler that we want auto-unboxing before compare:
    How about:
    @greedyunboxing(true)
    Integer getOneValue() ...
    Integer getAnotherValue() ...
    if (getOneValue() == getAnotherValue()) ... // unbox before compare now because @greedyunboxing is true

    I'd just prefer that the compiler issue a warning when it sees reference equality tests between two primitive wrapper objects. If you really intend to do that (which would be extremely rare) you could turn off the warning via some annotation.
    God bless,
    -Toby Reyelts

  • The background thread running lazy writer encountered an I/O error

    Hi I have a test server which has thrown the following error
    File system error: A system error occurred while attempting to read or write to a file store. The system might be under memory pressure or low on disk space. Physical file: \\?\F:\MSAS11.DEPLOYAS\OLAP\Data\Prod_KCube.0.db\DIM Flags And Types.0.dim\3.Flag
    Types Key.khstore. Logical file: . GetLastError code: 8. File system error: The background thread running lazy writer encountered an I/O error. Physical file: \\?\F:\MSAS11.DEPLOYAS\OLAP\Data\Prod_KCube.0.db\DIM Flags And Types.0.dim\3.Flag Types Key.khstore.
    Logical file: . Errors in the OLAP storage engine: An error occurred while processing the 'Facts' partition of the 'Main Facts' measure group for the 'Prod_Cube' cube from the Prod_KCube database.
    The cube sits on a not very well maintained server which is used by various users (it is a test server) with the following specs
    Intel(R) Xenon(R) CPU x5690 @3.47GHz
    24GB Ram
    64 Bit operating system.
    The Cube data and logs are on separate drives and have plenty data but the C drive (where SQL Server is installed) only has3.5Gb of space left.
    It's a fairly big cube and I've managed to get it running by processing dimensions and facts bit by bit but errors when processed all together.
    What could be causing the errors above?

    Hi aivoryuk,
    According to your description, you get the lazy writing error when processing partitions. Right?
    In this scenario, the issue may cause by low memory for SSAS and lack of disk space. Please consider configure
    Server Properties (Memory Page) and increase
    memory setting for SSAS. If the .cub file is located in C drive, please reserve more disk space.
    Please refer to a similar thread below:
    https://social.msdn.microsoft.com/Forums/sqlserver/en-US/21bf84c5-f89a-464a-a5f1-2649fae5eb1e/while-processing-large-cubes-various-file-system-errors-the-background-thread-running-lazy-writer?forum=sqlanalysisservices
    Best Regards,
    Simon Hou
    TechNet Community Support

  • HT5262 How long should the icloud back up take?

    How long should the iCloud back up take? I only have 4gb of storage but it has taken almost an hour already with approximately 2 hours remaining. 

    Hi RMaskery14,
    If you are concerned about the time your iCloud backup is taking, you may find the following article helpful:
    My backup is taking a long time to finish.
    Backing up and restoring takes time, especially if you have a lot of data or a slow connection. Depending on the size of your backup and the speed of your network, you may need more time than expected to complete the process. Using a reliable connection when backing up your device is highly recommended.
    iCloud: Troubleshooting creating an iCloud backup
    http://support.apple.com/kb/ts3992
    Regards,
    - Brenden

  • What size should the back-up drive be?

    I'm using a lacie 1TB External firewire drive to back-up my 250gig iMac, I mostly use the mac for email, photos, home use etc. (The drive is almost full, using 230 gig). (Yes I know that's too full and I plan to put in a 500 gig drive). I upgraded to leopard about a month ago and set up time machine recently. There are 17 backups- "lines" in the time machine "star wars" screen- on the external drive totaling 700 gig of data!!
    I have not added any pictures or large files since beginning to use Time machine. Should the time machine backups use that much space? I thought after the initial back-up time machine only keeps record of the changes.? Using CCC I could have cloned the hard drive three times and still have room left!
    Does the large amount of HD space used to back-up sound ok for only a 250 hard drive?
    Joe

    Many users here recommend that your TM volume be about two and a half times the size of the data on your main hard drive. So, if you have 400GB of data to back up, you should give TM a 1GB volume for backing up.
    But in my experience, how much space you need really depends on your computer usage patterns. My weekly backups go all the way back to January 2008, when I first started. My main hard drive has 115 GB used of 148 GB total. My TM backups of that disk total 168 GB on a 212 GB partition. So I have never needed to have nearly as much backup space as the 2.5 multiplier recommendation.
    I try to manage my computer use so that Time Machine is not backing up files I do not want backed up, and is not backing up stuff twice if I move files to a different location. I rarely work with large files (no photoshop, no Final Cut Pro, etc). When I do have large files, they usually start in my Downloads folder. If I want to keep something I download, I eventually move it to a different location. To prevent TM from backing it up twice and unnecessarily using up space on the TM drive, I exclude my Downloads folder from being backed up. I'll let TM back it up after the download is in its new permanent location.
    I don't really consider it a big deal to not have backups of the contents of my downloads folder. I figure that if my hard drive breaks and I lose all of my downloads, I can just download them again.

  • Should the condition in the loop step

    Should the condition in the loop step in the integration process(BPM) be = or not= ?I need to do the following>>perform certain operation only when the container value is less than 3 Else then get out of the loop.
    Regards,
    Mansi

    The loop step in ccBPM implements a while loop.
    So, while count not = 3, it will be executed.
    Once the counter reachs 3, the loop will be terminated.
    Regards,
    Henrique.

  • What should the"default behavior" be for WiFi network connections?

    I Have been able to at least temporarily fix the plethora of problems encountered after downloading Mountain Lion to my 2009 17" MBP just ten days ago.  Thanks to the time and effort of so many posters that are much more savvy than me, I successfully executed the steps suggested in many of the posts and with good results.  It surely beats running down to the Apple store and being told that I am the only one with a problem.
    Okay,  I've  realized that I don't really know what the default behavior of the WiFi network connection should be? 
    Specifically:
    Should the Wi-Fi drop down in Network always be" looking for networks", even though I am obviously on my Network?
    Should the Wi-Fi be connected at all times even when your computer is in sleep mode- or deep sleep mode?  There have been so many problems with Wi-Fi dropping off,slow or hanging loads, etc.
    I unchecked "ask to join networks, in Network preferences thinking it might stop looking for networks when it doesn't need to because I'm already on mine.  I do see my neighbors (four neighbors) in the drop down in Network. 
    How do you get into Time Capsule's settings, to check speeds, especially ping?  What should the ideal settings be?
    How do you know if your DHCP license is renewed? I've heard that feature isn't working and may be the culprit to some of the Wi-Fi problems.
    I'll look forward to your help in understanding more about this.  I've been in the support  area a lot lately, I've read plenty of definitions, and explanations of the different options to choose from in Apple's support area, but nowhere have I seen anything that explains what the default behavior should be or perform  like. 
    Thanks, as always.

    Generally, you don't want to tweak the wifi settings. It pretty much takes care of itself. The caveat to that is, of course, if you're experiencing problems.
    The 'looking for networks' behaviour only happens when you log in, wake the mac from sleep OR when you click on the wifi icon. You clicking on it tells the mac  "I want to see what networks are available" - so it does a scan for you to check to see if any new networks have appeared since you last clicked on it (or woke/logged in). In short, if you don't want it to look for new networks, don't click on the icon!
    Unchecking the 'ask to join networks' option only applies when your mac detects a new network (such as when it wakes) that you haven't already authorised; it'll ask you to confirm whether you want to join it or not. Otherwise, if the network is open it'll join automatically. You should keep this selected if you travel around with your Mac. It's a good idea to know what network you're on before you start plugging in passwords or typing other things into the mac.
    There is a utility that you can use for ping and traceroute called 'Network Utility'. Click on the Spotlight icon in the top right of your screen and type "Network' and you should see it at the top of the list. Hit 'return' to open it.
    DHCP licences are normally renewed automatically by your router every 24 hours. Again, there's no reason to be messing about with that unless you're experiencing problems.
    If you're experiencing wifi dropout, let us know, and we'll make some suggestions, but if you're not, you're best leaving your mac to manage the background processes. It knows what it's doing!
    Message was edited by: softwater

  • If someone changes the date on an iCal event should the date change for the invitees if they accept the change?

    My wife's calendar schedule is pretty hectic and prone to date changes. If I accept the initial invitation it appears correctly in my calendar and syncs correctly to all my devices but I find that if she changes a date and I accept the new change, the event stays the same in my calendar. 
    Is this correct or am I having problems?
    Cheers

    Thanks - I did get the event to go back to 2008, but should the individual clips move to the correct spot in the timeline also?  I need to go back and play with it a little more - I would guess you might have to look at the length of clips on either side of where you want the new clip placed for it to work correctly. 
    So, I guess my 2nd question is if you can get the new clips that were added at the end of the event to move into the correct position within the event.

  • What should the settings in Preview be if scanning documents and the faxing them

    I'm trying to scan documents using preview and my printer. Once I scan the documents, I save them in dropbox and later fax them using SFax. However, the faxes are coming out blurry and very difficult to read. What should the Preview settings be on? PDF? File Format? How many dots per inch? What are standard settings?

    I am a recently retired webmaster and fortunately have fewer eye problems than most people my age. I have astigmatism and, in common with most people over 40, have reduced accommodation. Perhaps because I have spent considerable time in front of computer screens my eyes focus most easily at screen distance. I use low power long distance glasses to watch television and drive after dark. I use low power reading glasses for small print such as maps and repairing small items. Most of the time I don't need glasses.
    There is no such thing as standard settings for font size or style. It is entirely a matter of personal preference.
    Here are my settings:
    34cm x 27cm Apple Studio Display set to millions of colours and a resolution of 1280 x 1024
    Safari 'standard' font set to Geneva 14
    Safari fixed width font set to Courier 14
    Default encoding set to Western (ISO Latin 1)
    Minimum font size set to 10
    Geneva is a very old Apple font optimised for screen use. I still find it more readable than other fonts under a wide range of conditions.
    I assume you know about Zoom settings to override the above:
    cmd + to increase size
    cmd - to decrease size
    cmd 0 to return to 'normal' size
    I set 'Zoom Text Only' on the view menu.
    You can also create your own style sheet to obtain even more control. Here is a Google search link about these:
    https://encrypted.google.com/search?q=browser+%27style+sheet%27+%27visually+impa ired%27&as_qdr=all&newwindow=1&num=100
    I have written many style sheets but not for visually impaired. I am happy to assist if required.

  • Should the vendor in the Shopping Cart be updated from the Sourcing Cockpit

    Hi All,
    hopefully an easy question for someone to answer.
    When a vendor is assigned in the Sourcing Cockpit and the Purchase Order is created should the vendor be updated in the linked shopping cart?
    Cheers
    Chris

    Hi Chris,
    All questions are welcome irrespective of the criticality so you are free to ask anything related to SRM.
    The vendor will not get updated in the shopping cart if you assign a vendor at the time of sourcing while creating a P.O. The same can be checked out by selecting the Source of supply / service agents link in the check status for a particular shopping cart.
    The source of supply field will only be populated when you assign the vendor at the shopping cart level and not during the P.O creation.
    Hope this will make you clear.
    Rgds,
    Teja

  • Should the passwords in 'System keychain' (in Keychain Access) normally be accessible to the owner/administrator?

    Should the passwords in 'System keychain' (in Keychain Access) normally be accessible to the owner/administrator or not?
    If not, would it be possible to gain access via the Root Account?
    I can access the passwords in 'Login keychain' (in Keychain Access). But when I try to access the passwords in 'System keychain' I'm asked for the Keychain Access password! I've never set such a password. I've only ever used one password - my owner/administrator password. But this isn't accepted when I try to access the passwords in 'System keychain'.
    Please note, this question was previously posted in the OSX Tiger forum but no-one offered an answer
    Thanks,
    iHope

    Seems this is a characteristic of the system keychain.
    Check out this thread...and furtwanglerian's response....
    http://discussions.apple.com/thread.jspa?messageID=8767033&#8767033
    closed

  • Should the screen show when the ringer switch is changed?

    My ringer is not working on my 4S with 7. Should the screen show when the mute switch is changed from on to off and back? I believe it did before.

    But is not now. and my ringer is intermittent.

  • How long should the Mac Book pro hold its charge???

    How long should the Mac Book pro hold a  battery charge??

    For a single use or how long will the battery last until it needs to be replaced?  For single use, it depends on what you are doing when using you mac.  I find that when using mine I get about 6-6 1/2 hours just using it to browse the internet before I need to recharge it.  If it is one of the newer Macbook Pros that claim to have a 7 hour battery life, It can last up to 5 years.  See this article on notebook batteries to get the most out of your battery: http://www.apple.com/batteries/notebooks.html.  Hope this helps

  • Should the USB port on my MacBook Pro charge my phone?

    Should the USB port on my MacBook Pro charge my phone?

    wait i misread as iphone
    well it depends what type of phone you have

Maybe you are looking for

  • Error message on start up "Lightroom encountered an error when reading from its preview cache and needs to quit"

    Error message on start up "Lightroom encountered an error when reading from its preview cache and needs to quit" I uninstalled and downloaded it again and still get the same error.  At this rate I won't have any chance to use the 30 day trial period

  • Can't export files in XPPro

    I just shelled out 30 duckets for the pro version to convert files to view in my new ipod nano. It will not convert files properly. The files are .flv type, when I click to export it opens box saying file already exists. then I check no to write a ne

  • JBO-30003 Error

    My application receive the next error at least three times by day, there are any solution? the users bother this kind of error (obviously they do not see the error I see the error by log) JBO-30003: The application pool (com.telmexusa.sales.services.

  • OIM Design Console customization

    Gurus How do I customize OIM Design Console and where can I find information regarding it? In particular how to add or remove Menu items? Kindly help oimlover

  • KUKEY Field in FEBKO table

    Hi Team, I would like to know how the FEBKO table gets filled as I need  to find out how the field KUKEY in the table FEBKO gets filled. Please help me. This field is displayed in FEBAN transaction.