问:
Moving business rules into model
I asked a question earlier which elicited some great responses.

Here's the earlier question

On the back of some advice given there, I've tried moving the following controller logic

```<code> if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1
  @concept.attributes = {:status => 'Awaiting Compliance Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1
  @concept.attributes = {:status => 'Awaiting Marketing Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0
  @concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'}
else
  @concept.attributes = {:status => 'Pending Approval'}
end
</code>```

into the model, as so:

```<code>def set_status
if status.blank?
  if (consulted_legal == true) && (consulted_marketing == true)
      status = "Pending Approval"
  elsif (consulted_legal == true) && (consulted_marketing == false)
    status = "Awaiting Marketing Approval"
  elsif (consulted_legal == false) && (consulted_marketing == true)
    status = "Awaiting Legal Approval"
  elsif (consulted_legal == false) && (consulted_marketing == false)
    status = "Awaiting Marketing & Legal Approval"
  end
end
true # Needs to return true for the update to go through
  end
</code>```

I am calling that from a before_save callback.

As a default, both the consulted_legal and consulted_marketing attributes are set to false and not null, which is why I am testing for == false or true here, instead of asking

```<code>if consulted_legal?
</code>```

for instance.

However, this logic doesn't seem to be working. If I inspect the object, status is not being set to anything, ever. Can anyone spot why this might be happening? Have I got how attributes are accessed wrong in models, for instance?

TIA

答:
Instead of status = try self.status =. I've found that I needed to use self. to change a model's attribute within the model.

It's also much better to have errors.empty? at the end instead of true, so if you ever use errors.add_to_base in the future, your set_status method is ready to abort a save.

Edit:

You may also want to check out acts_as_state_machine. It looks like a plugin for exactly what you're doing.

OwnerDisplayName: The Pied Pipes

Title: Moving business rules into model

Body:
I asked a question earlier which elicited some great responses.

Here's the earlier question

