Spring + JPA PermGen Out of Memory

时间:2014-05-27 13:33:21

标签: java spring hibernate spring-mvc jpa

EDIT1:28/05/2014

我试图更改驱动程序(mysql-connector-java-5.1.30-bin AND ojdbc7)。

在这两种情况下,内存都泄漏了。例如(使用Java VisualVM)使用ojdbc并查看最近的GC我看到:

oracle.djbc.driver.ClockSource $ ThreadCachingBlockSource $ BlockReleaser isnt" free"来自contextClassLoader

使用Mysql我有同样的问题(使用sql驱动程序)

原始帖子: 只需配置spring和jpa,重新启动应用程序3/4次后,我就会有PermGen Out of Memory。使用Java VisualVM我看到每次重启我都有一个类加载器(开头我有4个类加载器,重启后我有5个等等)。在我的WEB-INB中,我有任何lib。我设置的唯一类是这个(任何jsp和我做逻辑的任何类,只设置spring + jpa)。

我正在使用Tomcat8 + Java 7 SDK:

Bootstrap配置

@SuppressWarnings("unused")
@Order(1)
public class FrameworkBootstrap implements WebApplicationInitializer
{

@Override
public void onStartup(ServletContext container)
        throws ServletException 
{
    container.getServletRegistration("default").addMapping("/resource/*");

    AnnotationConfigWebApplicationContext rootContext =
            new AnnotationConfigWebApplicationContext();
    rootContext.register(RootContextConfiguration.class);
    container.addListener(new ContextLoaderListener(rootContext));

    AnnotationConfigWebApplicationContext webContext =
            new AnnotationConfigWebApplicationContext();
    webContext.register(WebServletContextConfiguration.class);
    ServletRegistration.Dynamic dispatcher = container.addServlet(
            "springWebDispatcher", new DispatcherServlet(webContext)
    );
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
}
}

Servlet配置

@Configuration
@EnableWebMvc
@ComponentScan(
    basePackages = "it.dirimo.site",
    useDefaultFilters = false,
    includeFilters = @ComponentScan.Filter(WebController.class)
)
public class WebServletContextConfiguration extends WebMvcConfigurerAdapter
{
 @Inject ApplicationContext applicationContext;
 @Inject ObjectMapper objectMapper;
 @Inject Marshaller marshaller;
 @Inject Unmarshaller unmarshaller;
 @Inject SpringValidatorAdapter validator;

 @Override
    public void configureMessageConverters(
            List<HttpMessageConverter<?>> converters
    ) {
        converters.add(new ByteArrayHttpMessageConverter());
        converters.add(new StringHttpMessageConverter());
        converters.add(new FormHttpMessageConverter());
        converters.add(new SourceHttpMessageConverter<>());

        MarshallingHttpMessageConverter xmlConverter =
                new MarshallingHttpMessageConverter();
        xmlConverter.setSupportedMediaTypes(Arrays.asList(
                new MediaType("application", "xml"),
                new MediaType("text", "xml"),
                new MediaType("text", "json")
        ));
        xmlConverter.setMarshaller(this.marshaller);
        xmlConverter.setUnmarshaller(this.unmarshaller);
        converters.add(xmlConverter);

        MappingJackson2HttpMessageConverter jsonConverter =
                new MappingJackson2HttpMessageConverter();
        jsonConverter.setSupportedMediaTypes(Arrays.asList(
                new MediaType("application", "json"),
                new MediaType("text", "json")
        ));
        jsonConverter.setObjectMapper(this.objectMapper);
        converters.add(jsonConverter);
    }   

