isLocked returns wrong value - locking

I'm using Hazelcast for an attempt of distributed locking. The locking seems to work fine but checking if a thread is the owner of a lock or that there even is a lock does not work the way I expect. Please help.
I expect that if I call hazelcastInstance.cpSubsystem.getLock(lockName).isLocked and het true as an answer that I then should be able to unlock it. But the stacktrace shows that it was not locked at all. Even though the check returns true.
I also tried locking on the IMap entry but that had the same result.
fun offer(workItemToOffer: WorkItem, expectedLockState: Boolean = true) {
// Check if the expected state equals to the actual state
val actualLockState = isLocked(workItemToOffer.groupName)
if (expectedLockState != actualLockState) {
log.warn { "offer: '${workItemToOffer.groupName}' should be in the ${if (expectedLockState) "locked" else "unlocked"} state but isn't" }
}
// Release the lock if I have it
if (actualLockState) {
log.info("offer: releasing '${workItemToOffer.groupName}'")
try {
// Release the lock for other instances to work in this same workItem
unlock(workItemToOffer.groupName)
} catch (e: Exception) {
log.error(e) { "offer: error unlocking '${workItemToOffer.groupName}', actualLockState=$actualLockState, expectedLockState=$expectedLockState" }
}
}
}
private fun tryLock(lockName: String) = hazelcastInstance.cpSubsystem.getLock(lockName).tryLock()
private fun unlock(lockName: String) = hazelcastInstance.cpSubsystem.getLock(lockName).unlock()
private fun isLocked(lockName: String) = hazelcastInstance.cpSubsystem.getLock(lockName).isLocked
So the first thing is is that I check if isLocked(). And then if it is locked I do the unlock. But during the unlock I get an exception.
java.lang.IllegalMonitorStateException: Current thread is not owner of the lock!
at com.hazelcast.cp.internal.datastructures.lock.LockService.release(LockService.java:119)
at com.hazelcast.cp.internal.datastructures.lock.operation.UnlockOp.run(UnlockOp.java:45)
at com.hazelcast.cp.internal.operation.unsafe.AbstractUnsafeRaftOp.call(AbstractUnsafeRaftOp.java:67)
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.call(OperationRunnerImpl.java:256)
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:237)
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:452)
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.process(OperationThread.java:166)
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.process(OperationThread.java:136)
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.executeRun(OperationThread.java:123)
at com.hazelcast.internal.util.executor.HazelcastManagedThread.run(HazelcastManagedThread.java:102)
at ------ submitted from ------.()
at com.hazelcast.internal.util.ExceptionUtil.cloneExceptionWithFixedAsyncStackTrace(ExceptionUtil.java:265)
at com.hazelcast.spi.impl.AbstractInvocationFuture.wrapRuntimeException(AbstractInvocationFuture.java:1922)
at com.hazelcast.spi.impl.AbstractInvocationFuture.wrapOrPeel(AbstractInvocationFuture.java:1903)
at com.hazelcast.spi.impl.AbstractInvocationFuture$ExceptionalResult.wrapForJoinInternal(AbstractInvocationFuture.java:1385)
at com.hazelcast.spi.impl.AbstractInvocationFuture.resolveAndThrowForJoinInternal(AbstractInvocationFuture.java:597)
at com.hazelcast.spi.impl.AbstractInvocationFuture.joinInternal(AbstractInvocationFuture.java:581)
at com.hazelcast.cp.internal.datastructures.lock.proxy.AbstractFencedLockProxy.unlock(AbstractFencedLockProxy.java:216)
at com.api.draak.service.WorkItemsService.unlock(WorkItemsService.kt:157)
at com.api.draak.service.WorkItemsService.offer(WorkItemsService.kt:82)
at com.api.draak.service.DraakService.processWorkItem(DraakService.kt:87)
at jdk.internal.reflect.GeneratedMethodAccessor183.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.base/java.util.concurrent.FutureTask.runAndReset(Unknown Source)
at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)

