code_junkie

Java: enough free heap to create an object?

Nov 12th, 2011
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. try {
  2. // try to perform an operation using a huge in-memory array
  3. byte[] massiveArray = new byte[BIG_NUMBER];
  4. }
  5. catch (OutOfMemoryError oome) {
  6. // perform the operation in some slower but less
  7. // memory intensive way...
  8. }
  9.  
  10. if (Runtime.getRuntime().freeMemory() > SOME_MEMORY) {
  11. // quick memory-intensive approach
  12. }
  13. else {
  14. // slower, less demanding approach
  15. }
  16.  
  17. -Xmx
  18.  
  19. java -Xmx8g some.name.YourMemConsumingApp
  20.  
  21. if( isEnoughMemory( SOME_MEMORY ) ){
  22. strategy = new InMemoryStrategy();
  23. }else{
  24. strategy = new DiskStrategy();
  25. }
  26.  
  27. strategy.performTheAction();
  28.  
  29. ...
  30. strategy = new ImaginaryCloudComputingStrategy();
  31. ...
  32.  
  33. while( !isDone() ) {
  34. if( isMemoryLow() ){ //Runtime.getRuntime().freeMemory() < SOME_MEMORY + some other validations
  35. swapToDisk(); // and make sure resources are GC'able
  36. }
  37. byte [] array new byte[PREDEFINED_BUFFER_SIZE];
  38. process( array );
  39.  
  40. process( array );
  41. }
  42. cleanUp();
Add Comment
Please, Sign In to add comment