Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
   *
   * The contents of this file are subject to the terms of either the GNU
   * General Public License Version 2 only ("GPL") or the Common Development
   * and Distribution License("CDDL") (collectively, the "License").  You
   * may not use this file except in compliance with the License.  You can
  * obtain a copy of the License at
  * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
  * or packager/legal/LICENSE.txt.  See the License for the specific
  * language governing permissions and limitations under the License.
  *
  * When distributing the software, include this License Header Notice in each
  * file and include the License file at packager/legal/LICENSE.txt.
  *
  * GPL Classpath Exception:
  * Oracle designates this particular file as subject to the "Classpath"
  * exception as provided by Oracle in the GPL Version 2 section of the License
  * file that accompanied this code.
  *
  * Modifications:
  * If applicable, add the following below the License Header, with the fields
  * enclosed by brackets [] replaced by your own identifying information:
  * "Portions Copyright [year] [name of copyright owner]"
  *
  * Contributor(s):
  * If you wish your version of this file to be governed by only the CDDL or
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
  * elects to include this software in this distribution under the [CDDL or GPL
  * Version 2] license."  If you don't indicate a single choice of license, a
  * recipient has the option to distribute your version of this file under
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
  * its licensees as provided above.  However, if you add GPL Version 2 code
  * and therefore, elected the GPL Version 2 license, then the option applies
  * only if the new code is made subject to such option by the copyright
  * holder.
  */
 
 package com.sun.enterprise.web.ara.rules;
 
Based on the application context-root, configure the ReadTask Pipeline based on the policy metric defined in domain.xml.