Ok, I used the wrong call. I should have used isLockedByCurrentThread. Now I received the status of the lock for the whole cluster. But I needed the lock status for the current instance/thread.

Related

The operation of calling IResource in Eclipse RCP causes the thread to wait

I use it like this in the code.
Project.refreshLocal(IResource.DEPTH_ONE, null);
Project.delete(false, true, new NullProgressMonitor());
Then I got the thread information and found the following problems.
Many threads are in the WAITING(on object monitor) state.
"pool-2-thread-2" #69 prio=5 os_prio=0 tid=0x000000001fa76000 nid=0x1b54 in Object.wait() [0x0000000032f0e000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x00000000cfac5630> (a java.lang.Object)
at java.lang.Object.wait(Unknown Source)
at org.eclipse.core.internal.jobs.ThreadJob.waitForRun(ThreadJob.java:316)
- locked <0x00000000cfac5630> (a java.lang.Object)
at org.eclipse.core.internal.jobs.ThreadJob.joinRun(ThreadJob.java:205)
at org.eclipse.core.internal.jobs.ImplicitJobs.begin(ImplicitJobs.java:95)
at org.eclipse.core.internal.jobs.JobManager.beginRule(JobManager.java:297)
at org.eclipse.core.internal.resources.WorkManager.checkIn(WorkManager.java:124)
at org.eclipse.core.internal.resources.Workspace.prepareOperation(Workspace.java:2243)
at org.eclipse.core.internal.resources.Resource.refreshLocal(Resource.java:1542)
at cn.com.agree.studio.server.utils.ResourceRefreshLocal.refreshLocal(ResourceRefreshLocal.java:25)
- locked <0x00000000c00c5e50> (a org.eclipse.core.internal.resources.Project)
at cn.com.agree.studio.server.service.search.GetJavaMetadataService.transferClassMetaInfo(GetJavaMetadataService.java:175)
at cn.com.agree.studio.server.service.search.GetJavaMetadataService.lambda$0(GetJavaMetadataService.java:153)
- locked <0x00000000c31d7958> (a java.lang.Class for cn.com.agree.studio.server.service.search.GetJavaMetadataService)
at cn.com.agree.studio.server.service.search.GetJavaMetadataService$$Lambda$326/115772063.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Then below is the code near the Monitor.
The class name of this class is 'org.eclipse.core.internal.jobs.ThreadJob'.
while (true) {
// monitor is foreign code so do not hold locks while calling into monitor
if (interrupted || isCanceled(monitor))
// Condition #4.
throw new OperationCanceledException();
// Try to run the job. If result is null, this job was allowed to run.
// If the result is successful, atomically release thread from waiting
// status.
blockingJob = manager.runNow(threadJob, true);
if (blockingJob == null) {
// Condition #1.
waiting = false;
return threadJob;
}
Thread blocker = blockingJob.getThread();
// the rule could have been transferred to this thread while we were waiting
if (blocker == currentThread && blockingJob instanceof ThreadJob) {
// now we are just the nested acquire case
result = (ThreadJob) blockingJob;
// push expects a compatible rule, otherwise an exception will be thrown
result.push(threadJob.getRule());
// rule was either accepted or both jobs have null rules
ruleCompatibleAndTransferred = true;
result.isBlocked = threadJob.isBlocked;
// Condition #3.
return result;
}
// just return if lock listener decided to grant immediate access
if (manager.getLockManager().aboutToWait(blocker))
// Condition #2.
return threadJob;
// Notify the lock manager that we're about to block waiting for the scheduling rule
manager.getLockManager().addLockWaitThread(currentThread, threadJob.getRule());
synchronized (blockingJob.jobStateLock) {
try {
// Wait until we are no longer definitely blocked (not running).
// The actual exit conditions are listed above at the beginning of
// this while loop
int state = blockingJob.getState();
//ensure we don't wait forever if the blocker is waiting, because it might have yielded
//to me
if (state == Job.RUNNING && canBlock)
blockingJob.jobStateLock.wait();
else if (state != Job.NONE)
blockingJob.jobStateLock.wait(250);
} catch (InterruptedException e) {
// This thread may be interrupted via two common scenarios. 1) If
// the UISynchronizer is in use and this thread is a UI thread
// and a syncExec() is performed, this thread will be interrupted
// every 1000ms. 2) If this thread is allowed to be blocked and
// the progress monitor was canceled, the internal JobManager
// worker thread will interrupt this thread so cancellation can
// be carried out.
interrupted = true;
}
}
// Going around the loop again. Ensure we're not marked as waiting for the thread
// as external code is run via the monitor (Bug 262032).
manager.getLockManager().removeLockWaitThread(currentThread, threadJob.getRule());
}
So I don’t know why the thread is waiting and how to solve the problem.
Many thanks in advance!

