How to initialize JRockit MBean tree - java

I have the following code that just lists all MBean names found in platform MBean server:
public static void main(final String[] args) throws Exception {
initJMX();
}
#SuppressWarnings("unchecked")
private static void initJMX() throws IOException, MalformedURLException, AttributeNotFoundException,
InstanceNotFoundException, MalformedObjectNameException, MBeanException, ReflectionException,
NullPointerException {
JMXConnector jmxc = null;
final Map<String, String> map = new HashMap<String, String>();
jmxc = JMXConnectorFactory.newJMXConnector(createConnectionURL("localhost", 7788), map);
jmxc.connect();
final MBeanServerConnection connection = jmxc.getMBeanServerConnection();
final String[] domains = connection.getDomains();
for (final String domain : domains) {
final Set<ObjectName> mBeans = connection.queryNames(new ObjectName(domain + ":*"), null);
for (final ObjectName name : mBeans) {
System.out.println(name);
}
}
jmxc.close();
}
When I try to run this code with JRockit 1.5.0_4.0.1 with the following parameters:
-Xmanagement:ssl=false,authenticate=false,autodiscovery=false,port=7788
And it prints the following list:
[INFO ][mgmnt ] Remote JMX connector started at address localhost:7788
[INFO ][mgmnt ] Local JMX connector started
com.oracle.jrockit:type=FlightRecorder
java.util.logging:type=Logging
JMImplementation:type=MBeanServerDelegate
java.lang:type=Compilation
java.lang:type=GarbageCollector,name=Garbage collection optimized for throughput Young Collector
java.lang:type=MemoryManager,name=Class Manager
java.lang:type=MemoryPool,name=ClassBlock Memory
java.lang:type=GarbageCollector,name=Garbage collection optimized for throughput Old Collector
java.lang:type=Runtime
java.lang:type=MemoryPool,name=Nursery
java.lang:type=ClassLoading
java.lang:type=Threading
java.lang:type=MemoryPool,name=Class Memory
java.lang:type=OperatingSystem
java.lang:type=Memory
java.lang:type=MemoryPool,name=Old Space
But if I put a breakpoint before a call to initJMX method and at that point connect to that JVM with JRMC, then JRMC displays much more MBeans and also after I continue program execution it also prints a different list which contains more JRockit related MBeans:
[INFO ][mgmnt ] Remote JMX connector started at address T500W7AAD:7788
[INFO ][mgmnt ] Local JMX connector started
com.oracle.jrockit:type=FlightRecorder
oracle.jrockit.management:type=PerfCounters
oracle.jrockit.management:type=Compilation
oracle.jrockit.management:type=Log
oracle.jrockit.management:type=Profiler
oracle.jrockit.management:type=MemLeak
oracle.jrockit.management:type=JRockitConsole
oracle.jrockit.management:type=GarbageCollector
oracle.jrockit.management:type=Runtime
oracle.jrockit.management:type=Threading
oracle.jrockit.management:type=DiagnosticCommand
oracle.jrockit.management:type=Memory
java.util.logging:type=Logging
JMImplementation:type=MBeanServerDelegate
java.lang:type=Compilation
java.lang:type=GarbageCollector,name=Garbage collection optimized for throughput Young Collector
java.lang:type=MemoryManager,name=Class Manager
java.lang:type=MemoryPool,name=ClassBlock Memory
java.lang:type=GarbageCollector,name=Garbage collection optimized for throughput Old Collector
java.lang:type=Runtime
java.lang:type=MemoryPool,name=Nursery
java.lang:type=ClassLoading
java.lang:type=Threading
java.lang:type=MemoryPool,name=Class Memory
java.lang:type=OperatingSystem
java.lang:type=Memory
java.lang:type=MemoryPool,name=Old Space
Is there a way to say JRockit to initialize those beans automatically on JVM startup without a need of explicit JRMC connection? The problem is that I'm trying to write some code that reuses some of those MBeans, but they are not available until I connect with JRMC.
UPDATE: This seems to be JRockit jdk1.5.0_4.0.1 problem. As same code works as expected on JRockit jdk6.0_4.1.0.

