google / guava

Google core libraries for Java
Apache License 2.0
50.25k stars 10.91k forks source link

HashBasedTable defined more map type #7496

Closed qiuhuanhen closed 3 weeks ago

qiuhuanhen commented 1 month ago

API(s)

com.google.common.collect.HashBasedTable#create()

How do you want it to be improved?

add create method which provider map param, such as

HashBasedTable.create(new ConcurrentHashMap()); and keep the NoArgs method

Why do we need it to be improved?

create() use linkedHashMap by default, but sometimes we might want to thread-safe . It seems HashBaseTable#put use Map#put , so I wonder it could suitable if provier a map param

Example

HashBasedTable.create(new ConcurrentHashMap());

Current Behavior

put table data

Desired Behavior

put table data and keep safety (by developer)

Concrete Use Cases

put oper in thread pool

`ExecutorService executorService = Executors.newFixedThreadPool(100); executorService.execute( ()->{ // HashBasedTable<String,Integer,Integer> urlTable = HashBasedTable.create();

                        urlTable.put(url+"_"+method,maxRequest,timeWindow);
                    }
            );`

Checklist

cpovirk commented 3 weeks ago

In order to have a thread-safe Table implementation, you need more than a thread-safe backing map. That's because Table needs to keep multiple things in sync, such as keeping the size field in sync with with map contents.

There might be fancy ways to do that, and I think someone once experimented with something similar for Multimap. My recollection is that it ended up being both slower and more memory-hungry than if you just used locking around all accesses to the collection.

So locking is one option. (We generally recommend that you lock yourself, rather than use Tables.synchronizedTable, so that you are forced to consider whether to take the lock once for a series of operations.)

Another option is to build your own Table-like structure out of nested ConcurrentHashMap objects or out of a single ConcurrentHashMap whose keys contain all the information (in your case, URL, method, and max request).

You'll have to decide based on what kinds of views of the Table you need (like column) and based on how the options perform in your case.