How to fix NullPointerException within AnyLogic

I have been trying to fix a NullPointerException for awhile now and I am completely stumped. It is occurring in a 'seize' block, but I cannot determine what exactly is causing it.
I have a feeling it could be the code I have inputted into the seize block due to the fact that I am a beginner.
I am trying to seize another agent and send it to different parts of the world via a parameter within the 'order' agent that contains a value from 1 to 8.
On seize unit I have the following code:
if (agent.missionLocation <= 1); KC30resource1.moveTo(main.AsiaRegion.randomPointInside());
{
if (agent.missionLocation <= 2); KC30resource1.moveTo(main.AfricaRegion.randomPointInside());
}
{
if (agent.missionLocation <= 3); KC30resource1.moveTo(main.MiddleeastRegion.randomPointInside());
}
{
if (agent.missionLocation <= 4); KC30resource1.moveTo(main.EuropeRegion.randomPointInside());
}
{
if (agent.missionLocation <= 5); KC30resource1.moveTo(main.NAmericaRegion.randomPointInside());
}
{
if (agent.missionLocation <= 6); KC30resource1.moveTo(main.SAmericaRegion.randomPointInside());
}
{
if (agent.missionLocation <= 7); KC30resource3.moveTo(main.AustraliaNzRegion.randomPointInside());
}
{
if (agent.missionLocation <= 8); KC30resource2.moveTo(main.PacificRegion.randomPointInside());
}
Could this be the reason why it is happening?
Exception during discrete event execution:
NullPointerException
java.lang.NullPointerException
at com.anylogic.libraries.processmodeling.Seize.a(Unknown Source)
at com.anylogic.libraries.processmodeling.Seize.a(Unknown Source)
at com.anylogic.libraries.processmodeling.Seize.a(Unknown Source)
at com.anylogic.libraries.processmodeling.Seize.a(Unknown Source)
at com.anylogic.libraries.processmodeling.Seize.a(Unknown Source)
at com.anylogic.libraries.processmodeling.Seize.a(Unknown Source)
at com.anylogic.libraries.processmodeling.Seize.a(Unknown Source)
at com.anylogic.libraries.processmodeling.Seize$16.a(Unknown Source)
at com.anylogic.libraries.processmodeling.Seize$16.action(Unknown Source)
at com.anylogic.libraries.processmodeling.AsynchronousExecutor_xjal.executeActionOf(Unknown Source)
at com.anylogic.engine.EventTimeout.execute(Unknown Source)
at com.anylogic.engine.Engine.f(Unknown Source)
at com.anylogic.engine.Engine.gj(Unknown Source)
at com.anylogic.engine.Engine.e(Unknown Source)
at com.anylogic.engine.Engine$m.run(Unknown Source)
Expected results are that the unit will fly to the GISregion specified in the code. Each 'MoveTo' block for each region is connect to the Seize block.
Thank you in advance.
I think you are using the Seize block wrong. You are trying to tell the resource to move within the seize object but that is not how you do this, see some tutorials on that.
Instead, you set up your resource pool with your resources (Seems to be KC30 in your case). Set it up to have 10 or however many you have.
Now in Seize, make your order seize 1 KC30 from the resource pool. You may tell it to first move towards the order agent, if you like:
To make the KC30 agent move to a region with the order now, you use a "MoveTo" block after the seize block and tell the order (and its seized KC30) to your world region with your code.
PS: your if-statements could be replaced by a switch statement, it is more elegant and error-proof, check it out :-)