This appears to be a problem with the Windows version of JRockit that I use:
java version "1.5.0_24"
Java(TM) Platform, Standard Edition for Business (build 1.5.0_24-b02)
Oracle JRockit(R) (build R28.0.1-21-133393-1.5.0_24-20100512-2131-windows-x86_64, compiled mode)
Same code works as expected on latest JRockit for JDK 1.6.0 on Windows:
java version "1.6.0_29"
Java(TM) SE Runtime Environment (build 1.6.0_29-b11)
Oracle JRockit(R) (build R28.2.2-7-148152-1.6.0_29-20111221-2104-windows-x86_64, compiled mode)
and on the same JRockit version, but for Linux:
java version "1.5.0_24"
Java(TM) Platform, Standard Edition for Business (build 1.5.0_24-b02)
Oracle JRockit(R) (build R28.1.0-123-138454-1.5.0_24-20101014-1350-linux-x86_64, compiled mode)

try your query with object names of *:*
final Set<ObjectName> mBeans = connection.queryNames(new ObjectName("*:*"),
Maybe there is more than one MBeanServer in the JRockit that the JRMC finds all MBeanServers.

Related

Java Runtime Exception: USB to RS232 serial comm using jssc maven package

I developed a desktop application using JavaFX and Maven dependency manager. I used Java 8 and JSSC package to communicate with a serial port using USB. That time it was working as I expected. But now when I try to run the project, it's showing me the following exception and shutdown the app.
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000007110b5db, pid=9452, tid=0x0000000000002384
#
# JRE version: OpenJDK Runtime Environment (8.0_332-b08) (build 1.8.0_332-b08)
# Java VM: OpenJDK 64-Bit Server VM (25.332-b08 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# C [jSSC-2.8_x86_64.dll+0xb5db]
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# C:\Users\Sincos\Desktop\HomeOffice\Java\FDH-Relay\hs_err_pid9452.log
#
# If you would like to submit a bug report, please visit:
# https://github.com/corretto/corretto-8/issues/
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
Process finished with exit code 1
When I start the process, the following function is triggered.
public void open() throws SerialPortException {
port = new SerialPort(comPort);
port.openPort();//Open serial port
port.setParams(Integer.parseInt(baudRate), Integer.parseInt(dataSize), Integer.parseInt(stopBit), Integer.parseInt(parity));
port.addEventListener(new SerialPortEventListener() {
public void serialEvent(SerialPortEvent serialPortEvent) {
try {
int length = 0;
buffer= port.readString();
if (buffer != null){
length = buffer.length();
}
for (int i=0;i<length;i++){
queue.add((int)buffer.charAt(i));
}
} catch (SerialPortException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
I set up the port, baudRate, dataSize, stopBit, and parity.
Here is the maven dependency that I used in the project.
<!-- https://mvnrepository.com/artifact/org.scream3r/jssc -->
<dependency>
<groupId>org.scream3r</groupId>
<artifactId>jssc</artifactId>
<version>2.8.0</version>
</dependency>
Here is the other variable and constructor where I initialize the data.
String comPort;
public static Queue<Integer> queue = new LinkedList<>();
SerialPort port;
java.lang.String buffer;
String baudRate, dataSize, stopBit, parity;
public ExternalSerialConnection(String comport, String baudRate, String dataSize, String stopBit, String parity) {
this.comPort=comport;
this.baudRate=baudRate;
this.stopBit=stopBit;
this.dataSize=dataSize;
this.parity=parity;
}
Is there anyone who can help me to solve this issue?

java.rmi.NoSuchObjectException: no such object exception

There have been acouple of questions about this already, but their answers suggest that the exported object has been GC'd on the server side and that is cousing the problems. However it seems like that this is not the issue here.
Mentioned exception is thrown only on single machine:
PRETTY_NAME="Debian GNU/Linux 8 (jessie)"
NAME="Debian GNU/Linux"
VERSION_ID="8"
VERSION="8 (jessie)"
With java:
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
This happend on the same machine with OpenJDK 7something as well.
According to other answers I am supposed to keep a strong reference to handling objects. I am doing it now, so what more can be done?
The same code works on windows as well as on a different remote linux machine with java 7.
Any ideas why?
I have implemented some finalizers to the connected classes, but none of them are called.
As suggested I am using static references. As for me there is no way get exported object GC enligible. Exception is thrown on remote method invocation right after object lookup.
Piece of class
public class Client{
//some fields
private final int RMI_PORT;
private static SearchTestServiceImpl searchTestService;
private static Remote stub;
private Registry registry;
//and starting service
public void startService() throws RemoteException {
createRegistry();
searchTestService = new SearchTestServiceImpl(name);
stub = UnicastRemoteObject.exportObject(searchTestService, RMI_PORT + 1);
registry.rebind(SearchTestService.class.getName(), stub);
log.info("Binding {} to port {}", SearchTestService.class.getName(), RMI_PORT + 1);
}
private void createRegistry() throws RemoteException {
log.info("Starting RMI registry on port {}", RMI_PORT);
registry = LocateRegistry.createRegistry(RMI_PORT);
}
(...)
}
And bootstrapping code
public class Bootstrap {
private Logger log = LoggerFactory.getLogger(Bootstrap.class);
private static Client c;
public static void main(String[] args) throws NumberFormatException,
// some preparations
c = new Client(Integer.valueOf(port), name);
c.startService();
System.gc();
System.runFinalization();
synchronized (c) {
c.wait();
}
}
}
and stacktrace
java.rmi.NoSuchObjectException: no such object in table
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source) ~[na:1.7.0_65]
at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source) ~[na:1.7.0_65]
at sun.rmi.server.UnicastRef.invoke(Unknown Source) ~[na:1.7.0_65]
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(Unknown Source) ~[na:1.7.0_65]
at java.rmi.server.RemoteObjectInvocationHandler.invoke(Unknown Source) ~[na:1.7.0_65]
at com.sun.proxy.$Proxy0.getName(Unknown Source) ~[na:na]
at call to a method of remote lookedup object #getName in this example.
Requested piece of code - lookup and call that throws exception
//somewhere
SearchTestService c = getClient(address); // this returns nice stub
String name = c.getName(); // this is throwing exception
private SearchTestService getClient(String string) throws NumberFormatException, RemoteException, NotBoundException {
String[] parts = string.split(":");
Registry registry = LocateRegistry.getRegistry(parts[0], Integer.parseInt(parts[1]));
SearchTestService client = (SearchTestService) registry.lookup(SearchTestService.class.getName());
return (SearchTestService) client;
}
Console output after running "listening" client side code (with RMI registry)
10:17:55.915 [main] INFO pl.breeze.searchtest.client.Client - Starting RMI registry on port 12097
10:17:55.936 [main] INFO p.b.s.client.SearchTestServiceImpl - Test agent Breeze Dev staging is up and running
10:17:55.952 [main] INFO pl.breeze.searchtest.client.Client - Binding pl.choina.searchtest.remote.SearchTestService to port 12098
And this waits untill manuall shutdown - tested.
NoSuchObjectException
Javadoc:
A NoSuchObjectException is thrown if an attempt is made to invoke a method on an object that no longer exists in the remote virtual machine.
This means that the remote object referred to by the stub you are calling methods on has been unexported, i.e. the stub is 'stale'. The only way that can happen is by unexporting the object, either manually or as a result of GC.
As suggested I am using static references.
No you're not. You need to make the Registry reference static. Otherwise you just form a cycle between Client and Registry that can be garbage-collected all at once.
Why you're calling your server Client is another mystery.
EDIT A few comments:
stub = UnicastRemoteObject.exportObject(searchTestService, RMI_PORT + 1);
There's no need to use a second port here. Just re-use the Registry port.
log.info("Binding {} to port {}", SearchTestService.class.getName(), RMI_PORT + 1);
This is misleading. You've already done both, but what you have done is:
Exported the object on the port, and
Bound the object to a name
in two separate steps.
System.gc();
System.runFinalization();
Strange things to be doing here, or indeed anywhere.
synchronized (c) {
c.wait();
}
This isn't reliable. You don't really need anything here, as RMI should keep the JVM open as long as it has exported remote objects, but you could do what the Registry does:
while (true)
{
Thread.sleep(Integer.MAX_VALUE);
}
with the appropriate exception handling.
I can't reproduce your problem, but then I'm on Windows 7.

Performance tuning for Netty 4.1 on linux machine

I am building a messaging application using Netty 4.1 Beta3 for designing my server and the server understands MQTT protocol.
This is my MqttServer.java class that sets up the Netty server and binds it to a specific port.
EventLoopGroup bossPool=new NioEventLoopGroup();
EventLoopGroup workerPool=new NioEventLoopGroup();
try {
ServerBootstrap boot=new ServerBootstrap();
boot.group(bossPool,workerPool);
boot.channel(NioServerSocketChannel.class);
boot.childHandler(new MqttProxyChannel());
boot.bind(port).sync().channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally {
workerPool.shutdownGracefully();
bossPool.shutdownGracefully();
}
}
Now I did a load testing of my application on my Mac having the following configuration
The netty performance was exceptional. I had a look at the jstack while executing my code and found that netty NIO spawns about 19 threads and none of them seem to be stuck up waiting for channels or something else.
Then I executed my code on a linux machine
This is a 2 core 15GB machine. The problem is that the packet sent by my MQTT client seems to take a long time to pass through the netty pipeline and also on taking jstack I found that there were 5 netty threads and all were stuck up like this
."nioEventLoopGroup-3-4" #112 prio=10 os_prio=0 tid=0x00007fb774008800 nid=0x2a0e runnable [0x00007fb768fec000]
java.lang.Thread.State: RUNNABLE
at sun.nio.ch.EPollArrayWrapper.epollWait(Native Method)
at sun.nio.ch.EPollArrayWrapper.poll(EPollArrayWrapper.java:269)
at sun.nio.ch.EPollSelectorImpl.doSelect(EPollSelectorImpl.java:79)
at sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:86)
- locked <0x00000006d0fdc898> (a
io.netty.channel.nio.SelectedSelectionKeySet)
- locked <0x00000006d100ae90> (a java.util.Collections$UnmodifiableSet)
- locked <0x00000006d0fdc7f0> (a sun.nio.ch.EPollSelectorImpl)
at sun.nio.ch.SelectorImpl.select(SelectorImpl.java:97)
at io.netty.channel.nio.NioEventLoop.select(NioEventLoop.java:621)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:309)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:834)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137)
at java.lang.Thread.run(Thread.java:745)
Is this some performance issue related to epoll on linux machine. If yes then what changes should be made to netty configuration to handle this or to improve performance.
Edit
Java Version on local system is :-
java version "1.8.0_40"
Java(TM) SE Runtime Environment (build 1.8.0_40-b27)
Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode)
Java version on AWS is :-
openjdk version "1.8.0_40-internal"
OpenJDK Runtime Environment (build 1.8.0_40-internal-b09)
OpenJDK 64-Bit Server VM (build 25.40-b13, mixed mode)
Here are my findings from implementing a very simple HTTP → Kafka forklift:
Consider switching to EpollEventLoopGroup.
Simple autoreplace NioEventLoopGroup → EpollEventLoopGroup gave me 30% perfomance boost.
Removing LoggingHandler from the pipeline (if you have any) can give you a CPU usage drop (in my case CPU the drop was almost unbelievable: 80%).
Play around with the worker threads to see if this improves performance. The standard constructor of NioEventLoopGroup() creates the default amount of event loop threads:
DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
"io.netty.eventLoopThreads", Runtime.getRuntime().availableProcessors() * 2));
As you can see you can pass io.netty.eventLoopThreads as a launch argument but I usually don't do that.
You can also pass the amount of threads in the constructor of NioEventLoopGroup().
In our environment we have netty servers that accept communication from hundreds of clients. Usually one boss thread to handle the connections is enough. The worker thread amount needs to be scaled though. We use this:
private final static int BOSS_THREADS = 1;
private final static int MAX_WORKER_THREADS = 12;
EventLoopGroup bossGroup = new NioEventLoopGroup(BOSS_THREADS);
EventLoopGroup workerGroup = new NioEventLoopGroup(calculateThreadCount());
private int calculateThreadCount() {
int threadCount;
if ((threadCount = SystemPropertyUtil.getInt("io.netty.eventLoopThreads", 0)) > 0) {
return threadCount;
} else {
threadCount = Runtime.getRuntime().availableProcessors() * 2;
return threadCount > MAX_WORKER_THREADS ? MAX_WORKER_THREADS : threadCount;
}
}
So in our case we use just one boss thread. The worker threads depend on if a launch argument has been given. If not then use cores * 2 but never more than 12.
You will have to test yourself though what numbers work best for your environment.