On the back of some advice given there, I've tried moving the following controller logic

 if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1
  @concept.attributes = {:status => 'Awaiting Compliance Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1
  @concept.attributes = {:status => 'Awaiting Marketing Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0
  @concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'}
else
  @concept.attributes = {:status => 'Pending Approval'}
end

into the model, as so:

def set_status
if status.blank?
  if (consulted_legal == true) && (consulted_marketing == true)
      status = "Pending Approval"
  elsif (consulted_legal == true) && (consulted_marketing == false)
    status = "Awaiting Marketing Approval"
  elsif (consulted_legal == false) && (consulted_marketing == true)
    status = "Awaiting Legal Approval"
  elsif (consulted_legal == false) && (consulted_marketing == false)
    status = "Awaiting Marketing & Legal Approval"
  end
end
true # Needs to return true for the update to go through
  end

I am calling that from a before_save callback.

As a default, both the consulted_legal and consulted_marketing attributes are set to false and not null, which is why I am testing for == false or true here, instead of asking

if consulted_legal?

for instance.

However, this logic doesn't seem to be working. If I inspect the object, status is not being set to anything, ever. Can anyone spot why this might be happening? Have I got how attributes are accessed wrong in models, for instance?

TIA

OwnerDisplayName: Samuel

LastEditorDisplayName: Samuel


来源: stackexchange

问:
android Gps Application
i did the GPS application which gets the current location.It is working in android emulator by using DDMS perspective(by passing mock location).But it is not working in android phone and phone is Samsung gt-i5801.please help me.
And one more thing i want to ask you guys.
(Why i need Gps) bcoz
in my appln i want to display the nearest cinema theatres by using latitude and longitude.
Is there any other way to do that.
Please tell me.</p>

答:
I think there is no problem in your code if it runs in emulator. But you have not start the gps on your phone, so it's giving a null pointer exception.

So now when you use gps, first check whether gps is on or not. Then fetch lat. and long.

You can check your gps is on or off by this:

```<code>LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

boolean val= mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
</code>```

ContentLicense: CC BY-SA 2.5

Title: android Gps Application

Body:
I think there is no problem in your code if it runs in emulator. But you have not start the gps on your phone, so it's giving a null pointer exception.

So now when you use gps, first check whether gps is on or not. Then fetch lat. and long.

You can check your gps is on or off by this:

LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

boolean val= mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)

ContentLicense: CC BY-SA 4.0


问:
RegEx Parse Tool to extract digits from string
Using Alteryx, I have a field called Address which consists of fields like A32C, GH2X, ABC19E. So basically where digits are pinned between sets of letters. I am trying to use the RegEx tool to extract the digits out into a new column called ADDRESS1.

I have Address set to Field to Parse. Output method Parse.
My regular expression is typed in as:

```<code>(?:[[alpha]]+)(/d+)(?:[[alpha]]+)
</code>```

And then I have (/d+) outputting to ADDRESS1. However, when I run this it parses 0 records. What am I doing wrong?

答:
You can try this :

let regex = /(?!([A-Z]+))(\d+)(?=[A-Z]+)/g;
let values = 'A32CZ, GH2X, ABC19E'

let result = values.match(regex);

console.log(result);```

ContentLicense: CC BY-SA 3.0

Body:
Using Alteryx, I have a field called Address which consists of fields like A32C, GH2X, ABC19E. So basically where digits are pinned between sets of letters. I am trying to use the RegEx tool to extract the digits out into a new column called ADDRESS1.

I have Address set to Field to Parse. Output method Parse.
My regular expression is typed in as:

(?:[[alpha]]+)(/d+)(?:[[alpha]]+)

And then I have (/d+) outputting to ADDRESS1. However, when I run this it parses 0 records. What am I doing wrong?


问:
Creating new column based on row values of multiple data subsetting conditions
I have a dataframe that looks more or less like follows (the original one has 12 years of data):

```<code>   Year   Quarter   Age_1   Age_2   Age_3   Age_4
   2005      1       158     120     665     32
   2005      2       257     145     121     14
   2005      3       68       69     336     65
   2005      4       112     458     370     101
   2006      1       75      457     741     26
   2006      2       365     134     223     45
   2006      3       257     121     654     341
   2006      4       175     124     454     12
   2007      1       697     554     217     47
   2007      2       954     987     118     54
   2007      4       498     235     112     65
</code>```

Where the numbers in the age columns represents the amount of individuals in each age class for a specific quarter within a specific year. It is noteworthy that sometimes not all quarters in a specific year have data (e.g., third quarter is not represented in 2007). Also, each row represents a sampling event. Although not shown in this example, in the original dataset I always have more than one sampling event for a specific quarter within a specific year. For example, for the first quarter in 2005 I have 47 sampling events, leading therefore to 47 rows.

What I´d like to have now is a dataframe structured in a way like:

```<code>       Year   Quarter   Age_1   Age_2   Age_3   Age_4    Cohort
       2005      1       158     120     665     32        158
       2005      2       257     145     121     14        257
       2005      3       68       69     336     65         68
       2005      4       112     458     370     101       112
       2006      1       75      457     741     26        457
       2006      2       365     134     223     45        134
       2006      3       257     121     654     341       121
       2006      4       175     124     454     12        124
       2007      1       697     554     217     47         47
       2007      2       954     987     118     54         54
       2007      4       498     235     112     65         65
</code>```

In this case, I want to create a new column (Cohort) in my original dataset which basically follows my cohorts along my dataset. In other words, when I´m in my first year of data (2005 with all quarters), I take the row values of Age_1 and paste it into the new column. When I move to the next year (2006), then I take all my row values related to my Age_2 and paste it to the new column, and so on and so forth.

I have tried to use the following function, but somehow it only works for the first couple of years:

```<code>extract_cohort_quarter <- function(d, yearclass=2005, quarterclass=1) {

 ny <- 1:nlevels(d$Year) #no. of Year levels in the dataset
 nq <- 1:nlevels(d$Quarter)
 age0 <- (paste("age", ny, sep="_"))
 year0 <- as.character(yearclass + ny - 1)

quarter <- as.character(rep(1:4, length(age0)))
age <- rep(age0,each=4)
year <- rep(year0,each=4)

df <- data.frame(year,age,quarter,stringsAsFactors=FALSE)

n <- nrow(df)
dnew <- NULL
for(i in 1:n) {
    tmp <- subset(d, Year==df$year[i] & Quarter==df$quarter[i])
    tmp$Cohort <- tmp[[age[i]]]
    dnew <- rbind(dnew, tmp)
}
levels(dnew$Year) <- paste("Yearclass_", yearclass, ":",
year,":",quarter,":", age, sep="")
dnew
}
</code>```

I have plenty of data from age_1 to age_12 for all the years and quarters, so I don´t think that it´s something related to the data structure itself.

Is there an easier solution to solve this problem? Or is there a way to improve my extract_cohort_quarter() function? Any help will be much appreciated.

-M

Body:
I have a dataframe that looks more or less like follows (the original one has 12 years of data):

   Year   Quarter   Age_1   Age_2   Age_3   Age_4
   2005      1       158     120     665     32
   2005      2       257     145     121     14
   2005      3       68       69     336     65
   2005      4       112     458     370     101
   2006      1       75      457     741     26
   2006      2       365     134     223     45
   2006      3       257     121     654     341
   2006      4       175     124     454     12
   2007      1       697     554     217     47
   2007      2       954     987     118     54
   2007      4       498     235     112     65

Where the numbers in the age columns represents the amount of individuals in each age class for a specific quarter within a specific year. It is noteworthy that sometimes not all quarters in a specific year have data (e.g., third quarter is not represented in 2007). Also, each row represents a sampling event. Although not shown in this example, in the original dataset I always have more than one sampling event for a specific quarter within a specific year. For example, for the first quarter in 2005 I have 47 sampling events, leading therefore to 47 rows.

What I´d like to have now is a dataframe structured in a way like:

       Year   Quarter   Age_1   Age_2   Age_3   Age_4    Cohort
       2005      1       158     120     665     32        158
       2005      2       257     145     121     14        257
       2005      3       68       69     336     65         68
       2005      4       112     458     370     101       112
       2006      1       75      457     741     26        457
       2006      2       365     134     223     45        134
       2006      3       257     121     654     341       121
       2006      4       175     124     454     12        124
       2007      1       697     554     217     47         47
       2007      2       954     987     118     54         54
       2007      4       498     235     112     65         65

In this case, I want to create a new column (Cohort) in my original dataset which basically follows my cohorts along my dataset. In other words, when I´m in my first year of data (2005 with all quarters), I take the row values of Age_1 and paste it into the new column. When I move to the next year (2006), then I take all my row values related to my Age_2 and paste it to the new column, and so on and so forth.

I have tried to use the following function, but somehow it only works for the first couple of years:

extract_cohort_quarter <- function(d, yearclass=2005, quarterclass=1) {

 ny <- 1:nlevels(d$Year) #no. of Year levels in the dataset
 nq <- 1:nlevels(d$Quarter)
 age0 <- (paste("age", ny, sep="_"))
 year0 <- as.character(yearclass + ny - 1)

quarter <- as.character(rep(1:4, length(age0)))
age <- rep(age0,each=4)
year <- rep(year0,each=4)

df <- data.frame(year,age,quarter,stringsAsFactors=FALSE)

n <- nrow(df)
dnew <- NULL
for(i in 1:n) {
    tmp <- subset(d, Year==df$year[i] & Quarter==df$quarter[i])
    tmp$Cohort <- tmp[[age[i]]]
    dnew <- rbind(dnew, tmp)
}
levels(dnew$Year) <- paste("Yearclass_", yearclass, ":",
year,":",quarter,":", age, sep="")
dnew
}

I have plenty of data from age_1 to age_12 for all the years and quarters, so I don´t think that it´s something related to the data structure itself.

Is there an easier solution to solve this problem? Or is there a way to improve my extract_cohort_quarter() function? Any help will be much appreciated.

-M

Body:
Here is an option using tidyverse

library(dplyr)
library(tidyr)
df1 %>%
    gather(key, Cohort, -Year, -Quarter) %>%
    separate(key, into = c('key1', 'key2')) %>%
    mutate(ind = match(Year, unique(Year))) %>%
    group_by(Year) %>%
    filter(key2 == Quarter[ind]) %>%
    mutate(newcol = paste(Year, Quarter, paste(key1, ind, sep="_"), sep=":")) %>%
    ungroup %>%
    select(Cohort, newcol) %>%
    bind_cols(df1, .)
#   Year Quarter Age_1 Age_2 Age_3 Age_4 Cohort       newcol
#1  2005       1   158   120   665    32    158 2005:1:Age_1
#2  2005       2   257   145   121    14    257 2005:2:Age_1
#3  2005       3    68    69   336    65     68 2005:3:Age_1
#4  2005       4   112   458   370   101    112 2005:4:Age_1
#5  2006       1    75   457   741    26    457 2006:1:Age_2
#6  2006       2   365   134   223    45    134 2006:2:Age_2
#7  2006       3   257   121   654   341    121 2006:3:Age_2
#8  2006       4   175   124   454    12    124 2006:4:Age_2
#9  2007       1   697   554   217    47     47 2007:1:Age_3
#10 2007       2   954   987   118    54     54 2007:2:Age_3
#11 2007       4   498   235   112    65     65 2007:4:Age_3


问:
How can I cache Ruby VALUE values for later reuse?
I'm embedding Ruby 2.2 into a C++ application and try to optimise a function of the form

```<code>VALUE toRubyString( const MyObject &o )
{
     const char *utf8 = get_string_rep_of( o );
     return rb_enc_str_new( utf8, strlen( utf8 ), rb_utf8_encoding() );
}
</code>```

It turned out that toRubyString dominates the runtime profiling output in certain use cases. In those cases, the function gets called very often but only with a few different MyObject values. Hence, my idea is to cache the VALUE values in a std::map<MyObject, VALUE> or the like such that I can reuse them, along the lines of

```<code>std::map<MyObject, VALUE> cache;

VALUE toRubyString( const MyObject &o )
{
     std::map<MyObject, VALUE>::const_iterator it = cache.find( o );
     if ( it != cache.end() ) {
         return it->second;
     }
     const char *utf8 = get_string_rep_of( o );
     VALUE v = rb_enc_str_new( utf8, strlen( utf8 ), rb_utf8_encoding() );
     cache[o] = v;
     return v;
}
</code>```

Alas, I noticed that with this modification, the Ruby interpreter eventually crashes, and the crashes disappear if I omit the return it->second; line (i.e. when the code refrains from reusing cached entries).

I suspect this is related to the garbage collector since it only happens after a couple thousand calls to the function, but even a

```<code>rb_gc_mark(v);
</code>```

call (before adding the VALUE to the cache) didn't help. Does anybody have some idea as to what I might be missing here?

答:
rb_global_variable(&cache[o]) might work.

Apparently, inserting into a map should not invalidate pointers to existing elements, so it's technically okay to use the address of the map value like that. And then rb_global_variable will make it so the cached value is completely excluded from GC.

The reason why rb_gc_mark doesn't work is because that only prevents the object from being cleaned up on the next collection. You usually use it when defining a custom class's mark function so that the GC can mark internally-referenced objects appropriately.

Body:
I'm embedding Ruby 2.2 into a C++ application and try to optimise a function of the form

VALUE toRubyString( const MyObject &o )
{
     const char *utf8 = get_string_rep_of( o );
     return rb_enc_str_new( utf8, strlen( utf8 ), rb_utf8_encoding() );
}

It turned out that toRubyString dominates the runtime profiling output in certain use cases. In those cases, the function gets called very often but only with a few different MyObject values. Hence, my idea is to cache the VALUE values in a std::map<MyObject, VALUE> or the like such that I can reuse them, along the lines of

std::map<MyObject, VALUE> cache;

VALUE toRubyString( const MyObject &o )
{
     std::map<MyObject, VALUE>::const_iterator it = cache.find( o );
     if ( it != cache.end() ) {
         return it->second;
     }
     const char *utf8 = get_string_rep_of( o );
     VALUE v = rb_enc_str_new( utf8, strlen( utf8 ), rb_utf8_encoding() );
     cache[o] = v;
     return v;
}

Alas, I noticed that with this modification, the Ruby interpreter eventually crashes, and the crashes disappear if I omit the return it->second; line (i.e. when the code refrains from reusing cached entries).

I suspect this is related to the garbage collector since it only happens after a couple thousand calls to the function, but even a

rb_gc_mark(v);

call (before adding the VALUE to the cache) didn't help. Does anybody have some idea as to what I might be missing here?


问:
Access ActionArguments in IExceptionFilter
Is it possible to access ActionArguments in an IExceptionFilter?

According to the above picutre Exception Filters run after Action Filters which have access to them. So I don't see why they can't.

In an ActionFilter you access it like this

```<code>public class MyFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        context.ActionArguments // I need access to this in order to find out what type the input argument(s) was.
    }
}
</code>```

But an IExceptionFilter uses public void OnException(ExceptionContext context) instead.

答:
I figured it out :)</p>

```<code>public class ExceptionFilter : IExceptionFilter, IActionFilter
{
    private IDictionary<string, object> _actionArguments;

    public void OnException(ExceptionContext context)
    {
        _actionArguments // great success!
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        _actionArguments = context.ActionArguments;
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // do nothing
    }
}
</code>```

Body:
Is it possible to access ActionArguments in an IExceptionFilter?

According to the above picutre Exception Filters run after Action Filters which have access to them. So I don't see why they can't.

In an ActionFilter you access it like this

public class MyFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        context.ActionArguments // I need access to this in order to find out what type the input argument(s) was.
    }
}

But an IExceptionFilter uses public void OnException(ExceptionContext context) instead.

Body:
I figured it out :)

public class ExceptionFilter : IExceptionFilter, IActionFilter
{
    private IDictionary<string, object> _actionArguments;

    public void OnException(ExceptionContext context)
    {
        _actionArguments // great success!
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        _actionArguments = context.ActionArguments;
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // do nothing
    }
}


问:
GCC compilation error, braces around scalar initializer [-Werror]
I'm new in C programming and I try to create a struct containing a char and a function pointer, and that is the problem.

I want to change that code:

```<code>switch (flag) {
    case 'd':
    case 'i':
    return (my_put_nbr(va_arg(ap, int)));
    case 'p':
    return (my_putstr("0x") + my_l_base_changer(va_arg(ap, char *),
    16));
    case 'u':
    return (my_put_unbr(va_arg(ap, unsigned int)));
    case 'b':
    return (my_u_base_changer(va_arg(ap, unsigned int), 2, 0));
    case 'o':
    return (my_u_base_changer(va_arg(ap, unsigned int), 8, 0));
    case 'x':
    return (my_u_base_changer(va_arg(ap, unsigned int), 16, 0));
    case 'X':
    return (my_u_base_changer(va_arg(ap, unsigned int), 16, 1));
    default:
    return (0);
}
</code>```

in that kind of code:

```<code>typedef struct fptr
{
   char op;
   int (*ptr)(va_list);
} fptr;