Add trycatch inside method code failing with JSR/RET are not supported with computeFrames option

I am writing a Java agent which is supposed to be attached
to a running JVM. On that running JVM, there is a class already loaded and agent wants to instrument a method of that class.
The agent uses the ASM framework to add a try/catch block in the method content which is to be instrumented.
Below is the code I have written to add the try/catch block:
public void visitCode() {
if (mMethodName.equals("test")) {
mv.visitLabel(startFinally);
super.visitCode();
}
}
public void visitMaxs(int maxStack, int maxLocals) {
Label endFinally = new Label();
mv.visitTryCatchBlock(startFinally,endFinally,endFinally,
"java/lang/Exception");
mv.visitLabel(endFinally);
mv.visitVarInsn(ASTORE, 1);
mv.visitVarInsn(ALOAD, 1);
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Exception",
"printStackTrace", "()V"););
}
I am using ClassWriter.COMPUTE_FRAMES in ClassWriter, but I'm getting an error:
java.lang.RuntimeException: JSR/RET are not supported with computeFrames option
at com.bea.objectweb.asm.Frame.a(Unknown Source)
at com.bea.objectweb.asm.MethodWriter.visitJumpInsn(Unknown Source)
at com.bea.objectweb.asm.ClassReader.a(Unknown Source)

ERR EXEC without MULTI - spring redis+jedis

I meet with exception during a transactional operation with spring-data-redis
RedisTemplate<String,Object> cartCache;
public void create(final Cartline cartline) {
Object txResults = cartCache.execute(new SessionCallback<List>() {
public List execute(RedisOperations operations) throws DataAccessException {
String cartId = cartline.getMemberId();
String cartlineId = cartline.getCartlineId();
operations.multi();
......
return operations.exec();
}
});
}
redis.clients.jedis.exceptions.JedisDataException: ERR EXEC without MULTI
at redis.clients.jedis.Protocol.processError(Protocol.java:115)
at redis.clients.jedis.Protocol.process(Protocol.java:133)
at redis.clients.jedis.Protocol.read(Protocol.java:202)
at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:285)
at redis.clients.jedis.Connection.getRawObjectMultiBulkReply(Connection.java:230)
at redis.clients.jedis.Connection.getObjectMultiBulkReply(Connection.java:236)
at redis.clients.jedis.Transaction.exec(Transaction.java:38)
at org.springframework.data.redis.connection.jedis.JedisConnection.exec(JedisConnection.java:738)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.data.redis.core.CloseSuppressingInvocationHandler.invoke(CloseSuppressingInvocationHandler.java:57)
at com.sun.proxy.$Proxy512.exec(Unknown Source)
at org.springframework.data.redis.core.RedisTemplate$3.doInRedis(RedisTemplate.java:593)
at org.springframework.data.redis.core.RedisTemplate$3.doInRedis(RedisTemplate.java:591)
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:190)
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:152)
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:140)
at org.springframework.data.redis.core.RedisTemplate.execRaw(RedisTemplate.java:591)
at org.springframework.data.redis.core.RedisTemplate.exec(RedisTemplate.java:578)
at com.znova.stone.cart.repository.impl.CartCacheImpl$1.execute(CartCacheImpl.java:51)
at com.znova.stone.cart.repository.impl.CartCacheImpl$1.execute(CartCacheImpl.java:1)
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:217)
I read this post ERR EXEC without MULTI - Jedis which indicates a multi with exec, I also have redisTemplate.setEnableTransactionSupport(true); enabled, the error stood still.
I removed operation logic within the multi-exec block, I found there is no difference whatever is there, the exception happens event with a zero-operation block.
I had this same problem and fixed it by updating spring-data-redis from 1.4.2.RELEASE to 1.5.2.RELEASE.