Netty 4, Java 7 JVM SIGSEGV crash under load

I have a binary protocol implemented with Netty that is being performance tested, and the JVM is crashing with the below report. I do not know how to repeat the crash, but it does happen regularly and only under heavy load. I have the following dependencies:
java 7.0_51-b13
netty 4.0.18_Final
fedora 20
It appears that the array copy is occurring in the nioEventLoopGroup thread. The performance test I am running is sending a large number of small messages over ~50 TCP connections. Where a large number is about 1 million 200 byte messages per connection. Each message has 2 response messages sent back.
This is what I am doing to create Netty:
Bootstrap:
m_serverBootstrap.group(m_eventLoopGroup)
.channel(NioServerSocketChannel.class)
.localAddress(m_config.getSmppPort())
.childAttr(InternalAttributeKeys.METRICS, m_metricRegistry)
.childHandler(new CustomServerChannelInitializer());
m_serverBindChannelFuture = m_serverBootstrap.bind().sync();
CustomerServerChannelInitializer
protected void initChannel(SocketChannel ch) throws Exception {
log.info("initChannel(SocketChannel ch) {} {} ",ch,this);
ch.pipeline()
.addLast(new IpFilterHandler())
.addLast(new ProtocolEncoder())
.addLast(new LengthFieldBasedFrameDecoder(4 * 1024, 0, 4, -4, 0))
.addLast(new ProtocolDecoder())
.addLast(new WindowingHandler())
.addLast(new SequenceNumberAssignmentHandler())
.addLast("idleState", new IdleStateHandler(idleTime, idleTime, idleTime))
.addLast("idleDisconnect", m_idleDisconnectHandler)
.addLast("auth", m_authHandler)
.addLast("catchall", new CatchallHandler(false));
ch.config().setAllocator(PooledByteBufAllocator.DEFAULT);
ch.config().setAutoRead(true);
log.info("finished initChannel(SocketChannel ch) {} {} ",ch,this);
}
After initial connection the pipeline is altered again in the authHandler
#Override
protected void channelRead0(ChannelHandlerContext ctx, CustomMessage msg) throws Exception {
ResponseMessage response = auth(msg,ctx);
ctx.pipeline().replace("auth", "msghandler", new MessageHandler());
ctx.pipeline().replace("idleState", "inactivityPeriod", new IdleStateHandler());
ctx.pipeline().addAfter("msghandler", "responsehandler", new ResponseHandler());
ctx.pipeline().addAfter("responsehandler", "heartbeat", new HeartbeatHandler());
ctx.pipeline().addAfter("heartbeat", "disconnect", new DisconnectHandler());
ctx.channel().closeFuture().addListener(new CleanupChannelFutureListener(ctx));
ctx.writeAndFlush(response);
}
jvm report. I have a detailed report if it helps http://pastebin.com/RV0KqPMf
If the JMX threads in the detailed report are bothering you, I can and have reproduced the issue without them.
#
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007ffa9eb18eaa, pid=1731, tid=140710808540928
#
# JRE version: Java(TM) SE Runtime Environment (7.0_51-b13) (build 1.7.0_51-b13)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (24.51-b03 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# v ~StubRoutines::jbyte_disjoint_arraycopy
#
# Core dump written. Default location: /home/user/dir/core or core.1731
#
# If you would like to submit a bug report, please visit:
# http://bugreport.sun.com/bugreport/crash.jsp
#
--------------- T H R E A D ---------------
Current thread (0x00007ff9fc06f800): JavaThread "nioEventLoopGroup-2-12" [_thread_in_Java, id=1912, stack(0x00007ff9c9b25000,0x00007ff9c9c26000)]
siginfo:si_signo=SIGSEGV: si_errno=0, si_code=1 (SEGV_MAPERR), si_addr=0x00007ff987df7715
What is the best way to find out what is causing this SIGSEGV in the JVM?
This is definitely a Netty bug.
Netty 4.x heavily uses Unsafe API - Oracle JDK internal API that allows raw memory access.
See PlatformDependent0.java from Netty sources.
The crash log tells that the problem happens inside Unsafe.copyMemory call where the target is a byte[] array in Java Heap young generation, and the source points to an unmapped memory region. Most likely this is caused by an attempt to get bytes from a native buffer that has been previously released. There are no sanity checks inside Unsafe API, so any misuse typically ends up with a JVM crash.
Upgrading from Netty 4.0.18.Final to 4.0.20.Final fixed this issue.

