使用hibernate的程序不会终止 [英] program using hibernate does not terminate

查看:80
本文介绍了使用hibernate的程序不会终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Hibernate创建了一个程序。

程序到达主函数结束,但程序正在运行。



不知道是否在 SessionFactory 使用Hibernate Version 4.x配置时发生。



是如何配置错误?




manual1_1_first_hibernate_apps.java
$ b

  public static void main(String [] args){

args [0] =list;
if(args.length< = 0){
System.err.println(没有给出响应);
return;
}

manual1_1_first_hibernate_apps mgr = new manual1_1_first_hibernate_apps();

if(args [0] .equals(store)){
mgr.createAndStoreEvent(My Event,new Date());

else if(args [0] .equals(list)){
mgr。< Event> listEvents()。stream()
.map(e - >Event:+ e.getTitle()+Time:+ e.getDate())
.forEach(System.out :: println);
}
Util.getSessionFactory()。close();
}

私人< T>列表与LT; T> listEvents(){
Session session = Util.getSessionFactory()。getCurrentSession();
session.beginTransaction();
列表< T> events = Util.autoCast(session.createQuery(from Event).list());
session.getTransaction()。commit();
返回事件;
}

Util.java

  private static final SessionFactory sessionFactory; 
$ b / **
*建立一个SessionFactory
* /
static {
try {
//从hibernate.cfg创建SessionFactory .xml

//低于4.x的hibernate版本如下
//#它成功终止。但buildSessionFactory方法已被弃用。
// sessionFactory = new Configuration()。configure()。buildSessionFactory();

//版本4.3及更高版本
//#它不终止。我手动终止。
Configuration configuration = new Configuration()。configure();
StandardServiceRegistry serviceRegistry =
StandardServiceServiceRegistryBuilder()。applySettings(configuration.getProperties())。build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
catch(Throwable ex){
//确保您记录异常,因为它可能被吞噬
System.err.println(初始化SessionFactory创建失败。 + ex);
抛出新的ExceptionInInitializerError(ex);


$ b / **
* @return build SessionFactory
* /
public static SessionFactory getSessionFactory(){
return sessionFactory;
}






以下控制台日志片段当程序终止并使用buildSessionFactory方法。

  2 08,2014 8:42:25 org.hibernate.engine.jdbc.connections .internal.DriverManagerConnectionProviderImpl stop 
INFO:HHH000030:清理连接池[jdbc:derby:D:\Java\jdk1.7.0_03(x86)\db\bin\testdb]

但是如果不使用废弃的buildSessionFactory方法并终止(程序正在运行),则不会出现上述两行。 / b>

ENVIRONMENT:

 
Hibernate 4.3.1
DERBY
JRE 1.8
IntelliJ IDEA 13


解决方案

也许,我解决了这个问题。 / p>

我在调用Util.getSessionFactory()。close()后看到线程转储,名为pool-2-thread-1的线程的状态为TIMED_WAITING(parking)。



以下代码片段转储

 完全线程转储Java HotSpot™64位服务器虚拟机(25.0-b69混合模式):

DestroyJavaVM#16 prio = 5 os_prio = 0 tid = 0x00000000020b9000 nid = 0x3684等待条件[0x0000000000000000]
java.lang.Thread.State:RUNNABLE

pool-2-thread-1#15 prio = 5 os_prio = 0 tid = 0x000000001bc27000 nid = 0x3f0等待条件[0x000000001ce6f000]
java.lang.Thread.State:TIMED_WAITING(parking)
at sun.misc.Unsafe.park(Native Method)
- 停车等待< 0x0000000080be30a0> (java.util.concurrent.locks.AbstractQueuedSynchronizer $ ConditionObject)$ java.util.concurrent.locks.LockSupport.parkNanos处的
(LockSupport.java:215)$ java.util.concurrent.locks处的
。 AbstractQueuedSynchronizer $ ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
at java.util.concurrent.ScheduledThreadPoolExecutor $ DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093)
at java.util.concurrent.ScheduledThreadPoolExecutor $ DelayedWorkQueue。使用java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)获取(ScheduledThreadPoolExecutor.java:809)
在java.util.concurrent.ThreadPoolExecutor.runWorker处获得
(ThreadPoolExecutor.java:1127)
在java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:617)$ b $在java.lang.Thread.run(Thread.java:744)

derby.rawStoreDaemon#14守护进程prio = 5 os_prio = 0 tid = 0x000000001b059000 nid = 0xa3c在Object.wait()[0x000000001ba1f000]
java .lang.Thread.State:TIMED_WAITING(在对象监视器上)
在java.lang.Object.wait(本地方法)
- 等待< 0x00000000805f6190> (a org.apache.derby.impl.services.daemon.BasicDaemon)
at org.apache.derby.impl.services.daemon.BasicDaemon.rest(未知来源)
- 锁定< 0x00000000805f6190> (org.apache.derby.impl.services.daemon.BasicDaemon)
at org.apache.derby.impl.services.daemon.BasicDaemon.run(Unknown Source)
at java.lang.Thread .run(Thread.java:744)

Timer-0#13守护进程prio = 5 os_prio = 0 tid = 0x000000001b08e800 nid = 0x2160 Object.wait()[0x000000001b6af000]
java.lang.Thread.State:WAITING(在对象监视器上)
在java.lang.Object.wait(本地方法)
- 等待< 0x0000000080608118> (java.util.TaskQueue)
在java.lang.Object.wait(Object.java:502)
在java.util.TimerThread.mainLoop(Timer.java:526)
- 锁定< 0x0000000080608118> (a java.util.TaskQueue)
在java.util.TimerThread.run(Timer.java:505)

我认为原因是由buildSessionFactory方法创建的线程名为pool-2-thread-1。



buildSessionFactory方法,我注意到ServiceRegistry资源还没有发布。



程序通过发布成功终止。



以下代码,我加入。



Util.java

  configuration.setSessionFactoryObserver(
SessionFactoryObserver(){
@Override
public void sessionFactoryCreated(SessionFactory factory){}
@Override
public void sessionFactoryClosed(SessionFactory factory){
((StandardServiceRegistryImpl)serviceRegistry).destroy() ;
}
}
);

谢谢。


I created a program using Hibernate.

The program reaches the main function end, nevertheless the program is running.

I wonder if it happens when SessionFactory is configured using Hibernate Version 4.x.

Is the way to configure wrong?


manual1_1_first_hibernate_apps.java

public static void main(String[] args) {

    args[0] ="list";
    if (args.length <= 0) {
        System.err.println("argement was not given");
        return;
    }

    manual1_1_first_hibernate_apps mgr = new manual1_1_first_hibernate_apps();

    if (args[0].equals("store")) {
        mgr.createAndStoreEvent("My Event", new Date());
    }
    else if (args[0].equals("list")) {
        mgr.<Event>listEvents().stream()
            .map(e -> "Event: " + e.getTitle() + " Time: " + e.getDate())
            .forEach(System.out::println);
    }
    Util.getSessionFactory().close();
}

private <T> List<T> listEvents() {
    Session session = Util.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    List<T> events = Util.autoCast(session.createQuery("from Event").list());
    session.getTransaction().commit();
    return events;
}

Util.java

private static final SessionFactory sessionFactory;

/**
 * build a SessionFactory
 */
static {
    try {
        // Create the SessionFactory from hibernate.cfg.xml

        // hibernate version lower than 4.x are as follows
        // # it successful termination. but buildSessionFactory method is deprecated.
        // sessionFactory = new Configuration().configure().buildSessionFactory();

        // version 4.3 and later
        // # it does not terminate. I manually terminated.
        Configuration configuration = new Configuration().configure();
        StandardServiceRegistry serviceRegistry = 
                new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    }
    catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

/**
 * @return built SessionFactory
 */
public static SessionFactory getSessionFactory() {
    return sessionFactory;
}


The following console log snippets when program terminate and use buildSessionFactory method.

2 08, 2014 8:42:25 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:derby:D:\Java\jdk1.7.0_03(x86)\db\bin\testdb]

but if do not use deprecated buildSessionFactory method and terminated(program is running), the above two lines do not appear.

ENVIRONMENT:

 Hibernate 4.3.1
 DERBY
 JRE 1.8
 IntelliJ IDEA 13

解决方案

maybe, I solved this problem.

I saw the thread dump after Util.getSessionFactory().close() called, a thread named "pool-2-thread-1" state was TIMED_WAITING (parking).

The following snippets dump

Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.0-b69 mixed mode):

