Wednesday, March 17, 2010

Java Thread Local Usage

    private ThreadLocal tl = new ThreadLocal(){
        protected synchronized Session initialValue() {
            return sessionForBatchLoading;
        }    
    };
    
    private Session sessionForBatchLoading = null;

    private void initializeSession () throws Exception {
        session = SessionFactory.getSession ();
        sessionForBatchLoading = factory.getSession ();
        tl.set(sessionForBatchLoading);
    }

    private void getOrder (int orderId) throws Exception {
        Session tlSession = tl.get ();
        tlSession.getItemFromDBWithId (orderId);
    }

*Session is not thread safe .


    private void startThreads (int threadCount) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);

        for (int i = 0; i < threadCount; i++) {
            FetchTask task =  new FetchTask ();
            executor.submit (task);
        }

         executor.shutdown ();
    }

No comments:

Post a Comment