fptr  fptrs[]=
{
   { 's', ft_print_nb_spec },
   { 'S', ft_print_nb_up },
   { 0, NULL }
};
  int i = 0;
  while (fptrs[i++].op != flag && fptrs[i].op != 0);
  if (fptrs[i].op != 0)
  {
     fptrs[i].ptr();
  }
</code>```

And my struct contain a function pointer to functions who get differents prototypes

My struct is like that :

```<code>typedef struct action {
    char flag;
    void *function;
} action;
</code>```

And my code who bug like that :

```<code>action registers[] = {
    { 'd', (int *)(*my_put_nbr)(int) },
    { 'i', (int)(*my_put_nbr)(va_arg(ap, int)) },
    { 'p', (int)(*my_print_ptr)(va_list ap) },
    { 'u', (int)(*my_put_unbr)(va_arg(ap, unsigned int)) },
    { 'b', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 2, 0) },
    { 'o', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 8, 0) },
    { 'x', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 8, 0) },
    { 'X', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 8, 1) },
    { 0, NULL }
};
</code>```

And when I run gcc got that:

```<code>flag_nbr.c:13:28: error: expected expression before ‘int’
{ 'd', (int)(my_put_nbr)(int) },
                         ^~~
flag_nbr.c:13:28: error: missing initializer for field ‘function’ of ‘printf_action {aka struct <anonymous>}’ [-Werror=missing-field-initializers]
In file included from flag_nbr.c:8:0:
../include/my.h:21:8: note: ‘function’ declared here
void *function;
      ^~~~~~~~
flag_nbr.c:14:10: error: initialization makes pointer from integer without a cast [-Werror=int-conversion]
{ 'i', (int)(my_put_nbr)(va_arg(ap, int)) },
        ^
</code>```

And I don't understand that error...

答:
When in doubt, check the data types!!

You define the variable as an array of pointers to the action type.

What you pass in the initializers are the brace enclosed list which is certainly no match for a pointer to the action type.

In other words, you try to pass a brace enclosed list while a pointer was expected. Now, an initializer for a pointer is supposed to be a singular value (or scalar, as you may call it), so a brace enclosure is not MANDATORY.

While this is perfectly valid, most of the times, this may be caused by an issue where you write something you did not intend to write (example: your case!!) and thus, gcc produces a warning for this.

You may want to change your array type to hold structures of type action, not pointers to them.

Body:
I'm new in C programming and I try to create a struct containing a char and a function pointer, and that is the problem.

I want to change that code:

switch (flag) {
    case 'd':
    case 'i':
    return (my_put_nbr(va_arg(ap, int)));
    case 'p':
    return (my_putstr("0x") + my_l_base_changer(va_arg(ap, char *),
    16));
    case 'u':
    return (my_put_unbr(va_arg(ap, unsigned int)));
    case 'b':
    return (my_u_base_changer(va_arg(ap, unsigned int), 2, 0));
    case 'o':
    return (my_u_base_changer(va_arg(ap, unsigned int), 8, 0));
    case 'x':
    return (my_u_base_changer(va_arg(ap, unsigned int), 16, 0));
    case 'X':
    return (my_u_base_changer(va_arg(ap, unsigned int), 16, 1));
    default:
    return (0);
}

in that kind of code:

typedef struct fptr
{
   char op;
   int (*ptr)(va_list);
} fptr;

fptr  fptrs[]=
{
   { 's', ft_print_nb_spec },
   { 'S', ft_print_nb_up },
   { 0, NULL }
};
  int i = 0;
  while (fptrs[i++].op != flag && fptrs[i].op != 0);
  if (fptrs[i].op != 0)
  {
     fptrs[i].ptr();
  }

And my struct contain a function pointer to functions who get differents prototypes

My struct is like that :

typedef struct action {
    char flag;
    void *function;
} action;

And my code who bug like that :

action registers[] = {
    { 'd', (int *)(*my_put_nbr)(int) },
    { 'i', (int)(*my_put_nbr)(va_arg(ap, int)) },
    { 'p', (int)(*my_print_ptr)(va_list ap) },
    { 'u', (int)(*my_put_unbr)(va_arg(ap, unsigned int)) },
    { 'b', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 2, 0) },
    { 'o', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 8, 0) },
    { 'x', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 8, 0) },
    { 'X', (int)(*my_u_base_changer)(va_arg(ap, unsigned int), 8, 1) },
    { 0, NULL }
};

And when I run gcc got that:

flag_nbr.c:13:28: error: expected expression before ‘int’
{ 'd', (int)(my_put_nbr)(int) },
                         ^~~
flag_nbr.c:13:28: error: missing initializer for field ‘function’ of ‘printf_action {aka struct <anonymous>}’ [-Werror=missing-field-initializers]
In file included from flag_nbr.c:8:0:
../include/my.h:21:8: note: ‘function’ declared here
void *function;
      ^~~~~~~~
flag_nbr.c:14:10: error: initialization makes pointer from integer without a cast [-Werror=int-conversion]
{ 'i', (int)(my_put_nbr)(va_arg(ap, int)) },
        ^

And I don't understand that error...


问:
Bash tool to get nth line from a file
Is there a "canonical" way of doing that? I've been using head -n | tail -1 which does the trick, but I've been wondering if there's a Bash tool that specifically extracts a line (or a range of lines) from a file.

By "canonical" I mean a program whose main function is doing that.

答:
Lots of good answers already. I personally go with awk. For convenience, if you use bash, just add the below to your ~/.bash_profile. And, the next time you log in (or if you source your .bash_profile after this update), you will have a new nifty "nth" function available to pipe your files through.

Execute this or put it in your ~/.bash_profile (if using bash) and reopen bash (or execute source ~/.bach_profile)

# print just the nth piped in line
nth () { awk -vlnum=${1} 'NR==lnum {print; exit}'; }
```
<p>Then, to use it, simply pipe through it. E.g.,:</p>
```$ yes line | cat -n | nth 5
     5  line
```

Title: Bash tool to get nth line from a file

Body:
Lots of good answers already. I personally go with awk. For convenience, if you use bash, just add the below to your ~/.bash_profile. And, the next time you log in (or if you source your .bash_profile after this update), you will have a new nifty "nth" function available to pipe your files through.

Execute this or put it in your ~/.bash_profile (if using bash) and reopen bash (or execute source ~/.bach_profile)

# print just the nth piped in line
nth () { awk -vlnum=${1} 'NR==lnum {print; exit}'; }

Then, to use it, simply pipe through it. E.g.,:

$ yes line | cat -n | nth 5
     5  line


问:
How do I limit the number of rows in a datatable?
I generate a DataTable (from non-SQL data) and then use a DataView to filter the records.

I want to limit the number of records in the final record set but can't do this when I generate the DataTable.

I've resorted to deleting rows from the final result set, as per:

```<code>                DataView dataView = new DataView(dataTable);
                dataView.RowFilter = String.Format("EventDate > '{0}'", DateTime.Now);
                dataView.Sort = "EventDate";
                dataTable = dataView.ToTable();

                 while (dataTable.Rows.Count > _rowLimit)
                    dataTable.Rows[dataTable.Rows.Count - 1].Delete();

                 return dataTable;
</code>```

Is there a more efficient way to limit the results?

答:
Try copying the top x rows from one datatable into a new one.