    @Override
    public void configureContentNegotiation(
            ContentNegotiationConfigurer configurer)
    {
        configurer.favorPathExtension(true).favorParameter(false)
                .parameterName("mediaType").ignoreAcceptHeader(false)
                .useJaf(false).defaultContentType(MediaType.APPLICATION_XML)
                .mediaType("xml", MediaType.APPLICATION_XML)
                .mediaType("json", MediaType.APPLICATION_JSON);
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers)
    {
        Sort defaultSort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));
        Pageable defaultPageable = new PageRequest(0, 10, defaultSort);

        SortHandlerMethodArgumentResolver sortResolver =
                new SortHandlerMethodArgumentResolver();
        sortResolver.setSortParameter("paging.sort");
        sortResolver.setFallbackSort(defaultSort);

        PageableHandlerMethodArgumentResolver pageableResolver =
                new PageableHandlerMethodArgumentResolver(sortResolver);
        pageableResolver.setMaxPageSize(100);
        pageableResolver.setOneIndexedParameters(true);
        pageableResolver.setPrefix("paging.");
        pageableResolver.setFallbackPageable(defaultPageable);

        resolvers.add(sortResolver);
        resolvers.add(pageableResolver);
    }

    @Override
    public void addFormatters(FormatterRegistry registry)
    {
        if(!(registry instanceof FormattingConversionService))
        {
            return;
        }

        DomainClassConverter<FormattingConversionService> converter =
                new DomainClassConverter<>((FormattingConversionService)registry);
        converter.setApplicationContext(this.applicationContext);
    }

    @Override
    public Validator getValidator()
    {
        return this.validator;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        super.addInterceptors(registry);

        registry.addInterceptor(new LocaleChangeInterceptor());
    }

    @Bean
    public LocaleResolver localeResolver()
    {
        return new SessionLocaleResolver();
    }

    @Bean
    public ViewResolver viewResolver()
    {
        InternalResourceViewResolver resolver =
                new InternalResourceViewResolver();
        resolver.setViewClass(JstlView.class);
        resolver.setPrefix("/WEB-INF/jsp/view/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Bean
    public RequestToViewNameTranslator viewNameTranslator()
    {
        return new DefaultRequestToViewNameTranslator();
    }
}

根配置

@Configuration
@EnableScheduling
@EnableLoadTimeWeaving
@EnableAsync(
    mode = AdviceMode.PROXY, proxyTargetClass = true,
    order = 1
)
@EnableTransactionManagement(
    mode = AdviceMode.PROXY, proxyTargetClass = true,
    order = 2
)
@EnableJpaRepositories(
    basePackages = "it.dirimo.site.repositories",
    entityManagerFactoryRef = "entityManagerFactoryBean",
    transactionManagerRef = "jpaTransactionManager"
)
@ComponentScan(
    basePackages = "it.dirimo.site",
    excludeFilters =
    @ComponentScan.Filter({Controller.class, ControllerAdvice.class})
)
public class RootContextConfiguration implements AsyncConfigurer, SchedulingConfigurer
{
//private static final Logger log = LogManager.getLogger();

@Inject LoadTimeWeaver loadTimeWeaver;

@Bean
public MessageSource messageSource()
{
    ReloadableResourceBundleMessageSource messageSource =
            new ReloadableResourceBundleMessageSource();
    messageSource.setCacheSeconds(-1);
    messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name());
    messageSource.setBasenames(
            "/WEB-INF/i18n/titles", "/WEB-INF/i18n/messages",
            "/WEB-INF/i18n/errors", "/WEB-INF/i18n/validation"
    );
    return messageSource;
}

@Bean
public LocalValidatorFactoryBean localValidatorFactoryBean()
{
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.setValidationMessageSource(this.messageSource());
    return validator;
}

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor()
{
    MethodValidationPostProcessor processor =
            new MethodValidationPostProcessor();
    processor.setValidator(this.localValidatorFactoryBean());
    return processor;
}

@Bean
public ObjectMapper objectMapper()
{
    ObjectMapper mapper = new ObjectMapper();
    mapper.findAndRegisterModules();
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE,
            false);
    return mapper;
}

@Bean
public Jaxb2Marshaller jaxb2Marshaller()
{
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setPackagesToScan(new String[] { "it.dirimo.site" });
    return marshaller;
}

@Bean
public DataSource fileSearchDataSource()
{
    JndiDataSourceLookup lookup = new JndiDataSourceLookup();
    return lookup.getDataSource("jdbc/DIR");
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
{
    Map<String, Object> properties = new Hashtable<>();
    properties.put("javax.persistence.schema-generation.database.action",
            "none");
    properties.put("hibernate.ejb.use_class_enhancer", "true");

    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabasePlatform("org.hibernate.dialect.Oracle10gDialect");

    LocalContainerEntityManagerFactoryBean factory =
            new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(adapter);
    factory.setDataSource(this.fileSearchDataSource());
    factory.setPackagesToScan("it.dirimo.site.entities");
    factory.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
    factory.setValidationMode(ValidationMode.NONE);
    factory.setLoadTimeWeaver(this.loadTimeWeaver);
    factory.setJpaPropertyMap(properties);
    return factory;
}

@Bean
public PlatformTransactionManager jpaTransactionManager()
{
    return new JpaTransactionManager(
            this.entityManagerFactoryBean().getObject()
    );
}

@Bean
public ThreadPoolTaskScheduler taskScheduler()
{
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setPoolSize(20);
    scheduler.setThreadNamePrefix("task-");
    scheduler.setAwaitTerminationSeconds(60);
    scheduler.setWaitForTasksToCompleteOnShutdown(true);
    return scheduler;
}

@Override
public void configureTasks(ScheduledTaskRegistrar registrar) {
    TaskScheduler scheduler = this.taskScheduler();
    registrar.setTaskScheduler(scheduler);
}

@Override
public Executor getAsyncExecutor() {
    Executor executor = this.taskScheduler();
    return executor;
}
}

1 个答案:

答案 0 :(得分:2)

这是Tomcat / Spring / Hibernate的常见问题,并且通常没有适用于所有方案的明确答案。 最有可能的是,一般的潜在问题是动态类是在每次重新部署时创建的,存储在permgen中,并且类定义永远不会被垃圾收集。这通常不是Spring / Hibernate的直接错误,而是相反&#34;功能&#34; CGLIB和/或Tomcat的类加载器处理。

一些常见的建议:

  • -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled添加到您的tomcat启动选项。

  • 如果这是问题原因,请远离CGLIB。只有某些类型的代理才需要CGLIB。

  • 将您的JDBC jar文件放在{tomcat} / lib中,而不是WEB-INF / lib。

还有很多其他的想法here和互联网,但一般来说,如果你无法解决上述问题,那么唯一的办法是增加你的permgen并计划每次重新部署重启tomcat。

有趣的(根据我自己的经验),这个问题远不是最新的库/服务器/ jdk版本的问题。