/******************************************************************************* * Copyright (c) 2007, 2010 Association for Decentralized Information Management * in Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation *******************************************************************************/ package org.simantics.utils.threads.logger; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class ThreadLogger implements IThreadLogger { final private static ITask DUMMY = () -> {}; public static String LOG_FILE = "threads.log"; public static boolean LOG = false; static Object loggerCreationLock = new Object(); static ThreadLogger logger = null; DataOutput log; public ThreadLogger() { if(LOG) { try { FileOutputStream stream = new FileOutputStream(LOG_FILE); log = new DataOutputStream(stream); } catch (FileNotFoundException e) { e.printStackTrace(); } } } public static ThreadLogger getInstance() { if(logger == null) { synchronized (loggerCreationLock) { if(logger == null) logger = new ThreadLogger(); } } return logger; } public class Task implements ITask { String name; long beginTime; long endTime; long threadId; public Task(String name) { this.name = name; this.threadId = Thread.currentThread().getId(); this.beginTime = System.nanoTime(); } @Override public void finish() { this.endTime = System.nanoTime(); if(LOG && log != null) { try { synchronized(log) { log.writeUTF(name); log.writeLong(threadId); log.writeLong(beginTime); log.writeLong(endTime); } } catch(IOException e) { e.printStackTrace(); } } } } @Override public ITask begin(String taskName) { return new Task(taskName); } final public static ITask task(Object taskName) { if(LOG) return getInstance().begin(taskName.toString()); else return DUMMY; } }