Author(s):
Jeanfrancois Arcand
 
 public class HeapMemoryRule extends ThreadRatioRule implements TaskListener{

    
The memory allocated per application.
 
     protected final static ConcurrentHashMap<String,Long
             memoryAllowed = new ConcurrentHashMap<String,Long>();

                       
    
The memory available at startup.
  
     private static long availableMemory = -1L;
    
    
    
Cache application memory usage approximation.
 
     protected final static ConcurrentHashMap<String,Long>
             appMemoryUsage = new ConcurrentHashMap<String,Long>();
    
    
    
Cache the context-root assocated with a ReadTask
 
     protected final static ConcurrentHashMap<ReadTaskString>
             contextRootyCache = new ConcurrentHashMap<ReadTask,String>();
         
    
    
A customized Pipeline used to measure the memory used by an application.
 
     private static HeapMemoryRulePipeline hmrPipeline;

     
    
The default Pipeline used by application that are allowed to execute.
    private static Pipeline defaultPipeline;
    
    
    
The consolidated amount of memory an application is using.
    private static ConcurrentHashMap<String,Long>
            consolidatedMemoryUsed = new ConcurrentHashMap<String,Long>();
    
        
    
Simple lock.
    private Object[] lock = new Object[0];
    // ------------------------------------------------ Pipeline ------------//
    
    
    @Override
    public Integer call() throws Exception {
        synchronized(){
            if ( == -1L){
                 = usedMemory();
            }
            if (  == null ) {
                 = new HeapMemoryRulePipeline();
                .initPipeline();
                .startPipeline();
            }
        }
        
        String token = getContextRoot();
        Long memoryAllowedSize = .get(token);
        Double allowedRatio = .get(token);
        
        Pipeline pipeline = .get(token);
        synchronized(){
            if ( pipeline == null ){            
                if (  == null) {
                     = newPipeline(.getPipeline()
                        .getMaxThreads(),.getPipeline());
                }
                .put(token,);
                .setPipeline();
            } else {      
                .setPipeline(pipeline); 
            }
        }
        
        // If no policy metry has been defined for this token and there
        // is free memory, allow execution.
        if ( memoryAllowedSize == null && allowedRatio == null){           
            if ( countReservedMemory() <= ) {
                return .
            }
            
            if ( .equals() )
                return .;
            else if ( .equals() ) 
                return .;               
        }
        
        boolean isAllowed = 
                isAllowedToExecute(token,memoryAllowedSize,allowedRatio);
        
        pipeline = .get(token);
        if ( pipeline != null)
            .setPipeline(pipeline); 
        
        if ( !isAllowed ) {
            if ( .equals() )
                return .;
            else if ( .equals() ) 
                return .;    
        }
    }

    
    
Determine if an application can execute based on its policy metric and method.
    protected boolean isAllowedToExecute(String tokenLong memoryAllowedSize
            Double allowedRatiothrows Exception{          
        
        long currentMemory = usedMemory();
       
        // First request, needs to calculate the ratio.
        if ( memoryAllowedSize == null ){
            memoryAllowedSize = 
                    ( * allowedRatio.longValue())/100;
            // We must find the allowed size based on the ratio.
            .put(token,memoryAllowedSize);
        } 
        
        if ( memoryAllowedSize > currentMemory) {
            return false;
        }
        // Do we know how much memory is used?
        Long usage = .get(token);
        .put(,token);
        
        // If null, we must execute the task to find how much memory 
        // the app consume.
        if ( usage == null) {
            .put(token,);
            return true;
        }
        
        // Make sure we can get all memory consumed by the application
        Long currentAppUsage = .get(token);
        if ( currentAppUsage == null ) {
            currentAppUsage = 0L;
        }
        
        usage = currentAppUsage + usage;
        
        if ( usage > currentMemory ) return false;
        
        if ( usage > memoryAllowedSize ) return false;
            
        .put(token,usage);
        .addTaskListener(this);
        return true;
    }
   
    
    
Return the total memory required by application which has a policy metric defined.
    private long countReservedMemory(){
        Iterator<Longiterator = .values().iterator();
        long count = 0L;
        while (iterator.hasNext()){
            count += iterator.next(); 
        }  
        return count;
    }
    
    
    
Predict the current memory
    private static long usedMemory(){
        Runtime.getRuntime().gc();
        return Runtime.getRuntime().totalMemory () 
            - Runtime.getRuntime().freeMemory ();
    }    

    
    
Reduce the memory usage count when an application complete its execution.
    public void taskEvent(TaskEvent event) {
        if ( event.getStatus() == .){
        
            String token = .remove(event.attachement());
            if ( token != null ) {
               Long count = .get(token);
               count -= .get(token);
               .put(token,count); 
            }
        }
    }

    
    
Customized Pipeline used to approximate the memory used by an application.
    private static class HeapMemoryRulePipeline extends LinkedListPipeline{
                
        @Override
        public void initPipeline(){
             = new WorkerThreadImpl[1];
            WorkerThreadImpl workerThread = new WorkerThreadImpl(this
                    "HeapMemoryRuleThread"){
                
                @Override
                public void run(){
                    while (true) {
                        try{
                            ReadTask t = 
                                (ReadTask)HeapMemoryRulePipeline.this.getTask();
                            if ( t != null){
                                long current = usedMemory();
                                t.run();    
                                long usage = usedMemory() - current;
                                if ( usage > 0){
                                    String token = 
                                       .get(t);
                                    .put(token,usage);
                                    .remove(token);
                                }                                  
                            }
                        } catch (Throwable t) {
                            SelectorThread.logger().log(.,
                                    "workerThread.httpException",t);
                        }
                    }
                }                              
            };
            workerThread.setPriority();
            [0] = workerThread;
            ++; 
        }  
        
        
        
Start the Pipeline and all associated WorkerThread
        @Override
        public void startPipeline(){
            if (!) {
                [0].start();
                 = true;
            }
        }


        
Stop the Pipeline and all associated WorkerThread
        @Override
        public void stopPipeline(){
            if () {
                [0].terminate();
                 = false;
            }
        }    
        
        
        
Add an object to this pipeline
        @Override
        public synchronized void addTask(Task task) {
            addLast(task);
            notify();
        }    
    }
New to GrepCode? Check out our FAQ X