0

i am using log4j in my multi threaded web service. the problem is where do i close the logger? i have tryed to close it at the end of the program but i have other threads using it.

private Logger logger = Logger.getLogger(NewWebServiceFromWSDL.class.getName());
BasicConfigurator.configure();

Thread switchThread = new Thread(new Runnable() {
        @Override
        public void run() {
            logger.info("bla");
            LogManager.shutdown();
        }
    });
    switchThread.start();
susparsy
  • 1,016
  • 5
  • 22
  • 38
  • Possible duplicate of [How to log within shutdown hooks with Log4j2?](https://stackoverflow.com/questions/17400136/how-to-log-within-shutdown-hooks-with-log4j2) – kemsky Jul 04 '18 at 17:17

1 Answers1

0

You can use a CyclicBarrier. Once all threads are finished then can trigger a job to close the Logger.

Following is a sample code [Taken from another site and modified]:

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.logging.Level;
import java.util.logging.Logger;


public class CyclicBarrierExample {

    //Runnable task for each thread
    private static class Task implements Runnable {

        private CyclicBarrier barrier;

        public Task(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " is waiting on barrier");
                barrier.await();
                System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
            } catch (InterruptedException ex) {
                Logger.getLogger(CyclicBarrierExample.class.getName()).log(Level.SEVERE, null, ex);
            } catch (BrokenBarrierException ex) {
                Logger.getLogger(CyclicBarrierExample.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void main(String args[]) {

        //creating CyclicBarrier with 3 parties i.e. 3 Threads needs to call await()
        final CyclicBarrier cb = new CyclicBarrier(3, new Runnable(){
            @Override
            public void run(){
                //This task will be executed once all thread reaches barrier
                LogManager.shutdown();
            }
        });

        //starting each of thread
        Thread t1 = new Thread(new Task(cb), "Thread 1");
        Thread t2 = new Thread(new Task(cb), "Thread 2");
        Thread t3 = new Thread(new Task(cb), "Thread 3");

        t1.start();
        t2.start();
        t3.start();

    }
}
Lokesh
  • 7,810
  • 6
  • 48
  • 78