"Absent Code attribute in method that is not native or abstract in class" exception when starting a project in Netbeans 7.2

I've just installed the newest version of Netbeans ( 7.2 ) and tried to run an existing Swing project in it. I got the following exception:
StackTrace:
java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file com/eositservices/eldorado/dialogs/zahlungverrechnung/model/InitDataList
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2427)
at java.lang.Class.getDeclaredMethod(Class.java:1935)
at java.awt.Component.isCoalesceEventsOverriden(Component.java:5975)
at java.awt.Component.access$500(Component.java:169)
at java.awt.Component$3.run(Component.java:5929)
at java.awt.Component$3.run(Component.java:5927)
at java.security.AccessController.doPrivileged(Native Method)
at java.awt.Component.checkCoalescing(Component.java:5926)
at java.awt.Component.<init>(Component.java:5895)
at java.awt.Container.<init>(Container.java:249)
at javax.swing.JComponent.<init>(JComponent.java:570)
at javax.swing.JPanel.<init>(JPanel.java:65)
at javax.swing.JPanel.<init>(JPanel.java:92)
at javax.swing.JPanel.<init>(JPanel.java:100)
at com.eositservices.eldorado.masken.FormForderung.<init>(FormForderung.java:72)
at com.eositservices.eldorado.tabsheets.zahlung.TSZahlung.<init>(TSZahlung.java:183)
at com.eositservices.eldorado.masken.TFormForderung.addTabs(TFormForderung.java:366)
at com.eositservices.eldorado.masken.TFormForderung.initializeComponents(TFormForderung.java:275)
at com.eositservices.eldorado.masken.TFormForderung.configureComponents(TFormForderung.java:148)
at com.eositservices.bones.view.components.EOSInternalFrame.setUp(EOSInternalFrame.java:81)
at com.eositservices.eldorado.masken.TFormForderung.<init>(TFormForderung.java:113)
at com.eositservices.eldorado.main.MainFrame.oeffneForderung(MainFrame.java:577)
at com.eositservices.eldorado.main.MainFrame.showForderung(MainFrame.java:488)
at com.eositservices.eldorado.dev.QuickLogin.openForderung(QuickLogin.java:109)
at com.eositservices.eldorado.dev.QuickLogin.openInitialViews(QuickLogin.java:143)
at com.eositservices.eldorado.main.MainFrame$2.run(MainFrame.java:433)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:646)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:607)
at java.awt.EventQueue$1.run(EventQueue.java:605)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:616)
at com.eositservices.bones.view.GlobalHotkeyManager.dispatchEvent(GlobalHotkeyManager.java:163)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
The method in question looks like this:
#Override
public boolean add( InitData e ) {
boolean returnValue = super.add( e );
Collections.sort( this, c );
return returnValue;
}
The strange thing is that the exception only comes when I set the project properties to "Compile on save". When the option is unchecked it runs fine. We had no such problems in the previous versions of NetBeans. Is it just a coincidence and I should look elsewhere for the source of this error or has anyone had similar problems? Thanks in advance for your help.
It seems to be a bug in the NetBeans.
When this exception occurs, let's make an error in the code (e.g
#Override
**efefefefef**
public boolean add( InitData e ) {
boolean returnValue = super.add( e );
Collections.sort( this, c );
return returnValue;
}
)
save it and when the Netbeans displays the error, correct it back. I have tried to clear the Project, remove everything from the cache, but nothing happened. But this way helped on me.