Why does the for loop cause jvm escape failure - jvm

When a for loop is added, the escape fails. JVM memory GC frequently。
On the surface, the CTX field should escape successfully.
However, when CTX is before and after the for loop, it has different results.
I'm not sure about the detailed implementation of the JVM, but there is no place to explain the reasons for the escape failure.
Both jvm8 and 14 have tried, and the result is the same.
Can someone tell me why?
class Ctx {
private String name;
public Ctx(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void doNothing() {
}
}
public class Test {
public static void main(String[] args) {
for (long i = 0; i < Long.MAX_VALUE; ++i) {
Ctx ctx = new Ctx("name");
// escape success
ctx.doNothing();
for (int c = 0; c < 4; c++) {
}
// escape fail
// ctx.doNothing();
}
}
}

Related

Add weights to documents Lucene8+solr 8 while indexing

I am working on migrating solr from 5.4.3 to 8.11 for one of my search apps and successfully upgraded to 7.7.3. But for further upgradations facing the order of the response data being changed than it was earlier. Here I am trying to use FunctionScoreQuery along with DoubleValuesSource since CustomScoreQuery is deprecated in 7.7.3 and removed in 8.
Below is my code snippet (now I am using solr 8.5.2 and Lucene 8.5.2)
public class CustomQueryParser extends QParserPlugin {
#Override
public QParser createParser(final String qstr, final SolrParams localParams, final SolrParams params,
final SolrQueryRequest req) {
return new MyParser(qstr, localParams, params, req);
}
private static class MyParser extends QParser {
private Query innerQuery;
private String queryString;
public MyParser(final String qstr, final SolrParams localParams, final SolrParams params,
final SolrQueryRequest req) {
super(qstr, localParams, params, req);
if (qstr == null || qstr.trim().length() == 0) {
this.queryString = DEFAULT_SEARCH_QUERY;
setString(this.queryString);
} else {
this.queryString = qstr;
}
try {
if (queryString.contains(":")) {
final QParser parser = getParser(queryString, "edismax", getReq());
this.innerQuery = parser.parse();
} else {
final QParser parser = getParser(queryString, "dismax", getReq());
this.innerQuery = parser.parse();
}
} catch (final SyntaxError ex) {
throw new RuntimeException("Error parsing query", ex);
}
}
#Override
public Query parse() throws SyntaxError{
final Query query = new MyCustomQuery(innerQuery);
final CustomValuesSource customValuesSource = new CustomValuesSource(queryString,innerQuery);
final FunctionScoreQuery fsq = FunctionScoreQuery.boostByValue(query, customValuesSource.fromFloatField("score"));
return fsq;
}
}
}
public class MyCustomQuery extends Query {
#Override
public Weight createWeight(final IndexSearcher searcher, final ScoreMode scoreMode, final float boost) throws IOException {
Weight weight;
if(query == null){
weight = new ConstantScoreWeight(this, boost) {
#Override
public Scorer scorer(final LeafReaderContext context) throws IOException {
return new ConstantScoreScorer(this,score(),scoreMode, DocIdSetIterator.all(context.reader().maxDoc()));
}
#Override
public boolean isCacheable(final LeafReaderContext leafReaderContext) {
return false;
}
};
}else {
weight = searcher.createWeight(query,scoreMode,boost);
}
return weight;
}
}
public class CustomValuesSource extends DoubleValuesSource {
#Override
public DoubleValues getValues(final LeafReaderContext leafReaderContext,final DoubleValues doubleValues) throws IOException {
final DoubleValues dv = new CustomDoubleValues(leafReaderContext);
return dv;
}
class CustomDoubleValues extends DoubleValues {
#Override
public boolean advanceExact(final int doc) throws IOException {
final Document document = leafReaderContext.reader().document(doc);
final List<IndexableField> fields = document.getFields();
for (final IndexableField field : fields) {
// total_score is being calculated with my own preferences
document.add(new FloatDocValuesField("score",total_score));
//can we include the **score** here?
this custom logic which includes score is not even calling.
}
}
}
I am trying for a long time but have not found a single working example. Can anybody help me and save me here.
Thank you,
Syamala.

Pointcut for classes inside different package or sub-packages marked Deprecated and at the time whenever they used or instantiated?

I want to write a point cut for class instantiation in various packages,like classes inside the subpackages inside com.kepler.xenon (eg.com.kepler.xenon.modules.ticklers.pojo.Tickler,
com.kepler.xenon.modules.product.pojo.Product etc).
//This is my advice
#Aspect
#Component
public class OxAspect {
#After("execution(* com.oxane.xenon..*new(..)) && #within(java.lang.Deprecated)")
public void myAdvice(final JoinPoint jp){
System.out.println(jp.getSignature().getName()+""+jp.getTarget().getClass());
}
}
//This is my class
package com.kepler.xenon.modules.ticklers.pojo;
#Deprecated
public Class Ticklers{
#Id
#TableGenerator(name = "TICKLERS_ID", table = "ID_GENERATOR", pkColumnName = "GEN_KEY", valueColumnName = "GEN_VALUE", pkColumnValue = "TICKLERS_ID", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.TABLE, generator = "TICKLERS_ID")
#Column(name = "TICKLERS_ID", unique = true, nullable = false)
private int ticklersId;
#Column(name = "TASK", nullable = false, length = 256)
private String taskName;
public int getTicklersId() {
return ticklersId;
}
public void setTicklersId(int ticklersId) {
this.ticklersId = ticklersId;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
}
What i want is that if anyone tries to access the class which is deprecated,then pointcut filters that call and triggers advice.
I have done it for methods but i am failing to do it for classes.
I am adding aspect which works for methods,controller and Dao
#Aspect
#Component
public class OxAspect {
private final OxAspectService oxAspectService;
public OxAspect(OxAspectService oxAspectService) {
this.oxAspectService=oxAspectService;
}
#Pointcut("execution(#java.lang.Deprecated * com.oxane.xenon..*(..))"
+ " || execution(* com.oxane.xenon..*.*(..)) && #within(java.lang.Deprecated)")
public void deprecated() {
}
#Before("deprecated()")
public void log(final JoinPoint jp) {
oxAspectService.logDeprecatedMethod(jp);
}
}
Edit:
I have done some research on spring io and found that it can't be done using spring aop. I have to use load time weaving or compile time weaving to achieve what i want. For that i have to use pure aspect j implementation. Correct me if i am wrong.
If I were you I will devide #Pointcut to signle condition like below:
#Pointcut("execution(* com.oxane.xenon..*(..))")
public void anyClassInSubpackage() {
}
#Pointcut("#annotation(java.lang.Deprecated)")
public void deprecatedClass() {
}
#Pointcut("execution(* com.oxane.xenon..*new(..))")
public void anyMethodInSubpackege() {
}
#Pointcut("#within(java.lang.Deprecated)")
public void deprecatedMethod() {
}
#Before("(anyClassInSubpackage() && deprecatedClass()) || (anyMethodInSubpackege() && deprecatedMethod())")
public void myAdvice(final JoinPoint jp){
//TODO
}

DataStreamer does not work well

I'm using Ignite 2.1.0 and I create a simple program to try DataStreamer, but I offen got error like this:
"[diagnostic]Failed to wait for partition map exchange" or "Attempted to release write lock while not holding it".
I started two local nodes, one was started in windows CMD using example xml configuration and another was started in Eclipse. My code in Eclipse like this :
public class TestDataStreamer {
public static void main(String[] args) {
// TODO Auto-generated method stub
long bgn,end;
IgniteConfiguration cfg = new IgniteConfiguration();
cfg.setPeerClassLoadingEnabled(true);
Ignite ignite = Ignition.start(cfg);
CacheConfiguration<Long, Map> cacheConf = new CacheConfiguration();
cacheConf.setName("TestDataStreamer").setCacheMode(CacheMode.REPLICATED);
cacheConf.setBackups(0);
IgniteCache cache = ignite.getOrCreateCache(cacheConf);
cache.clear();
File dataFile = new File("D:/data/1503307171374.data"); //10,000,000 rows text data
bgn = System.currentTimeMillis();
try {
loadByStreamer(dataFile,ignite,"TestDataStreamer");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
end = System.currentTimeMillis();
System.out.println("---------------");
System.out.println((end-bgn)/1000.0+" s");
}
cache.destroy();
System.out.println("cache destroy...");
ignite.close();
System.out.println("finish");
}
private static void loadByStreamer(File dataFile, Ignite ignite, String cacheName) throws Exception {
IgniteDataStreamer<Long,TestObj> ds = ignite.dataStreamer(cacheName);
//ds.allowOverwrite(true);
ds.autoFlushFrequency(10000);
ds.perNodeBufferSize(4096);
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(dataFile),"UTF-8"));
String line = null;
long count = 0;
while((line=br.readLine())!=null){
ds.addData(System.currentTimeMillis(), parseData(line, Constants.DEFAULT_SEPARATOR,
"id,sn,type_code,trade_ts,bill_ts,company_code,company_name,biz_type,charge_amt,pay_mode".split(",")));
if(++count%10000==0){
System.out.println(count+" loaded...");
}
//System.out.println(count+":"+line);
}
System.out.println("flushing...");
ds.flush();
System.out.println("flushed");
br.close();
ds.close();
System.out.println("file handled...");
}
private static TestObj parseData(String data, String saperator, String[] fields){
TestObj obj = new TestObj();
if(data!=null && saperator.trim().length()>0){
String[] values = data.split(saperator);
obj.setId(values[0]);
obj.setSn(values[1]);
obj.setType_code(values[2]);
obj.setTrade_ts(values[3]);
obj.setBill_ts(values[4]);
obj.setCompany_code(values[5]);
obj.setCompany_name(values[6]);
obj.setBiz_type(values[7]);
obj.setCharge_amt(values[8]);
obj.setPay_mode(values[9]);
}
return obj;
}
}
class TestObj {
private String id;
private String sn;
private String type_code;
private String trade_ts;
private String bill_ts;
private String company_code;
private String company_name;
private String biz_type;
private String charge_amt;
private String pay_mode;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
public String getType_code() {
return type_code;
}
public void setType_code(String type_code) {
this.type_code = type_code;
}
public String getTrade_ts() {
return trade_ts;
}
public void setTrade_ts(String trade_ts) {
this.trade_ts = trade_ts;
}
public String getBill_ts() {
return bill_ts;
}
public void setBill_ts(String bill_ts) {
this.bill_ts = bill_ts;
}
public String getCompany_code() {
return company_code;
}
public void setCompany_code(String company_code) {
this.company_code = company_code;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getBiz_type() {
return biz_type;
}
public void setBiz_type(String biz_type) {
this.biz_type = biz_type;
}
public String getCharge_amt() {
return charge_amt;
}
public void setCharge_amt(String charge_amt) {
this.charge_amt = charge_amt;
}
public String getPay_mode() {
return pay_mode;
}
public void setPay_mode(String pay_mode) {
this.pay_mode = pay_mode;
}
}
If stop the node started in CMD and run the program in only one node, it works well.
Is there anyone can help me?
Update jdk for both nodes to the same version, for example for 1.8.0_144(as you already have it in installed), or at least, try to update idk in eclipse to the latest of 1.7 versions, it should help.
There is a thread on Ignite user list, when guys faced pretty the same exception and updating of java version helped them to fix it.

How to find size of a queue in LinkedQueue.java without a counter variable

So for a project I have to create a LinkedQueue class but without a counter variable so I can't exactly keep track of how many elements are in the queue.
I need to create a size method to return the number of elements in the queue but I have no idea how to do it...here's my code:
package animal;
import exceptions.EmptyQueueException;
/**
* #author Sharon Umute
* Comp 139 001B
*/
public class LinkedQueue<T> implements QueueADT<T>{
SinglyLinkedNode<T> tail,head;
public LinkedQueue(){
head=tail=null;
}
#Override
public void enqueue(T element) {
SinglyLinkedNode<T> node =new SinglyLinkedNode<T>(element);
if(isEmpty()){
head = node;
}else{
tail.setNext(node);
}
tail=node;
}
#Override
public T dequeue() throws EmptyQueueException {
if (isEmpty()){
throw new EmptyQueueException("queue");
}else{
T result = head.getElement();
head=head.getNext();
if(isEmpty()){
tail=null;
}
return result;
}
}
#Override
public T first() throws EmptyQueueException {
if (isEmpty()){
throw new EmptyQueueException("queue");
}else{
T result=head.getElement();
return result;
}
}
#Override
public boolean isEmpty() {
return(head.getElement()==null);
}
#Override
public int size() {
}
}
I think this is should be a good way to implement size method:
Iterator it = this.head.iterator();
int i = 0;
while (it.hasNext())
{
LinkedQueue node = it.Next();
i++;
}
return i;

Glassfish - cannot remove entity using JPA

In my exploration of JPA, I have the code below (which I understand should not be used in production). Running my code produces the following error:
java.lang.IllegalStateException:
Exception Description: Cannot use an EntityTransaction while using JTA.
The Resource code is as follows:
#Path("users")
public class UsersAPI {
#Context
UriInfo uriInfo;
#Inject
UserBean accountsBean;
#GET
#Path("deduplicate")
public Response deduplicateDB(){
List<UserProfile> profiles = accountsBean.getAll();
int profilesNum = profiles.size();
for(int i = 0; i < profilesNum; ++i){
for(int k = 0; k < profilesNum; ++k){
if(i != k){ //if it's not the same profile
if(profiles.get(i).getUsername().equals(profiles.get(k).getUsername())){
accountsBean.remove(profiles.get(k));
profiles.remove(k);
}
}
profilesNum = profiles.size();
}
}
return Response.ok().build();
}
}
The code in the ProfilesBean is as follows:
#Local
#Stateless
public class UserBean {
#PersistenceContext
EntityManager eManager;
public void save(UserProfile data){
eManager.merge(data);
}
public void remove(UserProfile data){
eManager.getTransaction().begin();
eManager.remove(data);
eManager.getTransaction().commit();
}
public List<UserProfile> getAll(){
Query q = eManager.createQuery("SELECT profile FROM Users profile");
return (List<UserProfile>)q.getResultList();
}
}
Here is the code for the Entity class:
#Entity(name="Users")
public class UserProfile {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
Long id;
String password;
#Column(unique=true)
String username;
public UserProfile(String username){
setUsername(username);
}
public UserProfile(){
this(null);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
It seems like the error comes from my misusing the platform somehow. How can I fix this code and not misuse the platform in the future?
If you are using JTA as transaction-type in persistence.xml file just leave JTA handles your transactions
public void remove(UserProfile data){
eManager.remove(eManager.merge(data));
}
UPDATE:
In a more clear solution you could use "find", but you need to provide the object id
public void remove(UserProfile data){
UserProfile e = em.find(UserProfile.class, data.getId());
eManager.remove(e);
}