```<code>dataTable.AsEnumerable().Take(50).CopyToDataTable(newdataTable)
</code>```

and then use that.

Body:
I generate a DataTable (from non-SQL data) and then use a DataView to filter the records.

I want to limit the number of records in the final record set but can't do this when I generate the DataTable.

I've resorted to deleting rows from the final result set, as per:

                DataView dataView = new DataView(dataTable);
                dataView.RowFilter = String.Format("EventDate > '{0}'", DateTime.Now);
                dataView.Sort = "EventDate";
                dataTable = dataView.ToTable();

                 while (dataTable.Rows.Count > _rowLimit)
                    dataTable.Rows[dataTable.Rows.Count - 1].Delete();

                 return dataTable;

Is there a more efficient way to limit the results?

Body:
Try copying the top x rows from one datatable into a new one.

dataTable.AsEnumerable().Take(50).CopyToDataTable(newdataTable)

and then use that.


问:
Error in calculation Winforms C#
I am building C# WinForms application which has 3 textboxes. First two take value and after calculation show value in third textbox. It has to be in textbox so user can change value if thinks that calculation is wrong. Everything works perfect, but when I run app on windows 7 I get huge error, it calculates that (for example ) 2 times 2.15 is 430. Why is that happening ? I tried installing latest .Net framework on that computer but still doesn't work and after research I have no further ideas.

```<code>num1 = num2 = sum = 0;
if (tbNum1.Text.Contains(","))
{
    tbNum1.Text = tbNum1.Text.Replace(",", ".");
}

double.TryParse(tbNum1.Text, out num1);
if (tbNum2.Text.Contains(","))
{
    tbNum2.Text = tbNum2.Text.Replace(",", ".");
}

double.TryParse(tbNum2.Text, out num2);
sum = num1 * num2;
sum = Math.Round(sum, 2);
tbSum.Text = sum.ToString();
</code>```

Also, additional two problems appear with displaying WinForm.
First is that panels have different sizes and positions than I programatically set.
Secont is that ( and I suppose that is my fault because I am probably doing that wrong ) all panels show very slow. What I have is like 6 panels with particular dimensions and 6 buttons. Depending on pressed button, I set all panels visible to false and only correct panel visible to true. But it loads very slow. Do you have any suggestions ? Thanks a lot in advance !

答:
The character that double.Parse recognizes as the decimal separator depends on the supplied IFormatProvider; if you don't supply any, that's the one for the current culture.

If you specifically want to use the dot as the decimal separator, you can just use CultureInfo.InvariantCulture:

```<code>double.TryParse(tbNum2.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out double num);
</code>```

Title: Error in calculation Winforms C#

Body:
I am building C# WinForms application which has 3 textboxes. First two take value and after calculation show value in third textbox. It has to be in textbox so user can change value if thinks that calculation is wrong. Everything works perfect, but when I run app on windows 7 I get huge error, it calculates that (for example ) 2 times 2.15 is 430. Why is that happening ? I tried installing latest .Net framework on that computer but still doesn't work and after research I have no further ideas.

num1 = num2 = sum = 0;
if (tbNum1.Text.Contains(","))
{
    tbNum1.Text = tbNum1.Text.Replace(",", ".");
}

double.TryParse(tbNum1.Text, out num1);
if (tbNum2.Text.Contains(","))
{
    tbNum2.Text = tbNum2.Text.Replace(",", ".");
}

double.TryParse(tbNum2.Text, out num2);
sum = num1 * num2;
sum = Math.Round(sum, 2);
tbSum.Text = sum.ToString();

Also, additional two problems appear with displaying WinForm.
First is that panels have different sizes and positions than I programatically set.
Secont is that ( and I suppose that is my fault because I am probably doing that wrong ) all panels show very slow. What I have is like 6 panels with particular dimensions and 6 buttons. Depending on pressed button, I set all panels visible to false and only correct panel visible to true. But it loads very slow. Do you have any suggestions ? Thanks a lot in advance !

Body:
The character that double.Parse recognizes as the decimal separator depends on the supplied IFormatProvider; if you don't supply any, that's the one for the current culture.

If you specifically want to use the dot as the decimal separator, you can just use CultureInfo.InvariantCulture:

double.TryParse(tbNum2.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out double num);


问:
Selenium WebDriver zoom in/out page content
How to change page zoom level in Selenium WebDriver?
I tried:

```<code>driver.Keyboard().pressKey(Keys.Control);
driver.Keyboard().pressKey(Keys.Add);
</code>```

But it doesn't work.

答:
11-17-2017 Update</p>

```<code>var html = page.FindElement(By.XPath("/html"));
html.SendKeys(Keys.Control + "0" + Keys.Control);
</code>```

Body:
How to change page zoom level in Selenium WebDriver?
I tried:

driver.Keyboard().pressKey(Keys.Control);
driver.Keyboard().pressKey(Keys.Add);

But it doesn't work.

Body:
11-17-2017 Update

var html = page.FindElement(By.XPath("/html"));
html.SendKeys(Keys.Control + "0" + Keys.Control);


问:
credentials used by google cloud dataflow
Currently have some confusion on the credentials/configuration used by dataflow...

From my experimentation, it seems that dataflow is always using the default configuration instead of the active configuration. Is that correct? (For example in my gcloud config if I have a default configuration with project A while my active configuration is on project B, it seems that my dataflow job will submit to project A always. Also in this way it seems that the dataflow job is ignoring what is set in options.setProject(), so sort of wondering when is dataflow using options.getProject() again...?)

And also wondering is there any way that I submit dataflow job with customized configuration, say I want to submit multiple jobs to different projects with different credentials on the same run(without manually changing my gcloud config)?

btw I am running the dataflow job on dataflow services cloud platform but submit the job from non-gce Cloudservices Account if it will make a difference.

答:
The code I used to have Dataflow populate its workers with the service account we wanted (in addition to Lukas answer above):</p>

```<code>final List<String> SCOPES = Arrays.asList(
      "https://www.googleapis.com/auth/cloud-platform",
      "https://www.googleapis.com/auth/devstorage.full_control",
      "https://www.googleapis.com/auth/userinfo.email",
      "https://www.googleapis.com/auth/datastore",
      "https://www.googleapis.com/auth/pubsub");
options.setGcpCredential(ServiceAccountCredentials.fromStream(new FileInputStream("key.json")).createScoped(SCOPES));
options.setServiceAccount("xxx@yyy.iam.gserviceaccount.com");
</code>```

Body:
The code I used to have Dataflow populate its workers with the service account we wanted (in addition to Lukas answer above):

final List<String> SCOPES = Arrays.asList(
      "https://www.googleapis.com/auth/cloud-platform",
      "https://www.googleapis.com/auth/devstorage.full_control",
      "https://www.googleapis.com/auth/userinfo.email",
      "https://www.googleapis.com/auth/datastore",
      "https://www.googleapis.com/auth/pubsub");
options.setGcpCredential(ServiceAccountCredentials.fromStream(new FileInputStream("key.json")).createScoped(SCOPES));
options.setServiceAccount("xxx@yyy.iam.gserviceaccount.com");


问:
Split lines in clojure while reading from file
I am learning clojure at school and I have an exam coming up. I was just working on a few things to make sure I get the hang of it.

I am trying to read from a file line by line and as I do, I want to split the line whenever there is a ";".

Here is my code so far

```<code>(defn readFile []
  (map (fn [line] (clojure.string/split line #";"))
  (with-open [rdr (reader "C:/Users/Rohil/Documents/work.txt.txt")]
    (doseq [line (line-seq rdr)]
      (clojure.string/split line #";")
        (println line)))))
</code>```

When I do this, I still get the output:

```<code>"I;Am;A;String;"
</code>```

Am I missing something?

答:
I'm not sure if you need this at school, but since Gary already gave an excellent answer, consider this as a bonus.

You can do elegant transformations on lines of text with transducers. The ingredient you need is something that allows you to treat the lines as a reducible collection and which closes the reader when you're done reducing:

```<code>(defn lines-reducible [^BufferedReader rdr]
  (reify clojure.lang.IReduceInit
    (reduce [this f init]
      (try
        (loop [state init]
          (if (reduced? state)
            @state
            (if-let [line (.readLine rdr)]
              (recur (f state line))
              state)))
        (finally
          (.close rdr))))))
</code>```

Now you're able to do the following, given input work.txt:

```<code>I;am;a;string
Next;line;please
</code>```

Count the length of each 'split'

```<code>(require '[clojure.string :as str])
(require '[clojure.java.io :as io])

(into []
      (comp
       (mapcat #(str/split % #";"))
       (map count))
      (lines-reducible (io/reader "/tmp/work.txt")))
;;=> [1 2 1 6 4 4 6]
</code>```

Sum the length of all 'splits'

```<code>(transduce
 (comp
  (mapcat #(str/split % #";"))
  (map count))
 +
 (lines-reducible (io/reader "/tmp/work.txt")))
;;=> 24
</code>```