"DestroyJavaVM" #16 prio=5 os_prio=0 tid=0x00000000020b9000 nid=0x3684 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"pool-2-thread-1" #15 prio=5 os_prio=0 tid=0x000000001bc27000 nid=0x3f0 waiting on condition [0x000000001ce6f000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000080be30a0> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
    at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093)
    at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:744)

"derby.rawStoreDaemon" #14 daemon prio=5 os_prio=0 tid=0x000000001b059000 nid=0xa3c in Object.wait() [0x000000001ba1f000]
   java.lang.Thread.State: TIMED_WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x00000000805f6190> (a org.apache.derby.impl.services.daemon.BasicDaemon)
    at org.apache.derby.impl.services.daemon.BasicDaemon.rest(Unknown Source)
    - locked <0x00000000805f6190> (a org.apache.derby.impl.services.daemon.BasicDaemon)
    at org.apache.derby.impl.services.daemon.BasicDaemon.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:744)

"Timer-0" #13 daemon prio=5 os_prio=0 tid=0x000000001b08e800 nid=0x2160 in Object.wait() [0x000000001b6af000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x0000000080608118> (a java.util.TaskQueue)
    at java.lang.Object.wait(Object.java:502)
    at java.util.TimerThread.mainLoop(Timer.java:526)
    - locked <0x0000000080608118> (a java.util.TaskQueue)
    at java.util.TimerThread.run(Timer.java:505)

I thought the cause is thread named "pool-2-thread-1" that created by buildSessionFactory method.

As a result of comparing the two buildSessionFactory method, I noticed that ServiceRegistry resources has not released.

Program successfully terminated by releasing it.

The following code, I adding.

Util.java

configuration.setSessionFactoryObserver(
        new SessionFactoryObserver() {
            @Override
            public void sessionFactoryCreated(SessionFactory factory) {}
            @Override
            public void sessionFactoryClosed(SessionFactory factory) {
                ((StandardServiceRegistryImpl) serviceRegistry).destroy();
            }
        }
);

thanks.

这篇关于使用hibernate的程序不会终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