Accessing Tomcat Monitors using Java code

I am very new to JMX. I am trying to log the tomcat statistics like threads used, cache, sessions and other standard values. I am trying to achieve this with java code.
I have done the following things as of now. (I am trying to access the values of a local tomcat 6.0 monitor on windows)
1)I have added the following options in the catalina.bat
set CATALINA_OPTS=-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9004 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false
After that I restarted the tomcat server.
2) Then I wrote the following code.
package com.ss.fg;
import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;
public class SystemConfigManagement
{
static MBeanServer connection = ManagementFactory.getPlatformMBeanServer();
public static void main(String[] args) throws Exception {
getActiveSession();
}
public static void getActiveSession()throws Exception
{
ObjectName name=new ObjectName("Catalina:type=Manager,path=/MMDisplay,host=localhost");
String attrValue = ManagementFactory.getPlatformMBeanServer().getAttribute(name, "activeSessions").toString();
System.out.println(attrValue);
}
}
I even tried context instead of path.
I am getting the following exception
Exception in thread "main" javax.management.InstanceNotFoundException: Catalina:type=Manager,path=/MMDisplay,host=localhost
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getMBean(Unknown Source)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getAttribute(Unknown Source)
at com.sun.jmx.mbeanserver.JmxMBeanServer.getAttribute(Unknown Source)
at com.softsmith.floodgates.SystemConfigManagement.getActiveSession(SystemConfigManagement.java:15)
at com.softsmith.floodgates.SystemConfigManagement.main(SystemConfigManagement.java:10)
How can I resolve this issue?
Should I add Some jar files, or should I do some other settings..
Please help
When using
MBeanServer connection = ManagementFactory.getPlatformMBeanServer();
you are actually connectiong to the MBean-Server of the JVM running your program, not to that of your tomcat-instance, so it doesn't know of the Catalina-MBeans.
To establish a connection to a remote jvm try something like:
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://servername:9999/jmxrmi");
JMXConnector connector = JMXConnectorFactory.connect(url);
connector.connect();
MBeanServerConnection server = connector.getMBeanServerConnection();
//do work here
ObjectName name = new ObjectName("Catalina:type=Manager,path=/manager,host=localhost");
String attrValue = mb.getAttribute(name, "activeSessions").toString();
System.out.println(attrValue);
//..and don't forget to close the connection
connector.close();
If the error is still there make sure you are using the correct object-name.
When i using
MBeanServer connection = ManagementFactory.getPlatformMBeanServer();
i am actually connectiong to the MBean-Server of the JVM running my program, not to that of my tomcat-instance, so it doesn't know of the Catalina-MBeans.
so i try to connected remotly to jmx but have error like this :
java.io.IOException: Failed to retrieve RMIServer stub: javax.naming.CommunicationException [Root exception is java.rmi.ConnectIOException: error during JRMP connection establishment; nested exception is....
and now i solve :
for first i added catalina-jmx-remote.jar to TOMCAT_HOME/lib directory of Tomcat and then configure the listener on server.xml i added the following
snippet under the tag :
<Listener className="org.apache.catalina.mbeans.JmxRemoteLifecycleListener" rmiRegistryPortPlatform="10001" rmiServerPortPlatform="10002" useLocalPorts="true" />
and finally i set the following sentence in my catalina.bat :
JAVA_OPTS="$JAVA_OPTS -Djava.rmi.server.hostname=localhost -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"

Categories