Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

2010-05-29

Eclipse tip: Choose editor from the "Open Resource" dialog

Eclipse 3.5 added the option to choose which editor to use when opening a file from the Open Resource dialog:
The Open Resource dialog with option to choose editor

It's useful when a file type is associated with an external editor, but one has a need of finding it in Eclipse to work with e.g. version control.

2009-05-03

Java app to send geocaching data to your Nokia phone

I have documented a small java app that's useful for me that allows me to send geocaching information from geocaching.com to Nokia phones. See http://fornwall.net/landmarksender/ for more information.

2008-08-04

Servlet to create java heap dumps

To create a heap dump for analyzing memory usage one needs to use non-portable API:s. This is example code using suns HotSpotDiagnosticMXBean, but using reflection to avoid compile-time dependency on the sun class library:
public class HeapDumpServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
File tmpFile = File.createTempFile("heapdump", ".hprof");
try {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
// use reflection to avoid compile time dependency on sun classes
String className = "com.sun.management.HotSpotDiagnosticMXBean";
Class diagClass = Class.forName(className);
Object diagBean = ManagementFactory.newPlatformMXBeanProxy(server,
"com.sun.management:type=HotSpotDiagnostic", diagClass);
Method dumpHeapMethod = diagClass.getMethod("dumpHeap", String.class, boolean.class);
dumpHeapMethod.invoke(diagBean, tmpFile.getAbsolutePath(), true);
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename=heapdump.hprof");
IOUtils.copy(new FileInputStream(tmpFile), response.getOutputStream());
} catch (Exception e) {
response.setContentType("text/plain");
response.getWriter().println("ERROR: " + e.getMessage() + "\n" + ExceptionUtils.getFullStackTrace(e));
} finally {
tmpFile.delete();
}
}

}

Monitoring java threads programmatically

Using the java.lang.management package introduced in java 1.5 one may monitor some aspects of the threads of a java process:
  • Find all active threads and get their stack traces
  • Find deadlocked threads
  • Find out what lock a thread is waiting for (and which thread owns it)
  • (Optional, depending on JVM): Monitor thread contention - how many times and for how long have each thread waited or blocked
  • (Optional, depending on JVM): Measure thread CPU time (and how much of that time was spent in user mode)
The code to do this looks as follows:
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
if (threadBean.isThreadCpuTimeSupported())
threadBean.setThreadCpuTimeSupported(true);
if (threadBean.isThreadContentionMonitoringSupported())
threadBean.setThreadContentionMonitoringEnabled(true);

out.println("There are " + threadBean.getThreadCount() +
" threads of which " + threadBean.getDaemonThreadCount() +
" are daemons.");

ThreadInfo[] infos
= threadBean.getThreadInfo(threadBean.getAllThreadIds(), Integer.MAX_VALUE);

for (ThreadInfo info : infos) {
out.println("Thread(id=" + info.getThreadId() + "): " +
info.getThreadName() + ":");

out.println("\tState: " + info.getThreadState());
if (info.getLockOwnerId() != null)
out.println("\tWaiting on lock " + info.getLockName() + " owned by " + info.getLockOwnerId());

if (info.getBlockedTime() != -1) {
out.println("\tBlocked time: " + (info.getBlockedTime() / 1000.) + " seconds during " +
info.getBlockedCount() + " blocks");
out.println("\tWaited time: " + (info.getWaitedTime() / 1000.) + " seconds during " +
info.getWaitedCount() + " blocks");
}

out.println("\tStack trace:");
for (int j = 0; j < threadInfo.getStackTrace().length; j++) {
StackTraceElement e = threadInfo.getStackTrace()[j];
out.println(e.getClassName() + "#" + e.getMethodName() + ":" + e.getLineNumber());
}
}

2008-08-02

Java thread safety: Memory Consistency Properties

From the words-to-live-by department (or, the java.util.concurrent javadoc):

Chapter 17 of the Java Language Specification defines the happens-before relation on memory operations such as reads and writes of shared variables. The results of a write by one thread are guaranteed to be visible to a read by another thread only if the write operation happens-before the read operation. The synchronized and volatile constructs, as well as the Thread.start() and Thread.join() methods, can form happens-before relationships. In particular:
  • Each action in a thread happens-before every action in that thread that comes later in the program's order.
  • An unlock (synchronized block or method exit) of a monitor happens-before every subsequent lock (synchronized block or method entry) of that same monitor. And because the happens-before relation is transitive, all actions of a thread prior to unlocking happen-before all actions subsequent to any thread locking that monitor.
  • A write to a volatile field happens-before every subsequent read of that same field. Writes and reads of volatile fields have similar memory consistency effects as entering and exiting monitors, but do not entail mutual exclusion locking.
  • A call to start on a thread happens-before any action in the started thread.
  • All actions in a thread happen-before any other thread successfully returns from a join on that thread.


The methods of all classes in java.util.concurrent and its subpackages extend these guarantees to higher-level synchronization. In particular:
  • Actions in a thread prior to placing an object into any concurrent collection happen-before actions subsequent to the access or removal of that element from the collection in another thread.
  • Actions in a thread prior to the submission of a Runnable to an Executor happen-before its execution begins. Similarly for Callables submitted to an ExecutorService.
  • Actions taken by the asynchronous computation represented by a Future happen-before actions subsequent to the retrieval of the result via Future.get() in another thread.
  • Actions prior to "releasing" synchronizer methods such as Lock.unlock, Semaphore.release, and CountDownLatch.countDown happen-before actions subsequent to a successful "acquiring" method such as Lock.lock, Semaphore.acquire, Condition.await, and CountDownLatch.await on the same synchronizer object in another thread.
  • For each pair of threads that successfully exchange objects via an Exchanger, actions prior to the exchange() in each thread happen-before those subsequent to the corresponding exchange() in another thread.
  • Actions prior to calling CyclicBarrier.await happen-before actions performed by the barrier action, and actions performed by the barrier action happen-before actions subsequent to a successful return from the corresponding await in other threads.