Sum the length of all words until we find a word that is longer than 5

```<code>(transduce
 (comp
  (mapcat #(str/split % #";"))
  (map count))
 (fn
   ([] 0)
   ([sum] sum)
   ([sum l]
    (if (> l 5)
      (reduced sum)
      (+ sum l))))
 (lines-reducible (io/reader "/tmp/work.txt")))
</code>```

or with take-while:

```<code>(transduce
 (comp
  (mapcat #(str/split % #";"))
  (map count)
  (take-while #(> 5 %)))
 +
 (lines-reducible (io/reader "/tmp/work.txt")))
</code>```

Read https://tech.grammarly.com/blog/building-etl-pipelines-with-clojure for more details.

Body:
I am learning clojure at school and I have an exam coming up. I was just working on a few things to make sure I get the hang of it.

I am trying to read from a file line by line and as I do, I want to split the line whenever there is a ";".

Here is my code so far

(defn readFile []
  (map (fn [line] (clojure.string/split line #";"))
  (with-open [rdr (reader "C:/Users/Rohil/Documents/work.txt.txt")]
    (doseq [line (line-seq rdr)]
      (clojure.string/split line #";")
        (println line)))))

When I do this, I still get the output:

"I;Am;A;String;"

Am I missing something?

Body:
I'm not sure if you need this at school, but since Gary already gave an excellent answer, consider this as a bonus.

You can do elegant transformations on lines of text with transducers. The ingredient you need is something that allows you to treat the lines as a reducible collection and which closes the reader when you're done reducing:

(defn lines-reducible [^BufferedReader rdr]
  (reify clojure.lang.IReduceInit
    (reduce [this f init]
      (try
        (loop [state init]
          (if (reduced? state)
            @state
            (if-let [line (.readLine rdr)]
              (recur (f state line))
              state)))
        (finally
          (.close rdr))))))

Now you're able to do the following, given input work.txt:

I;am;a;string
Next;line;please

Count the length of each 'split'

(require '[clojure.string :as str])
(require '[clojure.java.io :as io])

(into []
      (comp
       (mapcat #(str/split % #";"))
       (map count))
      (lines-reducible (io/reader "/tmp/work.txt")))
;;=> [1 2 1 6 4 4 6]

Sum the length of all 'splits'

(transduce
 (comp
  (mapcat #(str/split % #";"))
  (map count))
 +
 (lines-reducible (io/reader "/tmp/work.txt")))
;;=> 24

Sum the length of all words until we find a word that is longer than 5

(transduce
 (comp
  (mapcat #(str/split % #";"))
  (map count))
 (fn
   ([] 0)
   ([sum] sum)
   ([sum l]
    (if (> l 5)
      (reduced sum)
      (+ sum l))))
 (lines-reducible (io/reader "/tmp/work.txt")))

or with take-while:

(transduce
 (comp
  (mapcat #(str/split % #";"))
  (map count)
  (take-while #(> 5 %)))
 +
 (lines-reducible (io/reader "/tmp/work.txt")))

Read https://tech.grammarly.com/blog/building-etl-pipelines-with-clojure for more details.


问:
SQL - select muliple rows if search criteria matches one of the Values
Apologies if already asked but not too sure what to search for. I want to select muliple LocaleIds if search criterial matches one of the Values.

Currently I am doing simple search like this:

```<code>SELECT *
   FROM [dbo].[Localizations]
   WHERE Value like 'task switching' OR ResourceId like 'task switching'
   ORDER BY LocaleId, ResourceId
</code>```

This results in:

```<code>Id      ResourceId                      Value            LocaleId
53591   AssessmentType_Description_21   Task Switching
53247   Attribute_Description_1         Task Switching
53378   Attribute_Description_132       Task Switching
</code>```

However this is missing the associated rows for the Other LocaleIds (English LocaleId is blank ' '). For example, I require:

```<code>Id      ResourceId                      Value                  LocaleId
53591   AssessmentType_Description_21   Task Switching
53247   Attribute_Description_1         Task Switching
53378   Attribute_Description_132       Task Switching
42257   AssessmentType_Description_21   Aufgabenwechsel         de
42839   Attribute_Description_1         Aufgabenwechsel         de
42876   Attribute_Description_132       Aufgabenwechsel         de
45864   AssessmentType_Description_21   Changement de tâches    fr
46446   Attribute_Description_1         Changement de tâches    fr
46483   Attribute_Description_132       Changement de tâches    fr
</code>```

How can I get the full results set for all LocaleIds? Any help appreciated.

Edit:
Sorry I want all the records that match 'Task switching' and their corresponding values in other languages. Will only ever be searching in 1 language.

答:
I hope this SQL will resolve Your Problem : </p>

```<code>SELECT * FROM [dbo].[Localizations]
WHERE ResourceId in (SELECT ResourceId
                     FROM [dbo].[Localizations]
                     WHERE Value like 'task switching')
ORDER BY LocaleId, ResourceId
</code>```

Body:
Apologies if already asked but not too sure what to search for. I want to select muliple LocaleIds if search criterial matches one of the Values.

Currently I am doing simple search like this:

SELECT *
   FROM [dbo].[Localizations]
   WHERE Value like 'task switching' OR ResourceId like 'task switching'
   ORDER BY LocaleId, ResourceId

This results in:

Id      ResourceId                      Value            LocaleId
53591   AssessmentType_Description_21   Task Switching
53247   Attribute_Description_1         Task Switching
53378   Attribute_Description_132       Task Switching

However this is missing the associated rows for the Other LocaleIds (English LocaleId is blank ' '). For example, I require:

Id      ResourceId                      Value                  LocaleId
53591   AssessmentType_Description_21   Task Switching
53247   Attribute_Description_1         Task Switching
53378   Attribute_Description_132       Task Switching
42257   AssessmentType_Description_21   Aufgabenwechsel         de
42839   Attribute_Description_1         Aufgabenwechsel         de
42876   Attribute_Description_132       Aufgabenwechsel         de
45864   AssessmentType_Description_21   Changement de tâches    fr
46446   Attribute_Description_1         Changement de tâches    fr
46483   Attribute_Description_132       Changement de tâches    fr

How can I get the full results set for all LocaleIds? Any help appreciated.

Edit:
Sorry I want all the records that match 'Task switching' and their corresponding values in other languages. Will only ever be searching in 1 language.

Body:
I hope this SQL will resolve Your Problem :

SELECT * FROM [dbo].[Localizations]
WHERE ResourceId in (SELECT ResourceId
                     FROM [dbo].[Localizations]
                     WHERE Value like 'task switching')
ORDER BY LocaleId, ResourceId


问:
Javascript if else timer on specific days
I am using this code

Here is a codePen to see it. https://codepen.io/celli/pen/jaBrpP But the console doesn't seem to log any of my if else statements, except for the first log. What is wrong in the code, where it is not firing each of my conditions ?

function showDateContent() {
  var d = new Date();
  console.log(d.getDate(), d.getMonth());
  if (d.getDate() >= 4 && d.getDate() <= 17 && d.getMonth() + 1 == 12) {
    console.log("date is between 12/4 and 12/17");
  } else if (d.getDate() >= 18 && d.getDate() <= 30 && d.getMonth() + 1 == 12) {
    console.log("date is between 12/18 and 12/30");
  } else if (d.getDate() >= 31 && d.getMonth() + 1 == 12 || d.getDate() >= 1 && d.getMonth() + 1 == 1) {
    console.log("date is after 12/31/2017 or we are in the New Year of 2018");
  }
}
showDateContent();```

答:
Current month is 11, getMonth() is  0 based index and offset by 1

```<code>if(d.getDate() >= 4 && d.getDate()<= 17 && d.getMonth()+1 == 11)
</code>```

function showDateContent(){
var d=new Date();

console.log(d.getDate(), d.getMonth());

if(d.getDate() >= 4 && d.getDate()<= 17 && d.getMonth()+1 == 11){
    console.log("date is between 12/4 and 12/17");

} else if(d.getDate() >= 18 && d.getDate()<= 30 && d.getMonth()+1 == 11){
    console.log("date is between 12/18 and 12/30");

} else if(d.getDate() >= 31 && d.getMonth()+1 == 12 || d.getDate() >= 1 && d.getMonth()+1 == 1){
    console.log("date is after 12/31/2017 or we are in the New Year of 2018");

}
}

showDateContent();```

Body:
Current month is 11, getMonth() is  0 based index and offset by 1

if(d.getDate() >= 4 && d.getDate()<= 17 && d.getMonth()+1 == 11)

function showDateContent(){
var d=new Date();

console.log(d.getDate(), d.getMonth());

if(d.getDate() >= 4 && d.getDate()<= 17 && d.getMonth()+1 == 11){
    console.log("date is between 12/4 and 12/17");

} else if(d.getDate() >= 18 && d.getDate()<= 30 && d.getMonth()+1 == 11){
    console.log("date is between 12/18 and 12/30");

} else if(d.getDate() >= 31 && d.getMonth()+1 == 12 || d.getDate() >= 1 && d.getMonth()+1 == 1){
    console.log("date is after 12/31/2017 or we are in the New Year of 2018");

}
}

showDateContent();


问:
Kafka topic not being deleted
I am using Kafka 0.10.0.1. There are 3 brokers in the cluster. I issued delete command to delete nearly 10 topics which were not getting used since a month. I had checked, there are no consumers registered on those topics, nor were their log sizes increasing. </p>

<p>However, it's been more than 5 hours and those topics haven't yet been deleted. They are just marked for deletion. What can be the reason? </p>

答:
By default in 0.10, delete.topic.enable is false. To be able to delete topics, you need to set this to true in the broker properties file.

Note that starting from 1.0.0, this is now enabled by default.

Title: Kafka topic not being deleted

Body:
I am using Kafka 0.10.0.1. There are 3 brokers in the cluster. I issued delete command to delete nearly 10 topics which were not getting used since a month. I had checked, there are no consumers registered on those topics, nor were their log sizes increasing.

However, it's been more than 5 hours and those topics haven't yet been deleted. They are just marked for deletion. What can be the reason?


问:
python + objectlistview + updatelist
I have an objectlistview. I remove a line from it and then I want to update the list without the removed line. I fill the list with data from a database. I tried repopulatelist, but then it seems to use the data that is already in the list.

I think I can solve it with clearAll (clearing the list) and then addobjects and add the database again. But it seems that it should be possible to just update the list. This is my code:

```<code>def deletemeas(self):

    MAid = self.objectma.id
    MAname = self.pagename

    objectsRemList = self.tempmeasurements.GetCheckedObjects()

    print 'objectremlist', objectsRemList
    for measurement in objectsRemList:
        print measurement
        Measname = measurement.filename
        Measid = database.Measurement.select(database.Measurement.q.filename == Measname)[0].id
        deleteMeas = []
        deleteMeas.append(MAid)
        deleteMeas.append(Measid)
        pub.sendMessage('DELETE_MEAS', Container(data=deleteMeas)) #to microanalyse controller
    #here I get the latest information from the database what should be viewed in the objectlist self.tempmeasurements
    MeasInListFromDB = list(database.Microanalysismeasurement.select(database.Microanalysismeasurement.q.microanalysisid == MAid))

    print 'lijstmetingen:', MeasInListFromDB
    #this doesn't work
    self.tempmeasurements.RefreshObjects(MeasInListFromDB)
</code>```

答:
Ok, this was actually easier than I thought ...

I added this line:

```<code>self.tempmeasurements.RemoveObject(measurement)
</code>```

So I first removed the data from my database table and then I just removed the line in my objectlistview.

Title: python + objectlistview + updatelist

Body:
I have an objectlistview. I remove a line from it and then I want to update the list without the removed line. I fill the list with data from a database. I tried repopulatelist, but then it seems to use the data that is already in the list.

I think I can solve it with clearAll (clearing the list) and then addobjects and add the database again. But it seems that it should be possible to just update the list. This is my code:

def deletemeas(self):

    MAid = self.objectma.id
    MAname = self.pagename

    objectsRemList = self.tempmeasurements.GetCheckedObjects()

    print 'objectremlist', objectsRemList
    for measurement in objectsRemList:
        print measurement
        Measname = measurement.filename
        Measid = database.Measurement.select(database.Measurement.q.filename == Measname)[0].id
        deleteMeas = []
        deleteMeas.append(MAid)
        deleteMeas.append(Measid)
        pub.sendMessage('DELETE_MEAS', Container(data=deleteMeas)) #to microanalyse controller
    #here I get the latest information from the database what should be viewed in the objectlist self.tempmeasurements
    MeasInListFromDB = list(database.Microanalysismeasurement.select(database.Microanalysismeasurement.q.microanalysisid == MAid))

    print 'lijstmetingen:', MeasInListFromDB
    #this doesn't work
    self.tempmeasurements.RefreshObjects(MeasInListFromDB)

Body:
Ok, this was actually easier than I thought ...

I added this line:

self.tempmeasurements.RemoveObject(measurement)

So I first removed the data from my database table and then I just removed the line in my objectlistview.


问:
is it possible for `ConcurrentHashMap` to hang?
First I'll summarize what I've found so far.

This answer suggests that changing the concurrencyLevel parameter of ConcurrentHashMap's constructor might help. I've tried that and my code still hanged.

Answers here suggest that it could be a runtime bug.

What I'm trying to do:

I have 10 worker threads running along with a main thread. The worker threads will have to process many arrays to find the index of the max element in the array (if there are multiple max values, the first occurrence will be used). Among these "many arrays," some of them can be duplicate, so I'm trying to avoid those full array scans to speed up the program.

The controller class contains a ConcurrentHashMap that maps the hash values of arrays to the corresponding max-element indices.

The worker threads will ask the controller class for the mapped index first before trying to calculate the index by doing full array scans. In the latter case, the newly calculated index will be put into the map.

The main thread does not access the hash map.

What happened:

My code will hang after 70,000 ~ 130,000 calls to getMaxIndex(). This count is obtained by putting a log string into getMaxIndex() so it might not be exactly accurate.

My CPU usage will gradually go up for ~6 seconds, and then it will go down to ~10% after peaked at ~100%. I have plenty of unused memory left. (Does this look like deadlock?)

If the code does not use map it works just fine (see getMaxIndex() version 2 below).

I've tried to add synchronized to getMaxIndex()'s signature and use the regular HashMap instead, that also did not work.

I've tried to use different initialCapacity values too (e.g. 50,000 & 100,000). Did not work.

Here's my code:

```<code>// in the controller class
int getMaxIndex(@NotNull double[] arr) {
    int hash = Arrays.hashCode(arr);

    if(maxIndices.containsKey(hash)) {
        return maxIndices.get(hash);
    } else {
        int maxIndex =
            IntStream.range(0, arr.length)
                .reduce((a, b) -> arr[a] < arr[b] ? b : a)
                .orElse(-1); // -1 to let program crash

        maxIndices.put(hash, maxIndex);
        return maxIndex;
    }
}
</code>```

The worker thread will call getMaxIndex() like this: return remaining[controller.getMaxIndex(arr)];, remaining is just another int array.

getMaxIndex() v2:

```<code>int getMaxIndex(@NotNull double[] arr) {
    return IntStream.range(0, arr.length)
        .reduce((a, b) -> arr[a] < arr[b] ? b : a)
        .orElse(-1); // -1 to let program crash
}
</code>```

JVM info in case it matters:

```<code>java version "1.8.0_151"
Java(TM) SE Runtime Environment (build 1.8.0_151-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.151-b12, mixed mode)
</code>```

EDIT: stack dump; I used Phaser to synchronize the worker threads, so some of them appear to be waiting on the phaser, but pool-1-thread-2, pool-1-thread-10, pool-1-thread-11, and pool-1-thread-12 do not appear to be waiting on the phaser.

```<code>Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.151-b12 mixed mode):

"Attach Listener" #23 daemon prio=9 os_prio=0 tid=0x00007f0c54001000 nid=0x4da2 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"pool-1-thread-13" #22 prio=5 os_prio=0 tid=0x00007f0c8c2cb800 nid=0x4d5e waiting on condition [0x00007f0c4eddd000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e792f40> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-12" #21 prio=5 os_prio=0 tid=0x00007f0c8c2ca000 nid=0x4d5d waiting on condition [0x00007f0c4eede000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-11" #20 prio=5 os_prio=0 tid=0x00007f0c8c2c8000 nid=0x4d5c waiting on condition [0x00007f0c4efdf000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-10" #19 prio=5 os_prio=0 tid=0x00007f0c8c2c6000 nid=0x4d5b waiting on condition [0x00007f0c4f0e0000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-9" #18 prio=5 os_prio=0 tid=0x00007f0c8c2c4800 nid=0x4d5a waiting on condition [0x00007f0c4f1e1000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e7c74f8> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-8" #17 prio=5 os_prio=0 tid=0x00007f0c8c2c2800 nid=0x4d59 waiting on condition [0x00007f0c4f2e2000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e64fb78> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-7" #16 prio=5 os_prio=0 tid=0x00007f0c8c2c1000 nid=0x4d58 waiting on condition [0x00007f0c4f3e3000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e8b44c8> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-6" #15 prio=5 os_prio=0 tid=0x00007f0c8c2bf800 nid=0x4d57 waiting on condition [0x00007f0c4f4e4000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e5b4500> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-5" #14 prio=5 os_prio=0 tid=0x00007f0c8c2bd800 nid=0x4d56 waiting on condition [0x00007f0c4f5e5000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e836958> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-4" #13 prio=5 os_prio=0 tid=0x00007f0c8c2bc000 nid=0x4d55 waiting on condition [0x00007f0c4f6e6000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e4f4cf0> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-3" #12 prio=5 os_prio=0 tid=0x00007f0c8c2ba000 nid=0x4d54 waiting on condition [0x00007f0c4f7e7000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e40abb8> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-2" #11 prio=5 os_prio=0 tid=0x00007f0c8c2b8800 nid=0x4d53 waiting on condition [0x00007f0c4f8e8000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-1" #10 prio=5 os_prio=0 tid=0x00007f0c8c2b5800 nid=0x4d52 waiting on condition [0x00007f0c4f9e9000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e486ab0> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"Service Thread" #9 daemon prio=9 os_prio=0 tid=0x00007f0c8c200800 nid=0x4d50 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C1 CompilerThread2" #8 daemon prio=9 os_prio=0 tid=0x00007f0c8c1fd800 nid=0x4d4f waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread1" #7 daemon prio=9 os_prio=0 tid=0x00007f0c8c1f8800 nid=0x4d4e waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread0" #6 daemon prio=9 os_prio=0 tid=0x00007f0c8c1f7800 nid=0x4d4d waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Monitor Ctrl-Break" #5 daemon prio=5 os_prio=0 tid=0x00007f0c8c1fb000 nid=0x4d4c runnable [0x00007f0c781b4000]
   java.lang.Thread.State: RUNNABLE
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
    at java.net.SocketInputStream.read(SocketInputStream.java:171)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    - locked <0x000000077550ecb0> (a java.io.InputStreamReader)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at java.io.BufferedReader.fill(BufferedReader.java:161)
    at java.io.BufferedReader.readLine(BufferedReader.java:324)
    - locked <0x000000077550ecb0> (a java.io.InputStreamReader)
    at java.io.BufferedReader.readLine(BufferedReader.java:389)
    at com.intellij.rt.execution.application.AppMainV2$1.run(AppMainV2.java:64)

"Signal Dispatcher" #4 daemon prio=9 os_prio=0 tid=0x00007f0c8c181000 nid=0x4d49 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Finalizer" #3 daemon prio=8 os_prio=0 tid=0x00007f0c8c14d800 nid=0x4d42 in Object.wait() [0x00007f0c78564000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x0000000775500d08> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
    - locked <0x0000000775500d08> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
    at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)

"Reference Handler" #2 daemon prio=10 os_prio=0 tid=0x00007f0c8c149000 nid=0x4d41 in Object.wait() [0x00007f0c78665000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x0000000775500d48> (a java.lang.ref.Reference$Lock)
    at java.lang.Object.wait(Object.java:502)
    at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
    - locked <0x0000000775500d48> (a java.lang.ref.Reference$Lock)
    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)

"main" #1 prio=5 os_prio=0 tid=0x00007f0c8c00c800 nid=0x4d35 waiting on condition [0x00007f0c91f77000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076dd5e268> (a java.util.concurrent.FutureTask)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.FutureTask.awaitDone(FutureTask.java:429)
    at java.util.concurrent.FutureTask.get(FutureTask.java:191)
    at java.util.concurrent.AbstractExecutorService.invokeAll(AbstractExecutorService.java:244)
    at ConcurrentACS.loop(ConcurrentACS.java:138)
    at ConcurrentACS.compute(ConcurrentACS.java:165)
    at ConcurrentACS.main(ConcurrentACS.java:192)

"VM Thread" os_prio=0 tid=0x00007f0c8c141800 nid=0x4d3f runnable

"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00007f0c8c022000 nid=0x4d37 runnable

"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00007f0c8c024000 nid=0x4d38 runnable

"GC task thread#2 (ParallelGC)" os_prio=0 tid=0x00007f0c8c025800 nid=0x4d39 runnable

"GC task thread#3 (ParallelGC)" os_prio=0 tid=0x00007f0c8c027800 nid=0x4d3a runnable

"VM Periodic Task Thread" os_prio=0 tid=0x00007f0c8c205800 nid=0x4d51 waiting on condition

JNI global references: 272
</code>```

答:
is it possible for ConcurrentHashMap to hang?

The short answer is no if by "hang" you mean some sort of program loop or deadlock.  If you are implying that you have discovered a race condition (bug) in that code that would cause it to hang during normal JVM and system execution then I seriously doubt it.

I suspect that there is something else going on and just because you are using a CHM in the version that is hanging shouldn't imply that the class has a bug.  I would use stack dumps or a profiler to show that the code is locked on a CHM line before I'd cast any blame that way.

Is it possible to be calling CHM at some large number of times per second so that the performance of your program suffers because of it?  Sure.  But it wouldn't hang in that it is stuck or deadlocked.

My CPU usage will gradually go up for ~6 seconds, and then it will go down to ~10% after peaked at ~100%. I have plenty of unused memory left. (Does this look like deadlock?)

Your now posted stack trace shows that no threads are locked in CHM code so it doesn't look to be the problem.  The performance curve you are talking about seems to be happening because of the fork/join thread-pool that you are using initially starts X threads but then some of them finish their tasks and exit.  This is to be expected.  It has nothing to do with the CHM.

```<code>if(maxIndices.containsKey(hash)) {
   return maxIndices.get(hash);
</code>```

Just a quick comment.  This code makes 2 calls to the CHM instead of something like:

```<code>Integer maxIndex = maxIndices.get(hash);
if (maxIndex != null) {
   return maxIndex;
}
...
</code>```

But that's just inefficient and wouldn't cause a bug.  Also, it is important to recognize that race conditions in your code means that multiple threads might get a null for the index and calculate the index value.  But also this is not a bug which would cause a "hang".

Body:
First I'll summarize what I've found so far.

This answer suggests that changing the concurrencyLevel parameter of ConcurrentHashMap's constructor might help. I've tried that and my code still hanged.

Answers here suggest that it could be a runtime bug.

What I'm trying to do:

I have 10 worker threads running along with a main thread. The worker threads will have to process many arrays to find the index of the max element in the array (if there are multiple max values, the first occurrence will be used). Among these "many arrays," some of them can be duplicate, so I'm trying to avoid those full array scans to speed up the program.

The controller class contains a ConcurrentHashMap that maps the hash values of arrays to the corresponding max-element indices.

The worker threads will ask the controller class for the mapped index first before trying to calculate the index by doing full array scans. In the latter case, the newly calculated index will be put into the map.

The main thread does not access the hash map.

What happened:

My code will hang after 70,000 ~ 130,000 calls to getMaxIndex(). This count is obtained by putting a log string into getMaxIndex() so it might not be exactly accurate.

My CPU usage will gradually go up for ~6 seconds, and then it will go down to ~10% after peaked at ~100%. I have plenty of unused memory left. (Does this look like deadlock?)

If the code does not use map it works just fine (see getMaxIndex() version 2 below).

I've tried to add synchronized to getMaxIndex()'s signature and use the regular HashMap instead, that also did not work.

I've tried to use different initialCapacity values too (e.g. 50,000 & 100,000). Did not work.

Here's my code:

// in the controller class
int getMaxIndex(@NotNull double[] arr) {
    int hash = Arrays.hashCode(arr);

    if(maxIndices.containsKey(hash)) {
        return maxIndices.get(hash);
    } else {
        int maxIndex =
            IntStream.range(0, arr.length)
                .reduce((a, b) -> arr[a] < arr[b] ? b : a)
                .orElse(-1); // -1 to let program crash

        maxIndices.put(hash, maxIndex);
        return maxIndex;
    }
}

The worker thread will call getMaxIndex() like this: return remaining[controller.getMaxIndex(arr)];, remaining is just another int array.

getMaxIndex() v2:

int getMaxIndex(@NotNull double[] arr) {
    return IntStream.range(0, arr.length)
        .reduce((a, b) -> arr[a] < arr[b] ? b : a)
        .orElse(-1); // -1 to let program crash
}

JVM info in case it matters:

java version "1.8.0_151"
Java(TM) SE Runtime Environment (build 1.8.0_151-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.151-b12, mixed mode)

EDIT: stack dump; I used Phaser to synchronize the worker threads, so some of them appear to be waiting on the phaser, but pool-1-thread-2, pool-1-thread-10, pool-1-thread-11, and pool-1-thread-12 do not appear to be waiting on the phaser.

Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.151-b12 mixed mode):

"Attach Listener" #23 daemon prio=9 os_prio=0 tid=0x00007f0c54001000 nid=0x4da2 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"pool-1-thread-13" #22 prio=5 os_prio=0 tid=0x00007f0c8c2cb800 nid=0x4d5e waiting on condition [0x00007f0c4eddd000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e792f40> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-12" #21 prio=5 os_prio=0 tid=0x00007f0c8c2ca000 nid=0x4d5d waiting on condition [0x00007f0c4eede000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-11" #20 prio=5 os_prio=0 tid=0x00007f0c8c2c8000 nid=0x4d5c waiting on condition [0x00007f0c4efdf000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-10" #19 prio=5 os_prio=0 tid=0x00007f0c8c2c6000 nid=0x4d5b waiting on condition [0x00007f0c4f0e0000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-9" #18 prio=5 os_prio=0 tid=0x00007f0c8c2c4800 nid=0x4d5a waiting on condition [0x00007f0c4f1e1000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e7c74f8> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-8" #17 prio=5 os_prio=0 tid=0x00007f0c8c2c2800 nid=0x4d59 waiting on condition [0x00007f0c4f2e2000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e64fb78> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-7" #16 prio=5 os_prio=0 tid=0x00007f0c8c2c1000 nid=0x4d58 waiting on condition [0x00007f0c4f3e3000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e8b44c8> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-6" #15 prio=5 os_prio=0 tid=0x00007f0c8c2bf800 nid=0x4d57 waiting on condition [0x00007f0c4f4e4000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e5b4500> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-5" #14 prio=5 os_prio=0 tid=0x00007f0c8c2bd800 nid=0x4d56 waiting on condition [0x00007f0c4f5e5000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e836958> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-4" #13 prio=5 os_prio=0 tid=0x00007f0c8c2bc000 nid=0x4d55 waiting on condition [0x00007f0c4f6e6000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e4f4cf0> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-3" #12 prio=5 os_prio=0 tid=0x00007f0c8c2ba000 nid=0x4d54 waiting on condition [0x00007f0c4f7e7000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e40abb8> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-2" #11 prio=5 os_prio=0 tid=0x00007f0c8c2b8800 nid=0x4d53 waiting on condition [0x00007f0c4f8e8000]
   java.lang.Thread.State: TIMED_WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000775518738> (a java.util.concurrent.SynchronousQueue$TransferStack)
    at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
    at java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
    at java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
    at java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
    at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1073)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1134)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"pool-1-thread-1" #10 prio=5 os_prio=0 tid=0x00007f0c8c2b5800 nid=0x4d52 waiting on condition [0x00007f0c4f9e9000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076e486ab0> (a java.util.concurrent.Phaser$QNode)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.Phaser$QNode.block(Phaser.java:1140)
    at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
    at java.util.concurrent.Phaser.internalAwaitAdvance(Phaser.java:1067)
    at java.util.concurrent.Phaser.arriveAndAwaitAdvance(Phaser.java:690)
    at Ant.call(Ant.java:77)
    at Ant.call(Ant.java:10)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

"Service Thread" #9 daemon prio=9 os_prio=0 tid=0x00007f0c8c200800 nid=0x4d50 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C1 CompilerThread2" #8 daemon prio=9 os_prio=0 tid=0x00007f0c8c1fd800 nid=0x4d4f waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread1" #7 daemon prio=9 os_prio=0 tid=0x00007f0c8c1f8800 nid=0x4d4e waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread0" #6 daemon prio=9 os_prio=0 tid=0x00007f0c8c1f7800 nid=0x4d4d waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Monitor Ctrl-Break" #5 daemon prio=5 os_prio=0 tid=0x00007f0c8c1fb000 nid=0x4d4c runnable [0x00007f0c781b4000]
   java.lang.Thread.State: RUNNABLE
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
    at java.net.SocketInputStream.read(SocketInputStream.java:171)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    - locked <0x000000077550ecb0> (a java.io.InputStreamReader)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at java.io.BufferedReader.fill(BufferedReader.java:161)
    at java.io.BufferedReader.readLine(BufferedReader.java:324)
    - locked <0x000000077550ecb0> (a java.io.InputStreamReader)
    at java.io.BufferedReader.readLine(BufferedReader.java:389)
    at com.intellij.rt.execution.application.AppMainV2$1.run(AppMainV2.java:64)

"Signal Dispatcher" #4 daemon prio=9 os_prio=0 tid=0x00007f0c8c181000 nid=0x4d49 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Finalizer" #3 daemon prio=8 os_prio=0 tid=0x00007f0c8c14d800 nid=0x4d42 in Object.wait() [0x00007f0c78564000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x0000000775500d08> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
    - locked <0x0000000775500d08> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
    at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)

"Reference Handler" #2 daemon prio=10 os_prio=0 tid=0x00007f0c8c149000 nid=0x4d41 in Object.wait() [0x00007f0c78665000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x0000000775500d48> (a java.lang.ref.Reference$Lock)
    at java.lang.Object.wait(Object.java:502)
    at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
    - locked <0x0000000775500d48> (a java.lang.ref.Reference$Lock)
    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)

"main" #1 prio=5 os_prio=0 tid=0x00007f0c8c00c800 nid=0x4d35 waiting on condition [0x00007f0c91f77000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x000000076dd5e268> (a java.util.concurrent.FutureTask)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
    at java.util.concurrent.FutureTask.awaitDone(FutureTask.java:429)
    at java.util.concurrent.FutureTask.get(FutureTask.java:191)
    at java.util.concurrent.AbstractExecutorService.invokeAll(AbstractExecutorService.java:244)
    at ConcurrentACS.loop(ConcurrentACS.java:138)
    at ConcurrentACS.compute(ConcurrentACS.java:165)
    at ConcurrentACS.main(ConcurrentACS.java:192)

"VM Thread" os_prio=0 tid=0x00007f0c8c141800 nid=0x4d3f runnable

"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00007f0c8c022000 nid=0x4d37 runnable

"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00007f0c8c024000 nid=0x4d38 runnable

"GC task thread#2 (ParallelGC)" os_prio=0 tid=0x00007f0c8c025800 nid=0x4d39 runnable

"GC task thread#3 (ParallelGC)" os_prio=0 tid=0x00007f0c8c027800 nid=0x4d3a runnable

"VM Periodic Task Thread" os_prio=0 tid=0x00007f0c8c205800 nid=0x4d51 waiting on condition

JNI global references: 272

Body:
is it possible for ConcurrentHashMap to hang?

The short answer is no if by "hang" you mean some sort of program loop or deadlock.  If you are implying that you have discovered a race condition (bug) in that code that would cause it to hang during normal JVM and system execution then I seriously doubt it.

I suspect that there is something else going on and just because you are using a CHM in the version that is hanging shouldn't imply that the class has a bug.  I would use stack dumps or a profiler to show that the code is locked on a CHM line before I'd cast any blame that way.

Is it possible to be calling CHM at some large number of times per second so that the performance of your program suffers because of it?  Sure.  But it wouldn't hang in that it is stuck or deadlocked.

My CPU usage will gradually go up for ~6 seconds, and then it will go down to ~10% after peaked at ~100%. I have plenty of unused memory left. (Does this look like deadlock?)

Your now posted stack trace shows that no threads are locked in CHM code so it doesn't look to be the problem.  The performance curve you are talking about seems to be happening because of the fork/join thread-pool that you are using initially starts X threads but then some of them finish their tasks and exit.  This is to be expected.  It has nothing to do with the CHM.

if(maxIndices.containsKey(hash)) {
   return maxIndices.get(hash);

Just a quick comment.  This code makes 2 calls to the CHM instead of something like:

Integer maxIndex = maxIndices.get(hash);
if (maxIndex != null) {
   return maxIndex;
}
...

But that's just inefficient and wouldn't cause a bug.  Also, it is important to recognize that race conditions in your code means that multiple threads might get a null for the index and calculate the index value.  But also this is not a bug which would cause a "hang".


问:
Somehow send command line commands on windows externally and get back the response
Problem: Need to convert local html (with local images etc) to pdf from an AIX box running Universe 11.2.5 with System Builder

Current solution: FTP over html file to a Windows server which converts in batches and sends the e-mail to the destination

Proposed Solution: Do everything on the AIX box, from converting html to pdf and sending the e-mail.

Current problem: Unable to find a way to convert local html to PDF on the AIX box. I have been trying many different ways from trying to install Python3, but to no avail.

答:
The only really difficult part of the process is getting the HTML to render into a format will properly display your html into pages that are suitable for printing. There is a fair amount of magic that goes on between HTTP:GET and clicking print on a browser window that needs to be accounted for.

I was trying accomplish something similar many moons ago on AIX but kind of ran into a skill level/time wall because I was going to have essentially create a headless browser to render the html. It looks like there are now some utilities that you might be able to leverage. I found this recent updated article on Super User that actually got me somewhat excited, especially since I don't use AIX anymore so precompiled binaries and well understood and easily attainable dependencies are something I can actually have in my life.

https://superuser.com/questions/280552/how-can-i-render-a-website-as-an-image-from-the-shell

Good Luck.