pypmannetjies
pypmannetjies

Reputation: 31414

Analysing Thread behaviour in Java

I need to draw a graph of write accesses of two concurrently running threads. What is the best way to write a timestamp value pair of these accesses to an array, without interfering with the threads themselves? The queue that is being written to looks like this:

import java.util.concurrent.atomic.AtomicInteger;

class IQueue<T> {
    AtomicInteger head = new AtomicInteger(0);
    AtomicInteger tail = new AtomicInteger(0);
    T[] items = (T[]) new Object[100];

    public void enq(T x) {
        int slot;
        do {
            slot = tail.get();
        } while (! tail.compareAndSet(slot, slot+1));
        items[slot] = x;
    }

    public T deq() throws EmptyException {
        T value;
        int slot;
        do {
            slot = head.get();
            value = items[slot];
            if (value == null)
                throw new EmptyException();
        } while (! head.compareAndSet(slot, slot+1));
        return value;
    }

    public String toString() {
        String s = "";
        for (int i = head.get(); i < tail.get(); i++) {
            s += items[i].toString() + "; ";
        }
        return s;
    }
}

I'd like to record whenever a thread starts/stops writing.

Upvotes: 1

Views: 349

Answers (1)

VonC
VonC

Reputation: 1326556

One possibility would be using BTrace, for dynamically (bytecode) instrumenting classes of a running Java program.
BTrace inserts tracing actions into the classes of a running Java program and hotswaps the traced program classes.

// import all BTrace annotations
import com.sun.btrace.annotations.*;
// import statics from BTraceUtils class
import static com.sun.btrace.BTraceUtils.*;

// @BTrace annotation tells that this is a BTrace program
@BTrace
public class HelloWorld {

    // @OnMethod annotation tells where to probe.
    // In this example, we are interested in entry
    // into the Thread.start() method.
    @OnMethod(
        clazz="java.lang.Thread",
        method="start"
    )
    public static void func() {
        // println is defined in BTraceUtils
        // you can only call the static methods of BTraceUtils
        println("about to start a thread!");
    }
}

Upvotes: 1

Related Questions